repo_name stringlengths 7 65 | path stringlengths 5 185 | copies stringlengths 1 4 | size stringlengths 4 6 | content stringlengths 977 990k | license stringclasses 14 values | hash stringlengths 32 32 | line_mean float64 7.18 99.4 | line_max int64 31 999 | alpha_frac float64 0.25 0.95 | ratio float64 1.5 7.84 | autogenerated bool 1 class | config_or_test bool 2 classes | has_no_keywords bool 2 classes | has_few_assignments bool 1 class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
abhinavsingh/proxy.py | proxy/core/base/tcp_server.py | 1 | 8417 | # -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE for more details.
.. spelling::
tcp
"""
import socket
import logging
import selectors
from abc import abstractmethod
from typing import Any, TypeVar, Optional
from ...core.work import Work
from ...common.flag import flags
from ...common.types import (
Readables, Writables, TcpOrTlsSocket, SelectableEvents,
)
from ...common.utils import wrap_socket
from ...core.connection import TcpClientConnection
from ...common.constants import (
DEFAULT_TIMEOUT, DEFAULT_KEY_FILE, DEFAULT_CERT_FILE,
DEFAULT_MAX_SEND_SIZE, DEFAULT_CLIENT_RECVBUF_SIZE,
DEFAULT_SERVER_RECVBUF_SIZE,
)
logger = logging.getLogger(__name__)
flags.add_argument(
'--key-file',
type=str,
default=DEFAULT_KEY_FILE,
help='Default: None. Server key file to enable end-to-end TLS encryption with clients. '
'If used, must also pass --cert-file.',
)
flags.add_argument(
'--cert-file',
type=str,
default=DEFAULT_CERT_FILE,
help='Default: None. Server certificate to enable end-to-end TLS encryption with clients. '
'If used, must also pass --key-file.',
)
flags.add_argument(
'--client-recvbuf-size',
type=int,
default=DEFAULT_CLIENT_RECVBUF_SIZE,
help='Default: ' + str(int(DEFAULT_CLIENT_RECVBUF_SIZE / 1024)) +
' KB. Maximum amount of data received from the '
'client in a single recv() operation.',
)
flags.add_argument(
'--server-recvbuf-size',
type=int,
default=DEFAULT_SERVER_RECVBUF_SIZE,
help='Default: ' + str(int(DEFAULT_SERVER_RECVBUF_SIZE / 1024)) +
' KB. Maximum amount of data received from the '
'server in a single recv() operation.',
)
flags.add_argument(
'--max-sendbuf-size',
type=int,
default=DEFAULT_MAX_SEND_SIZE,
help='Default: ' + str(int(DEFAULT_MAX_SEND_SIZE / 1024)) +
' KB. Maximum amount of data to flush in a single send() operation.',
)
flags.add_argument(
'--timeout',
type=int,
default=DEFAULT_TIMEOUT,
help='Default: ' + str(DEFAULT_TIMEOUT) +
'. Number of seconds after which '
'an inactive connection must be dropped. Inactivity is defined by no '
'data sent or received by the client.',
)
T = TypeVar('T', bound=TcpClientConnection)
class BaseTcpServerHandler(Work[T]):
"""BaseTcpServerHandler implements Work interface.
BaseTcpServerHandler lifecycle is controlled by Threadless core
using asyncio. If you want to also support threaded mode, also
implement the optional run() method from Work class.
An instance of BaseTcpServerHandler is created for each client
connection. BaseTcpServerHandler ensures that server is always
ready to accept new data from the client. It also ensures, client
is ready to accept new data before flushing data to it.
Most importantly, BaseTcpServerHandler ensures that pending buffers
to the client are flushed before connection is closed.
Implementations must provide::
a. handle_data(data: memoryview) implementation
b. Optionally, also implement other Work method
e.g. initialize, is_inactive, shutdown
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.must_flush_before_shutdown = False
logger.debug(
'Work#%d accepted from %s',
self.work.connection.fileno(),
self.work.address,
)
def initialize(self) -> None:
"""Optionally upgrades connection to HTTPS,
sets ``conn`` in non-blocking mode and initializes
HTTP protocol plugins."""
conn = self._optionally_wrap_socket(self.work.connection)
conn.setblocking(False)
logger.debug('Handling connection %s' % self.work.address)
@abstractmethod
def handle_data(self, data: memoryview) -> Optional[bool]:
"""Optionally return True to close client connection."""
pass # pragma: no cover
async def get_events(self) -> SelectableEvents:
events = {}
# We always want to read from client
# Register for EVENT_READ events
if self.must_flush_before_shutdown is False:
events[self.work.connection.fileno()] = selectors.EVENT_READ
# If there is pending buffer for client
# also register for EVENT_WRITE events
if self.work.has_buffer():
if self.work.connection.fileno() in events:
events[self.work.connection.fileno()] |= selectors.EVENT_WRITE
else:
events[self.work.connection.fileno()] = selectors.EVENT_WRITE
return events
async def handle_events(
self,
readables: Readables,
writables: Writables,
) -> bool:
"""Return True to shutdown work."""
teardown = await self.handle_writables(
writables,
) or await self.handle_readables(readables)
if teardown:
logger.debug(
'Shutting down client {0} connection'.format(
self.work.address,
),
)
return teardown
async def handle_writables(self, writables: Writables) -> bool:
teardown = False
if self.work.connection.fileno() in writables and self.work.has_buffer():
logger.debug(
'Flushing buffer to client {0}'.format(self.work.address),
)
self.work.flush(self.flags.max_sendbuf_size)
if self.must_flush_before_shutdown is True and \
not self.work.has_buffer():
teardown = True
self.must_flush_before_shutdown = False
return teardown
async def handle_readables(self, readables: Readables) -> bool:
teardown = False
if self.work.connection.fileno() in readables:
try:
data = self.work.recv(self.flags.client_recvbuf_size)
except ConnectionResetError:
logger.info(
'Connection reset by client {0}'.format(
self.work.address,
),
)
return True
except TimeoutError:
logger.info(
'Client recv timeout error {0}'.format(
self.work.address,
),
)
return True
if data is None:
logger.debug(
'Connection closed by client {0}'.format(
self.work.address,
),
)
teardown = True
else:
r = self.handle_data(data)
if isinstance(r, bool) and r is True:
logger.debug(
'Implementation signaled shutdown for client {0}'.format(
self.work.address,
),
)
if self.work.has_buffer():
logger.debug(
'Client {0} has pending buffer, will be flushed before shutting down'.format(
self.work.address,
),
)
self.must_flush_before_shutdown = True
else:
teardown = True
return teardown
def _encryption_enabled(self) -> bool:
return self.flags.keyfile is not None and \
self.flags.certfile is not None
def _optionally_wrap_socket(self, conn: socket.socket) -> TcpOrTlsSocket:
"""Attempts to wrap accepted client connection using provided certificates.
Shutdown and closes client connection upon error.
"""
if self._encryption_enabled():
assert self.flags.keyfile and self.flags.certfile
# TODO(abhinavsingh): Insecure TLS versions must not be accepted by default
conn = wrap_socket(conn, self.flags.keyfile, self.flags.certfile)
self.work._conn = conn
return conn
| bsd-3-clause | 355b4bc738318640d62d4abebea66a0c | 33.756198 | 105 | 0.594697 | 4.342282 | false | false | false | false |
abhinavsingh/proxy.py | proxy/core/event/dispatcher.py | 1 | 4706 | # -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE for more details.
"""
import queue
import logging
import threading
from typing import Any, Dict, List
from multiprocessing import connection
from .names import eventNames
from .queue import EventQueue
logger = logging.getLogger(__name__)
class EventDispatcher:
"""Core EventDispatcher.
Direct consuming from global events queue outside of dispatcher
module is not-recommended. Python native multiprocessing queue
doesn't provide a fanout functionality which core dispatcher module
implements so that several plugins can consume the same published
event concurrently (when necessary).
When --enable-events is used, a multiprocessing.Queue is created and
attached to global flags. This queue can then be used for
dispatching an Event dict object into the queue.
When --enable-events is used, dispatcher module is automatically
started. Most importantly, dispatcher module ensures that queue is
not flooded and doesn't utilize too much memory in case there are no
event subscribers for published messages.
EventDispatcher ensures that subscribers will receive the messages
in the order they are published.
"""
def __init__(
self,
shutdown: threading.Event,
event_queue: EventQueue,
) -> None:
self.shutdown: threading.Event = shutdown
self.event_queue: EventQueue = event_queue
# subscriber connection objects
self.subscribers: Dict[str, connection.Connection] = {}
def handle_event(self, ev: Dict[str, Any]) -> None:
if ev['event_name'] == eventNames.SUBSCRIBE:
sub_id = ev['event_payload']['sub_id']
self.subscribers[sub_id] = ev['event_payload']['conn']
# send ack
if not self._send(
sub_id, {
'event_name': eventNames.SUBSCRIBED,
},
):
self._close_and_delete(sub_id)
elif ev['event_name'] == eventNames.UNSUBSCRIBE:
sub_id = ev['event_payload']['sub_id']
if sub_id in self.subscribers:
# send ack
logger.debug('unsubscription request ack sent')
self._send(
sub_id, {
'event_name': eventNames.UNSUBSCRIBED,
},
)
self._close_and_delete(sub_id)
else:
logger.info(
'unsubscription request ack not sent, subscriber already gone',
)
else:
# logger.info(ev)
self._broadcast(ev)
def run_once(self) -> None:
ev: Dict[str, Any] = self.event_queue.queue.get(timeout=1)
self.handle_event(ev)
def run(self) -> None:
try:
while not self.shutdown.is_set():
try:
self.run_once()
except queue.Empty:
pass
except KeyboardInterrupt:
pass
except Exception as e:
logger.exception('Dispatcher exception', exc_info=e)
finally:
# Send shutdown message to all active subscribers
self._broadcast({
'event_name': eventNames.DISPATCHER_SHUTDOWN,
})
logger.info('Dispatcher shutdown')
def _broadcast(self, ev: Dict[str, Any]) -> None:
broken_pipes: List[str] = []
for sub_id in self.subscribers:
try:
self.subscribers[sub_id].send(ev)
except BrokenPipeError:
logger.warning(
'Subscriber#%s broken pipe', sub_id,
)
self._close(sub_id)
broken_pipes.append(sub_id)
for sub_id in broken_pipes:
del self.subscribers[sub_id]
def _close_and_delete(self, sub_id: str) -> None:
self._close(sub_id)
del self.subscribers[sub_id]
def _close(self, sub_id: str) -> None:
try:
self.subscribers[sub_id].close()
except Exception: # noqa: S110
pass
def _send(self, sub_id: str, payload: Any) -> bool:
done = False
try:
self.subscribers[sub_id].send(payload)
done = True
except (BrokenPipeError, EOFError):
pass
return done
| bsd-3-clause | 8cbce45edbe7592c560e58be01f6714a | 32.81295 | 86 | 0.575319 | 4.392523 | false | false | false | false |
abhinavsingh/proxy.py | proxy/core/work/task/remote.py | 1 | 1297 | # -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE for more details.
"""
import time
import uuid
import multiprocessing
from typing import Any
from ..remote import BaseRemoteExecutor
class RemoteTaskExecutor(BaseRemoteExecutor):
def work(self, *args: Any) -> None:
task_id = int(time.time())
uid = '%s-%s' % (self.iid, task_id)
self.works[task_id] = self.create(uid, *args)
class SingleProcessTaskExecutor(multiprocessing.Process):
def __init__(self, **kwargs: Any) -> None:
super().__init__()
self.daemon = True
self.work_queue, remote = multiprocessing.Pipe()
self.executor = RemoteTaskExecutor(
iid=uuid.uuid4().hex,
work_queue=remote,
**kwargs,
)
def __enter__(self) -> 'SingleProcessTaskExecutor':
self.start()
return self
def __exit__(self, *args: Any) -> None:
self.executor.running.set()
self.join()
def run(self) -> None:
self.executor.run()
| bsd-3-clause | 7037f08bd495b595c03c76fef23ce112 | 25.895833 | 86 | 0.615027 | 3.752907 | false | false | false | false |
abhinavsingh/proxy.py | proxy/core/tls/tls.py | 1 | 2493 | # -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE for more details.
"""
import struct
import logging
from typing import Tuple, Optional
from .types import tlsContentType
from .handshake import TlsHandshake
from .certificate import TlsCertificate
logger = logging.getLogger(__name__)
class TlsParser:
"""TLS packet parser"""
def __init__(self) -> None:
self.content_type: int = tlsContentType.OTHER
self.protocol_version: Optional[bytes] = None
self.length: Optional[bytes] = None
# only parse hand shake payload temporary
self.handshake: Optional[TlsHandshake] = None
self.certificate: Optional[TlsCertificate]
def parse(self, raw: bytes) -> Tuple[bool, bytes]:
"""Parse TLS fragmentation.
References
https://datatracker.ietf.org/doc/html/rfc5246#page-15
https://datatracker.ietf.org/doc/html/rfc5077#page-3
https://datatracker.ietf.org/doc/html/rfc8446#page-10
"""
length = len(raw)
if length < 5:
logger.debug('invalid data, len(raw) = %s', length)
return False, raw
payload_length, = struct.unpack('!H', raw[3:5])
if length < 5 + payload_length:
logger.debug(
'incomplete data, len(raw) = %s, len(payload) = %s', length, payload_length,
)
return False, raw
# parse
self.content_type = raw[0]
self.protocol_version = raw[1:3]
self.length = raw[3:5]
payload = raw[5:5 + payload_length]
if self.content_type == tlsContentType.HANDSHAKE:
# parse handshake
self.handshake = TlsHandshake()
self.handshake.parse(payload)
return True, raw[5 + payload_length:]
def build(self) -> bytes:
data = b''
data += bytes([self.content_type])
assert self.protocol_version
data += self.protocol_version
payload = b''
if self.content_type == tlsContentType.HANDSHAKE:
assert self.handshake
payload += self.handshake.build()
length = struct.pack('!H', len(payload))
data += length
data += payload
return data
| bsd-3-clause | 9b05c337fa8a80bae8be0c62bbcb9563 | 31.723684 | 92 | 0.607961 | 3.910377 | false | false | false | false |
abhinavsingh/proxy.py | proxy/core/base/tcp_upstream.py | 1 | 4399 | # -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE for more details.
"""
import ssl
import logging
from abc import ABC, abstractmethod
from typing import Any, Optional
from ...common.types import Readables, Writables, Descriptors
from ...core.connection import TcpServerConnection
logger = logging.getLogger(__name__)
class TcpUpstreamConnectionHandler(ABC):
""":class:`~proxy.core.base.TcpUpstreamConnectionHandler` can
be used to insert an upstream server connection lifecycle.
Call `initialize_upstream` to initialize the upstream connection object.
Then, directly use ``self.upstream`` object within your class.
See :class:`~proxy.plugin.proxy_pool.ProxyPoolPlugin` for example usage.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
# This is currently a hack, see comments below for rationale,
# will be fixed later.
super().__init__(*args, **kwargs) # type: ignore
self.upstream: Optional[TcpServerConnection] = None
# TODO: Currently, :class:`~proxy.core.base.TcpUpstreamConnectionHandler`
# is used within :class:`~proxy.http.server.ReverseProxy` and
# :class:`~proxy.plugin.ProxyPoolPlugin`.
#
# For both of which we expect a 4-tuple as arguments
# containing (uuid, flags, client, event_queue).
# We really don't need the rest of the args here.
# May be uuid? May be event_queue in the future.
# But certainly we don't not client here.
# A separate tunnel class must be created which handles
# client connection too.
#
# Both :class:`~proxy.http.server.ReverseProxy` and
# :class:`~proxy.plugin.ProxyPoolPlugin` are currently
# calling client queue within `handle_upstream_data` callback.
#
# This can be abstracted out too.
self.server_recvbuf_size = args[1].server_recvbuf_size
self.total_size = 0
@abstractmethod
def handle_upstream_data(self, raw: memoryview) -> None:
raise NotImplementedError() # pragma: no cover
def initialize_upstream(self, addr: str, port: int) -> None:
self.upstream = TcpServerConnection(addr, port)
async def get_descriptors(self) -> Descriptors:
if not self.upstream:
return [], []
return [self.upstream.connection.fileno()], \
[self.upstream.connection.fileno()] \
if self.upstream.has_buffer() \
else []
async def read_from_descriptors(self, r: Readables) -> bool:
if self.upstream and \
self.upstream.connection.fileno() in r:
try:
raw = self.upstream.recv(self.server_recvbuf_size)
if raw is None: # pragma: no cover
# Tear down because upstream proxy closed the connection
return True
self.total_size += len(raw)
self.handle_upstream_data(raw)
except TimeoutError: # pragma: no cover
logger.info('Upstream recv timeout error')
return True
except ssl.SSLWantReadError: # pragma: no cover
logger.info('Upstream SSLWantReadError, will retry')
return False
except ConnectionResetError: # pragma: no cover
logger.debug('Connection reset by upstream')
return True
return False
async def write_to_descriptors(self, w: Writables) -> bool:
if self.upstream and \
self.upstream.connection.fileno() in w and \
self.upstream.has_buffer():
try:
# TODO: max sendbuf size flag currently not used here
self.upstream.flush()
except ssl.SSLWantWriteError: # pragma: no cover
logger.info('Upstream SSLWantWriteError, will retry')
return False
except BrokenPipeError: # pragma: no cover
logger.debug('BrokenPipeError when flushing to upstream')
return True
return False
| bsd-3-clause | c6bd2c00a8030c792a56debe7148c17d | 40.056075 | 86 | 0.617118 | 4.366799 | false | false | false | false |
abhinavsingh/proxy.py | proxy/http/server/pac_plugin.py | 1 | 2727 | # -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE for more details.
.. spelling::
pac
"""
from typing import Any, List, Tuple, Optional
from .plugin import HttpWebServerBasePlugin
from ..parser import HttpParser
from .protocols import httpProtocolTypes
from ..responses import okResponse
from ...common.flag import flags
from ...common.utils import text_, bytes_
from ...common.constants import DEFAULT_PAC_FILE, DEFAULT_PAC_FILE_URL_PATH
flags.add_argument(
'--pac-file',
type=str,
default=DEFAULT_PAC_FILE,
help='A file (Proxy Auto Configuration) or string to serve when '
'the server receives a direct file request. '
'Using this option enables proxy.HttpWebServerPlugin.',
)
flags.add_argument(
'--pac-file-url-path',
type=str,
default=text_(DEFAULT_PAC_FILE_URL_PATH),
help='Default: %s. Web server path to serve the PAC file.' %
text_(DEFAULT_PAC_FILE_URL_PATH),
)
class HttpWebServerPacFilePlugin(HttpWebServerBasePlugin):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.pac_file_response: Optional[memoryview] = None
self.cache_pac_file_response()
def routes(self) -> List[Tuple[int, str]]:
if self.flags.pac_file_url_path:
return [
(
httpProtocolTypes.HTTP, r'{0}$'.format(
text_(self.flags.pac_file_url_path),
),
),
(
httpProtocolTypes.HTTPS, r'{0}$'.format(
text_(self.flags.pac_file_url_path),
),
),
]
return [] # pragma: no cover
def handle_request(self, request: HttpParser) -> None:
if self.flags.pac_file and self.pac_file_response:
self.client.queue(self.pac_file_response)
def cache_pac_file_response(self) -> None:
if self.flags.pac_file:
try:
with open(self.flags.pac_file, 'rb') as f:
content = f.read()
except IOError:
content = bytes_(self.flags.pac_file)
self.pac_file_response = okResponse(
content=content,
headers={
b'Content-Type': b'application/x-ns-proxy-autoconfig',
},
conn_close=True,
compress=False,
)
| bsd-3-clause | 0bd4f407501a1f771cd792b07631f8c3 | 31.392857 | 86 | 0.575891 | 3.903874 | false | false | false | false |
abhinavsingh/proxy.py | proxy/common/plugins.py | 1 | 3789 | # -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE for more details.
"""
import os
import inspect
import logging
import importlib
import itertools
from typing import Any, Dict, List, Tuple, Union, Optional
from .utils import text_, bytes_
from .constants import DOT, COMMA, DEFAULT_ABC_PLUGINS
logger = logging.getLogger(__name__)
class Plugins:
"""Common utilities for plugin discovery."""
@staticmethod
def resolve_plugin_flag(flag_plugins: Any, opt_plugins: Optional[Any] = None) -> List[Union[bytes, type]]:
if isinstance(flag_plugins, list):
requested_plugins = list(
itertools.chain.from_iterable([
p.split(text_(COMMA)) for p in list(
itertools.chain.from_iterable(flag_plugins),
)
]),
)
else:
requested_plugins = flag_plugins.split(text_(COMMA))
return [
p if isinstance(p, type) else bytes_(p)
for p in (opt_plugins if opt_plugins is not None else requested_plugins)
if not (isinstance(p, str) and len(p) == 0)
]
@staticmethod
def discover(input_args: List[str]) -> None:
"""Search for external plugin found in command line arguments,
then iterates over each value and discover/import the plugin.
"""
for i, f in enumerate(input_args):
if f in ('--plugin', '--plugins', '--auth-plugin'):
v = input_args[i + 1]
parts = v.split(',')
for part in parts:
Plugins.importer(bytes_(part))
@staticmethod
def load(
plugins: List[Union[bytes, type]],
abc_plugins: Optional[List[str]] = None,
) -> Dict[bytes, List[type]]:
"""Accepts a list Python modules, scans them to identify
if they are an implementation of abstract plugin classes and
returns a dictionary of matching plugins for each abstract class.
"""
p: Dict[bytes, List[type]] = {}
for abc_plugin in (abc_plugins or DEFAULT_ABC_PLUGINS):
p[bytes_(abc_plugin)] = []
for plugin_ in plugins:
klass, module_name = Plugins.importer(plugin_)
assert klass and module_name
mro = list(inspect.getmro(klass))
# Find the base plugin class that
# this plugin_ is implementing
base_klass = None
for k in mro:
if bytes_(k.__name__) in p:
base_klass = k
break
if base_klass is None:
raise ValueError('%s is NOT a valid plugin' % text_(plugin_))
if klass not in p[bytes_(base_klass.__name__)]:
p[bytes_(base_klass.__name__)].append(klass)
logger.info('Loaded plugin %s.%s', module_name, klass.__name__)
# print(p)
return p
@staticmethod
def importer(plugin: Union[bytes, type]) -> Tuple[type, str]:
"""Import and returns the plugin."""
if isinstance(plugin, type):
return (plugin, '__main__')
plugin_ = text_(plugin.strip())
assert plugin_ != ''
module_name, klass_name = plugin_.rsplit(text_(DOT), 1)
klass = getattr(
importlib.import_module(
module_name.replace(
os.path.sep, text_(DOT),
),
),
klass_name,
)
return (klass, module_name)
| bsd-3-clause | 7faf058d697d62259a38ec8ca794f0c3 | 35.028571 | 110 | 0.556965 | 4.308656 | false | false | false | false |
abhinavsingh/proxy.py | proxy/http/inspector/transformer.py | 1 | 5989 | # -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE for more details.
"""
import json
import time
from typing import TYPE_CHECKING, Any, Dict
from ..websocket import WebsocketFrame
from ...core.event import eventNames
from ...common.utils import bytes_
from ...common.constants import (
PROXY_PY_START_TIME, DEFAULT_DEVTOOLS_DOC_URL, DEFAULT_DEVTOOLS_FRAME_ID,
DEFAULT_DEVTOOLS_LOADER_ID,
)
if TYPE_CHECKING: # pragma: no cover
from ..connection import HttpClientConnection
class CoreEventsToDevtoolsProtocol:
"""Open in Chrome
``devtools://devtools/bundled/inspector.html?ws=localhost:8899/devtools``
"""
RESPONSES: Dict[str, bytes] = {}
@staticmethod
def transformer(
client: 'HttpClientConnection',
event: Dict[str, Any],
) -> None:
event_name = event['event_name']
if event_name == eventNames.REQUEST_COMPLETE:
data = CoreEventsToDevtoolsProtocol.request_complete(event)
elif event_name == eventNames.RESPONSE_HEADERS_COMPLETE:
data = CoreEventsToDevtoolsProtocol.response_headers_complete(
event,
)
elif event_name == eventNames.RESPONSE_CHUNK_RECEIVED:
data = CoreEventsToDevtoolsProtocol.response_chunk_received(event)
elif event_name == eventNames.RESPONSE_COMPLETE:
data = CoreEventsToDevtoolsProtocol.response_complete(event)
else:
# drop core events unrelated to Devtools
return
client.queue(
memoryview(
WebsocketFrame.text(
bytes_(
json.dumps(data),
),
),
),
)
@staticmethod
def request_complete(event: Dict[str, Any]) -> Dict[str, Any]:
now = time.time()
return {
'method': 'Network.requestWillBeSent',
'params': {
'requestId': event['request_id'],
'frameId': DEFAULT_DEVTOOLS_FRAME_ID,
'loaderId': DEFAULT_DEVTOOLS_LOADER_ID,
'documentURL': DEFAULT_DEVTOOLS_DOC_URL,
'timestamp': now - PROXY_PY_START_TIME,
'wallTime': now,
'hasUserGesture': False,
'type': event['event_payload']['headers']['content-type']
if 'content-type' in event['event_payload']['headers']
else 'Other',
'request': {
'url': event['event_payload']['url'],
'method': event['event_payload']['method'],
'headers': event['event_payload']['headers'],
'postData': event['event_payload']['body'],
'initialPriority': 'High',
'urlFragment': '',
'mixedContentType': 'none',
},
'initiator': {
'type': 'other',
},
},
}
@staticmethod
def response_headers_complete(event: Dict[str, Any]) -> Dict[str, Any]:
return {
'method': 'Network.responseReceived',
'params': {
'requestId': event['request_id'],
'frameId': DEFAULT_DEVTOOLS_FRAME_ID,
'loaderId': DEFAULT_DEVTOOLS_LOADER_ID,
'timestamp': time.time(),
'type': event['event_payload']['headers']['content-type']
if event['event_payload']['headers'].has_header('content-type')
else 'Other',
'response': {
'url': '',
'status': '',
'statusText': '',
'headers': '',
'headersText': '',
'mimeType': '',
'connectionReused': True,
'connectionId': '',
'encodedDataLength': '',
'fromDiskCache': False,
'fromServiceWorker': False,
'timing': {
'requestTime': '',
'proxyStart': -1,
'proxyEnd': -1,
'dnsStart': -1,
'dnsEnd': -1,
'connectStart': -1,
'connectEnd': -1,
'sslStart': -1,
'sslEnd': -1,
'workerStart': -1,
'workerReady': -1,
'sendStart': 0,
'sendEnd': 0,
'receiveHeadersEnd': 0,
},
'requestHeaders': '',
'remoteIPAddress': '',
'remotePort': '',
},
},
}
@staticmethod
def response_chunk_received(event: Dict[str, Any]) -> Dict[str, Any]:
return {
'method': 'Network.dataReceived',
'params': {
'requestId': event['request_id'],
'timestamp': time.time(),
'dataLength': event['event_payload']['chunk_size'],
'encodedDataLength': event['event_payload']['encoded_chunk_size'],
},
}
@staticmethod
def response_complete(event: Dict[str, Any]) -> Dict[str, Any]:
return {
'method': 'Network.loadingFinished',
'params': {
'requestId': event['request_id'],
'timestamp': time.time(),
'encodedDataLength': event['event_payload']['encoded_response_size'],
'shouldReportCorbBlocking': False,
},
}
| bsd-3-clause | 662b033c995318536ca4a127f326f3c7 | 35.260606 | 86 | 0.481865 | 4.641583 | false | false | false | false |
abhinavsingh/proxy.py | tests/http/exceptions/test_http_proxy_auth_failed.py | 1 | 5569 | # -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE for more details.
"""
import selectors
import pytest
from pytest_mock import MockerFixture
from proxy.http import HttpProtocolHandler, HttpClientConnection, httpHeaders
from proxy.common.flag import FlagParser
from proxy.common.utils import build_http_request
from proxy.http.responses import PROXY_AUTH_FAILED_RESPONSE_PKT
from ...test_assertions import Assertions
class TestHttpProxyAuthFailed(Assertions):
@pytest.fixture(autouse=True) # type: ignore[misc]
def _setUp(self, mocker: MockerFixture) -> None:
self.mock_fromfd = mocker.patch('socket.fromfd')
self.mock_selector = mocker.patch('selectors.DefaultSelector')
self.mock_server_conn = mocker.patch(
'proxy.http.proxy.server.TcpServerConnection',
)
self.fileno = 10
self._addr = ('127.0.0.1', 54382)
self.flags = FlagParser.initialize(
["--basic-auth", "user:pass"], threaded=True,
)
self._conn = self.mock_fromfd.return_value
self.protocol_handler = HttpProtocolHandler(
HttpClientConnection(self._conn, self._addr),
flags=self.flags,
)
self.protocol_handler.initialize()
@pytest.mark.asyncio # type: ignore[misc]
async def test_proxy_auth_fails_without_cred(self) -> None:
self._conn.recv.return_value = build_http_request(
b'GET', b'http://upstream.host/not-found.html',
headers={
b'Host': b'upstream.host',
},
)
self.mock_selector.return_value.select.side_effect = [
[(
selectors.SelectorKey(
fileobj=self._conn.fileno(),
fd=self._conn.fileno(),
events=selectors.EVENT_READ,
data=None,
),
selectors.EVENT_READ,
)],
]
await self.protocol_handler._run_once()
self.mock_server_conn.assert_not_called()
self.assertEqual(self.protocol_handler.work.has_buffer(), True)
self.assertEqual(
self.protocol_handler.work.buffer[0],
PROXY_AUTH_FAILED_RESPONSE_PKT,
)
self._conn.send.assert_not_called()
@pytest.mark.asyncio # type: ignore[misc]
async def test_proxy_auth_fails_with_invalid_cred(self) -> None:
self._conn.recv.return_value = build_http_request(
b'GET', b'http://upstream.host/not-found.html',
headers={
b'Host': b'upstream.host',
httpHeaders.PROXY_AUTHORIZATION: b'Basic hello',
},
)
self.mock_selector.return_value.select.side_effect = [
[(
selectors.SelectorKey(
fileobj=self._conn.fileno(),
fd=self._conn.fileno(),
events=selectors.EVENT_READ,
data=None,
),
selectors.EVENT_READ,
)],
]
await self.protocol_handler._run_once()
self.mock_server_conn.assert_not_called()
self.assertEqual(self.protocol_handler.work.has_buffer(), True)
self.assertEqual(
self.protocol_handler.work.buffer[0],
PROXY_AUTH_FAILED_RESPONSE_PKT,
)
self._conn.send.assert_not_called()
@pytest.mark.asyncio # type: ignore[misc]
async def test_proxy_auth_works_with_valid_cred(self) -> None:
self._conn.recv.return_value = build_http_request(
b'GET', b'http://upstream.host/not-found.html',
headers={
b'Host': b'upstream.host',
httpHeaders.PROXY_AUTHORIZATION: b'Basic dXNlcjpwYXNz',
},
)
self.mock_selector.return_value.select.side_effect = [
[(
selectors.SelectorKey(
fileobj=self._conn.fileno(),
fd=self._conn.fileno(),
events=selectors.EVENT_READ,
data=None,
),
selectors.EVENT_READ,
)],
]
await self.protocol_handler._run_once()
self.mock_server_conn.assert_called_once()
self.assertEqual(self.protocol_handler.work.has_buffer(), False)
@pytest.mark.asyncio # type: ignore[misc]
async def test_proxy_auth_works_with_mixed_case_basic_string(self) -> None:
self._conn.recv.return_value = build_http_request(
b'GET', b'http://upstream.host/not-found.html',
headers={
b'Host': b'upstream.host',
httpHeaders.PROXY_AUTHORIZATION: b'bAsIc dXNlcjpwYXNz',
},
)
self.mock_selector.return_value.select.side_effect = [
[(
selectors.SelectorKey(
fileobj=self._conn.fileno(),
fd=self._conn.fileno(),
events=selectors.EVENT_READ,
data=None,
),
selectors.EVENT_READ,
)],
]
await self.protocol_handler._run_once()
self.mock_server_conn.assert_called_once()
self.assertEqual(self.protocol_handler.work.has_buffer(), False)
| bsd-3-clause | bf6696becc287c8ce2fdd4e081f8453b | 36.33557 | 86 | 0.563545 | 3.970735 | false | true | false | false |
abhinavsingh/proxy.py | proxy/plugin/modify_post_data.py | 1 | 1679 | # -*- coding: utf-8 -*-
"""
proxy.py
~~~~~~~~
⚡⚡⚡ Fast, Lightweight, Pluggable, TLS interception capable proxy server focused on
Network monitoring, controls & Application development, testing, debugging.
:copyright: (c) 2013-present by Abhinav Singh and contributors.
:license: BSD, see LICENSE for more details.
.. spelling::
localhost
httpbin
"""
from typing import Optional
from ..http.proxy import HttpProxyBasePlugin
from ..http.parser import HttpParser
class ModifyPostDataPlugin(HttpProxyBasePlugin):
"""Modify POST request body before sending to upstream server.
Following curl executions will work:
1. Plain
curl -v -x localhost:8899 -X POST http://httpbin.org/post -d 'key=value'
2. Chunked
curl -v -x localhost:8899 -X POST \
-H 'Transfer-Encoding: chunked' http://httpbin.org/post -d 'key=value'
3. Chunked & Compressed
echo 'key=value' | gzip | curl -v \
-x localhost:8899 \
-X POST \
--data-binary @- -H 'Transfer-Encoding: chunked' \
-H 'Content-Encoding: gzip' http://httpbin.org/post
"""
MODIFIED_BODY = b'{"key": "modified"}'
def before_upstream_connection(
self, request: HttpParser,
) -> Optional[HttpParser]:
return request
def handle_client_request(
self, request: HttpParser,
) -> Optional[HttpParser]:
if request.body:
request.update_body(
ModifyPostDataPlugin.MODIFIED_BODY,
content_type=b'application/json',
)
return request
| bsd-3-clause | 0f5ce8ca465c0b9258962d7b3b475c1e | 29.418182 | 86 | 0.601913 | 3.983333 | false | false | false | false |
astropy/astropy | astropy/coordinates/baseframe.py | 3 | 83537 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Framework and base classes for coordinate frames/"low-level" coordinate
classes.
"""
# Standard library
import copy
import inspect
import warnings
from collections import defaultdict, namedtuple
# Dependencies
import numpy as np
from astropy import units as u
from astropy.utils import ShapedLikeNDArray, check_broadcast
# Project
from astropy.utils.decorators import deprecated, format_doc, lazyproperty
from astropy.utils.exceptions import AstropyDeprecationWarning, AstropyWarning
from . import representation as r
from .angles import Angle
from .attributes import Attribute
from .transformations import TransformGraph
__all__ = [
"BaseCoordinateFrame",
"frame_transform_graph",
"GenericFrame",
"RepresentationMapping",
]
# the graph used for all transformations between frames
frame_transform_graph = TransformGraph()
def _get_repr_cls(value):
"""
Return a valid representation class from ``value`` or raise exception.
"""
if value in r.REPRESENTATION_CLASSES:
value = r.REPRESENTATION_CLASSES[value]
elif not isinstance(value, type) or not issubclass(value, r.BaseRepresentation):
raise ValueError(
f"Representation is {value!r} but must be a BaseRepresentation class "
f"or one of the string aliases {list(r.REPRESENTATION_CLASSES)}"
)
return value
def _get_diff_cls(value):
"""
Return a valid differential class from ``value`` or raise exception.
As originally created, this is only used in the SkyCoord initializer, so if
that is refactored, this function my no longer be necessary.
"""
if value in r.DIFFERENTIAL_CLASSES:
value = r.DIFFERENTIAL_CLASSES[value]
elif not isinstance(value, type) or not issubclass(value, r.BaseDifferential):
raise ValueError(
f"Differential is {value!r} but must be a BaseDifferential class "
f"or one of the string aliases {list(r.DIFFERENTIAL_CLASSES)}"
)
return value
def _get_repr_classes(base, **differentials):
"""Get valid representation and differential classes.
Parameters
----------
base : str or `~astropy.coordinates.BaseRepresentation` subclass
class for the representation of the base coordinates. If a string,
it is looked up among the known representation classes.
**differentials : dict of str or `~astropy.coordinates.BaseDifferentials`
Keys are like for normal differentials, i.e., 's' for a first
derivative in time, etc. If an item is set to `None`, it will be
guessed from the base class.
Returns
-------
repr_classes : dict of subclasses
The base class is keyed by 'base'; the others by the keys of
``diffferentials``.
"""
base = _get_repr_cls(base)
repr_classes = {"base": base}
for name, differential_type in differentials.items():
if differential_type == "base":
# We don't want to fail for this case.
differential_type = r.DIFFERENTIAL_CLASSES.get(base.get_name(), None)
elif differential_type in r.DIFFERENTIAL_CLASSES:
differential_type = r.DIFFERENTIAL_CLASSES[differential_type]
elif differential_type is not None and (
not isinstance(differential_type, type)
or not issubclass(differential_type, r.BaseDifferential)
):
raise ValueError(
"Differential is {differential_type!r} but must be a BaseDifferential"
f" class or one of the string aliases {list(r.DIFFERENTIAL_CLASSES)}"
)
repr_classes[name] = differential_type
return repr_classes
_RepresentationMappingBase = namedtuple(
"RepresentationMapping", ("reprname", "framename", "defaultunit")
)
class RepresentationMapping(_RepresentationMappingBase):
"""
This `~collections.namedtuple` is used with the
``frame_specific_representation_info`` attribute to tell frames what
attribute names (and default units) to use for a particular representation.
``reprname`` and ``framename`` should be strings, while ``defaultunit`` can
be either an astropy unit, the string ``'recommended'`` (which is degrees
for Angles, nothing otherwise), or None (to indicate that no unit mapping
should be done).
"""
def __new__(cls, reprname, framename, defaultunit="recommended"):
# this trick just provides some defaults
return super().__new__(cls, reprname, framename, defaultunit)
base_doc = """{__doc__}
Parameters
----------
data : `~astropy.coordinates.BaseRepresentation` subclass instance
A representation object or ``None`` to have no data (or use the
coordinate component arguments, see below).
{components}
representation_type : `~astropy.coordinates.BaseRepresentation` subclass, str, optional
A representation class or string name of a representation class. This
sets the expected input representation class, thereby changing the
expected keyword arguments for the data passed in. For example, passing
``representation_type='cartesian'`` will make the classes expect
position data with cartesian names, i.e. ``x, y, z`` in most cases
unless overridden via ``frame_specific_representation_info``. To see this
frame's names, check out ``<this frame>().representation_info``.
differential_type : `~astropy.coordinates.BaseDifferential` subclass, str, dict, optional
A differential class or dictionary of differential classes (currently
only a velocity differential with key 's' is supported). This sets the
expected input differential class, thereby changing the expected keyword
arguments of the data passed in. For example, passing
``differential_type='cartesian'`` will make the classes expect velocity
data with the argument names ``v_x, v_y, v_z`` unless overridden via
``frame_specific_representation_info``. To see this frame's names,
check out ``<this frame>().representation_info``.
copy : bool, optional
If `True` (default), make copies of the input coordinate arrays.
Can only be passed in as a keyword argument.
{footer}
"""
_components = """
*args, **kwargs
Coordinate components, with names that depend on the subclass.
"""
@format_doc(base_doc, components=_components, footer="")
class BaseCoordinateFrame(ShapedLikeNDArray):
"""
The base class for coordinate frames.
This class is intended to be subclassed to create instances of specific
systems. Subclasses can implement the following attributes:
* `default_representation`
A subclass of `~astropy.coordinates.BaseRepresentation` that will be
treated as the default representation of this frame. This is the
representation assumed by default when the frame is created.
* `default_differential`
A subclass of `~astropy.coordinates.BaseDifferential` that will be
treated as the default differential class of this frame. This is the
differential class assumed by default when the frame is created.
* `~astropy.coordinates.Attribute` class attributes
Frame attributes such as ``FK4.equinox`` or ``FK4.obstime`` are defined
using a descriptor class. See the narrative documentation or
built-in classes code for details.
* `frame_specific_representation_info`
A dictionary mapping the name or class of a representation to a list of
`~astropy.coordinates.RepresentationMapping` objects that tell what
names and default units should be used on this frame for the components
of that representation.
Unless overridden via `frame_specific_representation_info`, velocity name
defaults are:
* ``pm_{lon}_cos{lat}``, ``pm_{lat}`` for `SphericalCosLatDifferential`
proper motion components
* ``pm_{lon}``, ``pm_{lat}`` for `SphericalDifferential` proper motion
components
* ``radial_velocity`` for any ``d_distance`` component
* ``v_{x,y,z}`` for `CartesianDifferential` velocity components
where ``{lon}`` and ``{lat}`` are the frame names of the angular components.
"""
default_representation = None
default_differential = None
# Specifies special names and units for representation and differential
# attributes.
frame_specific_representation_info = {}
frame_attributes = {}
# Default empty frame_attributes dict
def __init_subclass__(cls, **kwargs):
# We first check for explicitly set values for these:
default_repr = getattr(cls, "default_representation", None)
default_diff = getattr(cls, "default_differential", None)
repr_info = getattr(cls, "frame_specific_representation_info", None)
# Then, to make sure this works for subclasses-of-subclasses, we also
# have to check for cases where the attribute names have already been
# replaced by underscore-prefaced equivalents by the logic below:
if default_repr is None or isinstance(default_repr, property):
default_repr = getattr(cls, "_default_representation", None)
if default_diff is None or isinstance(default_diff, property):
default_diff = getattr(cls, "_default_differential", None)
if repr_info is None or isinstance(repr_info, property):
repr_info = getattr(cls, "_frame_specific_representation_info", None)
repr_info = cls._infer_repr_info(repr_info)
# Make read-only properties for the frame class attributes that should
# be read-only to make them immutable after creation.
# We copy attributes instead of linking to make sure there's no
# accidental cross-talk between classes
cls._create_readonly_property(
"default_representation",
default_repr,
"Default representation for position data",
)
cls._create_readonly_property(
"default_differential",
default_diff,
"Default representation for differential data (e.g., velocity)",
)
cls._create_readonly_property(
"frame_specific_representation_info",
copy.deepcopy(repr_info),
"Mapping for frame-specific component names",
)
# Set the frame attributes. We first construct the attributes from
# superclasses, going in reverse order to keep insertion order,
# and then add any attributes from the frame now being defined
# (if any old definitions are overridden, this keeps the order).
# Note that we cannot simply start with the inherited frame_attributes
# since we could be a mixin between multiple coordinate frames.
# TODO: Should this be made to use readonly_prop_factory as well or
# would it be inconvenient for getting the frame_attributes from
# classes?
frame_attrs = {}
for basecls in reversed(cls.__bases__):
if issubclass(basecls, BaseCoordinateFrame):
frame_attrs.update(basecls.frame_attributes)
for k, v in cls.__dict__.items():
if isinstance(v, Attribute):
frame_attrs[k] = v
cls.frame_attributes = frame_attrs
# Deal with setting the name of the frame:
if not hasattr(cls, "name"):
cls.name = cls.__name__.lower()
elif BaseCoordinateFrame not in cls.__bases__ and cls.name in [
getattr(base, "name", None) for base in cls.__bases__
]:
# This may be a subclass of a subclass of BaseCoordinateFrame,
# like ICRS(BaseRADecFrame). In this case, cls.name will have been
# set by init_subclass
cls.name = cls.__name__.lower()
# A cache that *must be unique to each frame class* - it is
# insufficient to share them with superclasses, hence the need to put
# them in the meta
cls._frame_class_cache = {}
super().__init_subclass__(**kwargs)
# call this once here to initialize defaults
# (via FrameAttribute.__get__/convert_input)
cls.get_frame_attr_defaults()
def __init__(
self,
*args,
copy=True,
representation_type=None,
differential_type=None,
**kwargs,
):
self._attr_names_with_defaults = []
self._representation = self._infer_representation(
representation_type, differential_type
)
self._data = self._infer_data(args, copy, kwargs) # possibly None.
# Set frame attributes, if any
values = {}
for fnm, fdefault in self.get_frame_attr_defaults().items():
# Read-only frame attributes are defined as FrameAttribute
# descriptors which are not settable, so set 'real' attributes as
# the name prefaced with an underscore.
if fnm in kwargs:
value = kwargs.pop(fnm)
setattr(self, "_" + fnm, value)
# Validate attribute by getting it. If the instance has data,
# this also checks its shape is OK. If not, we do it below.
values[fnm] = getattr(self, fnm)
else:
setattr(self, "_" + fnm, fdefault)
self._attr_names_with_defaults.append(fnm)
if kwargs:
raise TypeError(
f"Coordinate frame {self.__class__.__name__} got unexpected "
f"keywords: {list(kwargs)}"
)
# We do ``is None`` because self._data might evaluate to false for
# empty arrays or data == 0
if self._data is None:
# No data: we still need to check that any non-scalar attributes
# have consistent shapes. Collect them for all attributes with
# size > 1 (which should be array-like and thus have a shape).
shapes = {
fnm: value.shape
for fnm, value in values.items()
if getattr(value, "shape", ())
}
if shapes:
if len(shapes) > 1:
try:
self._no_data_shape = check_broadcast(*shapes.values())
except ValueError as err:
raise ValueError(
f"non-scalar attributes with inconsistent shapes: {shapes}"
) from err
# Above, we checked that it is possible to broadcast all
# shapes. By getting and thus validating the attributes,
# we verify that the attributes can in fact be broadcast.
for fnm in shapes:
getattr(self, fnm)
else:
self._no_data_shape = shapes.popitem()[1]
else:
self._no_data_shape = ()
# The logic of this block is not related to the previous one
if self._data is not None:
# This makes the cache keys backwards-compatible, but also adds
# support for having differentials attached to the frame data
# representation object.
if "s" in self._data.differentials:
# TODO: assumes a velocity unit differential
key = (
self._data.__class__.__name__,
self._data.differentials["s"].__class__.__name__,
False,
)
else:
key = (self._data.__class__.__name__, False)
# Set up representation cache.
self.cache["representation"][key] = self._data
def _infer_representation(self, representation_type, differential_type):
if representation_type is None and differential_type is None:
return {"base": self.default_representation, "s": self.default_differential}
if representation_type is None:
representation_type = self.default_representation
if inspect.isclass(differential_type) and issubclass(
differential_type, r.BaseDifferential
):
# TODO: assumes the differential class is for the velocity
# differential
differential_type = {"s": differential_type}
elif isinstance(differential_type, str):
# TODO: assumes the differential class is for the velocity
# differential
diff_cls = r.DIFFERENTIAL_CLASSES[differential_type]
differential_type = {"s": diff_cls}
elif differential_type is None:
if representation_type == self.default_representation:
differential_type = {"s": self.default_differential}
else:
differential_type = {"s": "base"} # see set_representation_cls()
return _get_repr_classes(representation_type, **differential_type)
def _infer_data(self, args, copy, kwargs):
# if not set below, this is a frame with no data
representation_data = None
differential_data = None
args = list(args) # need to be able to pop them
if args and (isinstance(args[0], r.BaseRepresentation) or args[0] is None):
representation_data = args.pop(0) # This can still be None
if len(args) > 0:
raise TypeError(
"Cannot create a frame with both a representation object "
"and other positional arguments"
)
if representation_data is not None:
diffs = representation_data.differentials
differential_data = diffs.get("s", None)
if (differential_data is None and len(diffs) > 0) or (
differential_data is not None and len(diffs) > 1
):
raise ValueError(
"Multiple differentials are associated with the representation"
" object passed in to the frame initializer. Only a single"
f" velocity differential is supported. Got: {diffs}"
)
else:
representation_cls = self.get_representation_cls()
# Get any representation data passed in to the frame initializer
# using keyword or positional arguments for the component names
repr_kwargs = {}
for nmkw, nmrep in self.representation_component_names.items():
if len(args) > 0:
# first gather up positional args
repr_kwargs[nmrep] = args.pop(0)
elif nmkw in kwargs:
repr_kwargs[nmrep] = kwargs.pop(nmkw)
# special-case the Spherical->UnitSpherical if no `distance`
if repr_kwargs:
# TODO: determine how to get rid of the part before the "try" -
# currently removing it has a performance regression for
# unitspherical because of the try-related overhead.
# Also frames have no way to indicate what the "distance" is
if repr_kwargs.get("distance", True) is None:
del repr_kwargs["distance"]
if (
issubclass(representation_cls, r.SphericalRepresentation)
and "distance" not in repr_kwargs
):
representation_cls = representation_cls._unit_representation
try:
representation_data = representation_cls(copy=copy, **repr_kwargs)
except TypeError as e:
# this except clause is here to make the names of the
# attributes more human-readable. Without this the names
# come from the representation instead of the frame's
# attribute names.
try:
representation_data = representation_cls._unit_representation(
copy=copy, **repr_kwargs
)
except Exception:
msg = str(e)
names = self.get_representation_component_names()
for frame_name, repr_name in names.items():
msg = msg.replace(repr_name, frame_name)
msg = msg.replace("__init__()", f"{self.__class__.__name__}()")
e.args = (msg,)
raise e
# Now we handle the Differential data:
# Get any differential data passed in to the frame initializer
# using keyword or positional arguments for the component names
differential_cls = self.get_representation_cls("s")
diff_component_names = self.get_representation_component_names("s")
diff_kwargs = {}
for nmkw, nmrep in diff_component_names.items():
if len(args) > 0:
# first gather up positional args
diff_kwargs[nmrep] = args.pop(0)
elif nmkw in kwargs:
diff_kwargs[nmrep] = kwargs.pop(nmkw)
if diff_kwargs:
if (
hasattr(differential_cls, "_unit_differential")
and "d_distance" not in diff_kwargs
):
differential_cls = differential_cls._unit_differential
elif len(diff_kwargs) == 1 and "d_distance" in diff_kwargs:
differential_cls = r.RadialDifferential
try:
differential_data = differential_cls(copy=copy, **diff_kwargs)
except TypeError as e:
# this except clause is here to make the names of the
# attributes more human-readable. Without this the names
# come from the representation instead of the frame's
# attribute names.
msg = str(e)
names = self.get_representation_component_names("s")
for frame_name, repr_name in names.items():
msg = msg.replace(repr_name, frame_name)
msg = msg.replace("__init__()", f"{self.__class__.__name__}()")
e.args = (msg,)
raise
if len(args) > 0:
raise TypeError(
"{}.__init__ had {} remaining unhandled arguments".format(
self.__class__.__name__, len(args)
)
)
if representation_data is None and differential_data is not None:
raise ValueError(
"Cannot pass in differential component data "
"without positional (representation) data."
)
if differential_data:
# Check that differential data provided has units compatible
# with time-derivative of representation data.
# NOTE: there is no dimensionless time while lengths can be
# dimensionless (u.dimensionless_unscaled).
for comp in representation_data.components:
if (diff_comp := f"d_{comp}") in differential_data.components:
current_repr_unit = representation_data._units[comp]
current_diff_unit = differential_data._units[diff_comp]
expected_unit = current_repr_unit / u.s
if not current_diff_unit.is_equivalent(expected_unit):
for (
key,
val,
) in self.get_representation_component_names().items():
if val == comp:
current_repr_name = key
break
for key, val in self.get_representation_component_names(
"s"
).items():
if val == diff_comp:
current_diff_name = key
break
raise ValueError(
f'{current_repr_name} has unit "{current_repr_unit}" with'
f' physical type "{current_repr_unit.physical_type}", but'
f" {current_diff_name} has incompatible unit"
f' "{current_diff_unit}" with physical type'
f' "{current_diff_unit.physical_type}" instead of the'
f' expected "{(expected_unit).physical_type}".'
)
representation_data = representation_data.with_differentials(
{"s": differential_data}
)
return representation_data
@classmethod
def _infer_repr_info(cls, repr_info):
# Unless overridden via `frame_specific_representation_info`, velocity
# name defaults are (see also docstring for BaseCoordinateFrame):
# * ``pm_{lon}_cos{lat}``, ``pm_{lat}`` for
# `SphericalCosLatDifferential` proper motion components
# * ``pm_{lon}``, ``pm_{lat}`` for `SphericalDifferential` proper
# motion components
# * ``radial_velocity`` for any `d_distance` component
# * ``v_{x,y,z}`` for `CartesianDifferential` velocity components
# where `{lon}` and `{lat}` are the frame names of the angular
# components.
if repr_info is None:
repr_info = {}
# the tuple() call below is necessary because if it is not there,
# the iteration proceeds in a difficult-to-predict manner in the
# case that one of the class objects hash is such that it gets
# revisited by the iteration. The tuple() call prevents this by
# making the items iterated over fixed regardless of how the dict
# changes
for cls_or_name in tuple(repr_info.keys()):
if isinstance(cls_or_name, str):
# TODO: this provides a layer of backwards compatibility in
# case the key is a string, but now we want explicit classes.
_cls = _get_repr_cls(cls_or_name)
repr_info[_cls] = repr_info.pop(cls_or_name)
# The default spherical names are 'lon' and 'lat'
repr_info.setdefault(
r.SphericalRepresentation,
[RepresentationMapping("lon", "lon"), RepresentationMapping("lat", "lat")],
)
sph_component_map = {
m.reprname: m.framename for m in repr_info[r.SphericalRepresentation]
}
repr_info.setdefault(
r.SphericalCosLatDifferential,
[
RepresentationMapping(
"d_lon_coslat",
"pm_{lon}_cos{lat}".format(**sph_component_map),
u.mas / u.yr,
),
RepresentationMapping(
"d_lat", "pm_{lat}".format(**sph_component_map), u.mas / u.yr
),
RepresentationMapping("d_distance", "radial_velocity", u.km / u.s),
],
)
repr_info.setdefault(
r.SphericalDifferential,
[
RepresentationMapping(
"d_lon", "pm_{lon}".format(**sph_component_map), u.mas / u.yr
),
RepresentationMapping(
"d_lat", "pm_{lat}".format(**sph_component_map), u.mas / u.yr
),
RepresentationMapping("d_distance", "radial_velocity", u.km / u.s),
],
)
repr_info.setdefault(
r.CartesianDifferential,
[
RepresentationMapping("d_x", "v_x", u.km / u.s),
RepresentationMapping("d_y", "v_y", u.km / u.s),
RepresentationMapping("d_z", "v_z", u.km / u.s),
],
)
# Unit* classes should follow the same naming conventions
# TODO: this adds some unnecessary mappings for the Unit classes, so
# this could be cleaned up, but in practice doesn't seem to have any
# negative side effects
repr_info.setdefault(
r.UnitSphericalRepresentation, repr_info[r.SphericalRepresentation]
)
repr_info.setdefault(
r.UnitSphericalCosLatDifferential, repr_info[r.SphericalCosLatDifferential]
)
repr_info.setdefault(
r.UnitSphericalDifferential, repr_info[r.SphericalDifferential]
)
return repr_info
@classmethod
def _create_readonly_property(cls, attr_name, value, doc=None):
private_attr = "_" + attr_name
def getter(self):
return getattr(self, private_attr)
setattr(cls, private_attr, value)
setattr(cls, attr_name, property(getter, doc=doc))
@lazyproperty
def cache(self):
"""
Cache for this frame, a dict. It stores anything that should be
computed from the coordinate data (*not* from the frame attributes).
This can be used in functions to store anything that might be
expensive to compute but might be re-used by some other function.
E.g.::
if 'user_data' in myframe.cache:
data = myframe.cache['user_data']
else:
myframe.cache['user_data'] = data = expensive_func(myframe.lat)
If in-place modifications are made to the frame data, the cache should
be cleared::
myframe.cache.clear()
"""
return defaultdict(dict)
@property
def data(self):
"""
The coordinate data for this object. If this frame has no data, an
`ValueError` will be raised. Use `has_data` to
check if data is present on this frame object.
"""
if self._data is None:
raise ValueError(
f'The frame object "{self!r}" does not have associated data'
)
return self._data
@property
def has_data(self):
"""
True if this frame has `data`, False otherwise.
"""
return self._data is not None
@property
def shape(self):
return self.data.shape if self.has_data else self._no_data_shape
# We have to override the ShapedLikeNDArray definitions, since our shape
# does not have to be that of the data.
def __len__(self):
return len(self.data)
def __bool__(self):
return self.has_data and self.size > 0
@property
def size(self):
return self.data.size
@property
def isscalar(self):
return self.has_data and self.data.isscalar
@classmethod
def get_frame_attr_defaults(cls):
"""Return a dict with the defaults for each frame attribute"""
return {name: getattr(cls, name) for name in cls.frame_attributes}
@deprecated(
"5.2",
alternative="get_frame_attr_defaults",
message=(
"The {func}() {obj_type} is deprecated and may be removed in a future"
" version. Use {alternative}() to obtain a dict of frame attribute names"
" and default values."
" The fastest way to obtain the names is frame_attributes.keys()"
),
)
@classmethod
def get_frame_attr_names(cls):
"""Return a dict with the defaults for each frame attribute"""
return cls.get_frame_attr_defaults()
def get_representation_cls(self, which="base"):
"""The class used for part of this frame's data.
Parameters
----------
which : ('base', 's', `None`)
The class of which part to return. 'base' means the class used to
represent the coordinates; 's' the first derivative to time, i.e.,
the class representing the proper motion and/or radial velocity.
If `None`, return a dict with both.
Returns
-------
representation : `~astropy.coordinates.BaseRepresentation` or `~astropy.coordinates.BaseDifferential`.
"""
if which is not None:
return self._representation[which]
else:
return self._representation
def set_representation_cls(self, base=None, s="base"):
"""Set representation and/or differential class for this frame's data.
Parameters
----------
base : str, `~astropy.coordinates.BaseRepresentation` subclass, optional
The name or subclass to use to represent the coordinate data.
s : `~astropy.coordinates.BaseDifferential` subclass, optional
The differential subclass to use to represent any velocities,
such as proper motion and radial velocity. If equal to 'base',
which is the default, it will be inferred from the representation.
If `None`, the representation will drop any differentials.
"""
if base is None:
base = self._representation["base"]
self._representation = _get_repr_classes(base=base, s=s)
representation_type = property(
fget=get_representation_cls,
fset=set_representation_cls,
doc="""The representation class used for this frame's data.
This will be a subclass from `~astropy.coordinates.BaseRepresentation`.
Can also be *set* using the string name of the representation. If you
wish to set an explicit differential class (rather than have it be
inferred), use the ``set_representation_cls`` method.
""",
)
@property
def differential_type(self):
"""
The differential used for this frame's data.
This will be a subclass from `~astropy.coordinates.BaseDifferential`.
For simultaneous setting of representation and differentials, see the
``set_representation_cls`` method.
"""
return self.get_representation_cls("s")
@differential_type.setter
def differential_type(self, value):
self.set_representation_cls(s=value)
@classmethod
def _get_representation_info(cls):
# This exists as a class method only to support handling frame inputs
# without units, which are deprecated and will be removed. This can be
# moved into the representation_info property at that time.
# note that if so moved, the cache should be acceessed as
# self.__class__._frame_class_cache
if (
cls._frame_class_cache.get("last_reprdiff_hash", None)
!= r.get_reprdiff_cls_hash()
):
repr_attrs = {}
for repr_diff_cls in list(r.REPRESENTATION_CLASSES.values()) + list(
r.DIFFERENTIAL_CLASSES.values()
):
repr_attrs[repr_diff_cls] = {"names": [], "units": []}
for c, c_cls in repr_diff_cls.attr_classes.items():
repr_attrs[repr_diff_cls]["names"].append(c)
rec_unit = u.deg if issubclass(c_cls, Angle) else None
repr_attrs[repr_diff_cls]["units"].append(rec_unit)
for (
repr_diff_cls,
mappings,
) in cls._frame_specific_representation_info.items():
# take the 'names' and 'units' tuples from repr_attrs,
# and then use the RepresentationMapping objects
# to update as needed for this frame.
nms = repr_attrs[repr_diff_cls]["names"]
uns = repr_attrs[repr_diff_cls]["units"]
comptomap = {m.reprname: m for m in mappings}
for i, c in enumerate(repr_diff_cls.attr_classes.keys()):
if c in comptomap:
mapp = comptomap[c]
nms[i] = mapp.framename
# need the isinstance because otherwise if it's a unit it
# will try to compare to the unit string representation
if not (
isinstance(mapp.defaultunit, str)
and mapp.defaultunit == "recommended"
):
uns[i] = mapp.defaultunit
# else we just leave it as recommended_units says above
# Convert to tuples so that this can't mess with frame internals
repr_attrs[repr_diff_cls]["names"] = tuple(nms)
repr_attrs[repr_diff_cls]["units"] = tuple(uns)
cls._frame_class_cache["representation_info"] = repr_attrs
cls._frame_class_cache["last_reprdiff_hash"] = r.get_reprdiff_cls_hash()
return cls._frame_class_cache["representation_info"]
@lazyproperty
def representation_info(self):
"""
A dictionary with the information of what attribute names for this frame
apply to particular representations.
"""
return self._get_representation_info()
def get_representation_component_names(self, which="base"):
out = {}
repr_or_diff_cls = self.get_representation_cls(which)
if repr_or_diff_cls is None:
return out
data_names = repr_or_diff_cls.attr_classes.keys()
repr_names = self.representation_info[repr_or_diff_cls]["names"]
for repr_name, data_name in zip(repr_names, data_names):
out[repr_name] = data_name
return out
def get_representation_component_units(self, which="base"):
out = {}
repr_or_diff_cls = self.get_representation_cls(which)
if repr_or_diff_cls is None:
return out
repr_attrs = self.representation_info[repr_or_diff_cls]
repr_names = repr_attrs["names"]
repr_units = repr_attrs["units"]
for repr_name, repr_unit in zip(repr_names, repr_units):
if repr_unit:
out[repr_name] = repr_unit
return out
representation_component_names = property(get_representation_component_names)
representation_component_units = property(get_representation_component_units)
def _replicate(self, data, copy=False, **kwargs):
"""Base for replicating a frame, with possibly different attributes.
Produces a new instance of the frame using the attributes of the old
frame (unless overridden) and with the data given.
Parameters
----------
data : `~astropy.coordinates.BaseRepresentation` or None
Data to use in the new frame instance. If `None`, it will be
a data-less frame.
copy : bool, optional
Whether data and the attributes on the old frame should be copied
(default), or passed on by reference.
**kwargs
Any attributes that should be overridden.
"""
# This is to provide a slightly nicer error message if the user tries
# to use frame_obj.representation instead of frame_obj.data to get the
# underlying representation object [e.g., #2890]
if inspect.isclass(data):
raise TypeError(
"Class passed as data instead of a representation instance. If you"
" called frame.representation, this returns the representation class."
" frame.data returns the instantiated object - you may want to use"
" this instead."
)
if copy and data is not None:
data = data.copy()
for attr in self.frame_attributes:
if attr not in self._attr_names_with_defaults and attr not in kwargs:
value = getattr(self, attr)
if copy:
value = value.copy()
kwargs[attr] = value
return self.__class__(data, copy=False, **kwargs)
def replicate(self, copy=False, **kwargs):
"""
Return a replica of the frame, optionally with new frame attributes.
The replica is a new frame object that has the same data as this frame
object and with frame attributes overridden if they are provided as extra
keyword arguments to this method. If ``copy`` is set to `True` then a
copy of the internal arrays will be made. Otherwise the replica will
use a reference to the original arrays when possible to save memory. The
internal arrays are normally not changeable by the user so in most cases
it should not be necessary to set ``copy`` to `True`.
Parameters
----------
copy : bool, optional
If True, the resulting object is a copy of the data. When False,
references are used where possible. This rule also applies to the
frame attributes.
**kwargs
Any additional keywords are treated as frame attributes to be set on the
new frame object.
Returns
-------
frameobj : `BaseCoordinateFrame` subclass instance
Replica of this object, but possibly with new frame attributes.
"""
return self._replicate(self.data, copy=copy, **kwargs)
def replicate_without_data(self, copy=False, **kwargs):
"""
Return a replica without data, optionally with new frame attributes.
The replica is a new frame object without data but with the same frame
attributes as this object, except where overridden by extra keyword
arguments to this method. The ``copy`` keyword determines if the frame
attributes are truly copied vs being references (which saves memory for
cases where frame attributes are large).
This method is essentially the converse of `realize_frame`.
Parameters
----------
copy : bool, optional
If True, the resulting object has copies of the frame attributes.
When False, references are used where possible.
**kwargs
Any additional keywords are treated as frame attributes to be set on the
new frame object.
Returns
-------
frameobj : `BaseCoordinateFrame` subclass instance
Replica of this object, but without data and possibly with new frame
attributes.
"""
return self._replicate(None, copy=copy, **kwargs)
def realize_frame(self, data, **kwargs):
"""
Generates a new frame with new data from another frame (which may or
may not have data). Roughly speaking, the converse of
`replicate_without_data`.
Parameters
----------
data : `~astropy.coordinates.BaseRepresentation`
The representation to use as the data for the new frame.
**kwargs
Any additional keywords are treated as frame attributes to be set on the
new frame object. In particular, `representation_type` can be specified.
Returns
-------
frameobj : `BaseCoordinateFrame` subclass instance
A new object in *this* frame, with the same frame attributes as
this one, but with the ``data`` as the coordinate data.
"""
return self._replicate(data, **kwargs)
def represent_as(self, base, s="base", in_frame_units=False):
"""
Generate and return a new representation of this frame's `data`
as a Representation object.
Note: In order to make an in-place change of the representation
of a Frame or SkyCoord object, set the ``representation``
attribute of that object to the desired new representation, or
use the ``set_representation_cls`` method to also set the differential.
Parameters
----------
base : subclass of BaseRepresentation or string
The type of representation to generate. Must be a *class*
(not an instance), or the string name of the representation
class.
s : subclass of `~astropy.coordinates.BaseDifferential`, str, optional
Class in which any velocities should be represented. Must be
a *class* (not an instance), or the string name of the
differential class. If equal to 'base' (default), inferred from
the base class. If `None`, all velocity information is dropped.
in_frame_units : bool, keyword-only
Force the representation units to match the specified units
particular to this frame
Returns
-------
newrep : BaseRepresentation-derived object
A new representation object of this frame's `data`.
Raises
------
AttributeError
If this object had no `data`
Examples
--------
>>> from astropy import units as u
>>> from astropy.coordinates import SkyCoord, CartesianRepresentation
>>> coord = SkyCoord(0*u.deg, 0*u.deg)
>>> coord.represent_as(CartesianRepresentation) # doctest: +FLOAT_CMP
<CartesianRepresentation (x, y, z) [dimensionless]
(1., 0., 0.)>
>>> coord.representation_type = CartesianRepresentation
>>> coord # doctest: +FLOAT_CMP
<SkyCoord (ICRS): (x, y, z) [dimensionless]
(1., 0., 0.)>
"""
# For backwards compatibility (because in_frame_units used to be the
# 2nd argument), we check to see if `new_differential` is a boolean. If
# it is, we ignore the value of `new_differential` and warn about the
# position change
if isinstance(s, bool):
warnings.warn(
"The argument position for `in_frame_units` in `represent_as` has"
" changed. Use as a keyword argument if needed.",
AstropyWarning,
)
in_frame_units = s
s = "base"
# In the future, we may want to support more differentials, in which
# case one probably needs to define **kwargs above and use it here.
# But for now, we only care about the velocity.
repr_classes = _get_repr_classes(base=base, s=s)
representation_cls = repr_classes["base"]
# We only keep velocity information
if "s" in self.data.differentials:
# For the default 'base' option in which _get_repr_classes has
# given us a best guess based on the representation class, we only
# use it if the class we had already is incompatible.
if s == "base" and (
self.data.differentials["s"].__class__
in representation_cls._compatible_differentials
):
differential_cls = self.data.differentials["s"].__class__
else:
differential_cls = repr_classes["s"]
elif s is None or s == "base":
differential_cls = None
else:
raise TypeError(
"Frame data has no associated differentials (i.e. the frame has no"
" velocity data) - represent_as() only accepts a new representation."
)
if differential_cls:
cache_key = (
representation_cls.__name__,
differential_cls.__name__,
in_frame_units,
)
else:
cache_key = (representation_cls.__name__, in_frame_units)
cached_repr = self.cache["representation"].get(cache_key)
if not cached_repr:
if differential_cls:
# Sanity check to ensure we do not just drop radial
# velocity. TODO: should Representation.represent_as
# allow this transformation in the first place?
if (
isinstance(self.data, r.UnitSphericalRepresentation)
and issubclass(representation_cls, r.CartesianRepresentation)
and not isinstance(
self.data.differentials["s"],
(
r.UnitSphericalDifferential,
r.UnitSphericalCosLatDifferential,
r.RadialDifferential,
),
)
):
raise u.UnitConversionError(
"need a distance to retrieve a cartesian representation "
"when both radial velocity and proper motion are present, "
"since otherwise the units cannot match."
)
# TODO NOTE: only supports a single differential
data = self.data.represent_as(representation_cls, differential_cls)
diff = data.differentials["s"] # TODO: assumes velocity
else:
data = self.data.represent_as(representation_cls)
# If the new representation is known to this frame and has a defined
# set of names and units, then use that.
new_attrs = self.representation_info.get(representation_cls)
if new_attrs and in_frame_units:
datakwargs = {comp: getattr(data, comp) for comp in data.components}
for comp, new_attr_unit in zip(data.components, new_attrs["units"]):
if new_attr_unit:
datakwargs[comp] = datakwargs[comp].to(new_attr_unit)
data = data.__class__(copy=False, **datakwargs)
if differential_cls:
# the original differential
data_diff = self.data.differentials["s"]
# If the new differential is known to this frame and has a
# defined set of names and units, then use that.
new_attrs = self.representation_info.get(differential_cls)
if new_attrs and in_frame_units:
diffkwargs = {comp: getattr(diff, comp) for comp in diff.components}
for comp, new_attr_unit in zip(diff.components, new_attrs["units"]):
# Some special-casing to treat a situation where the
# input data has a UnitSphericalDifferential or a
# RadialDifferential. It is re-represented to the
# frame's differential class (which might be, e.g., a
# dimensional Differential), so we don't want to try to
# convert the empty component units
if (
isinstance(
data_diff,
(
r.UnitSphericalDifferential,
r.UnitSphericalCosLatDifferential,
),
)
and comp not in data_diff.__class__.attr_classes
):
continue
elif (
isinstance(data_diff, r.RadialDifferential)
and comp not in data_diff.__class__.attr_classes
):
continue
# Try to convert to requested units. Since that might
# not be possible (e.g., for a coordinate with proper
# motion but without distance, one cannot convert to a
# cartesian differential in km/s), we allow the unit
# conversion to fail. See gh-7028 for discussion.
if new_attr_unit and hasattr(diff, comp):
try:
diffkwargs[comp] = diffkwargs[comp].to(new_attr_unit)
except Exception:
pass
diff = diff.__class__(copy=False, **diffkwargs)
# Here we have to bypass using with_differentials() because
# it has a validation check. But because
# .representation_type and .differential_type don't point to
# the original classes, if the input differential is a
# RadialDifferential, it usually gets turned into a
# SphericalCosLatDifferential (or whatever the default is)
# with strange units for the d_lon and d_lat attributes.
# This then causes the dictionary key check to fail (i.e.
# comparison against `diff._get_deriv_key()`)
data._differentials.update({"s": diff})
self.cache["representation"][cache_key] = data
return self.cache["representation"][cache_key]
def transform_to(self, new_frame):
"""
Transform this object's coordinate data to a new frame.
Parameters
----------
new_frame : coordinate-like or `BaseCoordinateFrame` subclass instance
The frame to transform this coordinate frame into.
The frame class option is deprecated.
Returns
-------
transframe : coordinate-like
A new object with the coordinate data represented in the
``newframe`` system.
Raises
------
ValueError
If there is no possible transformation route.
"""
from .errors import ConvertError
if self._data is None:
raise ValueError("Cannot transform a frame with no data")
if (
getattr(self.data, "differentials", None)
and hasattr(self, "obstime")
and hasattr(new_frame, "obstime")
and np.any(self.obstime != new_frame.obstime)
):
raise NotImplementedError(
"You cannot transform a frame that has velocities to another frame at a"
" different obstime. If you think this should (or should not) be"
" possible, please comment at"
" https://github.com/astropy/astropy/issues/6280"
)
if inspect.isclass(new_frame):
warnings.warn(
"Transforming a frame instance to a frame class (as opposed to another "
"frame instance) will not be supported in the future. Either "
"explicitly instantiate the target frame, or first convert the source "
"frame instance to a `astropy.coordinates.SkyCoord` and use its "
"`transform_to()` method.",
AstropyDeprecationWarning,
)
# Use the default frame attributes for this class
new_frame = new_frame()
if hasattr(new_frame, "_sky_coord_frame"):
# Input new_frame is not a frame instance or class and is most
# likely a SkyCoord object.
new_frame = new_frame._sky_coord_frame
trans = frame_transform_graph.get_transform(self.__class__, new_frame.__class__)
if trans is None:
if new_frame is self.__class__:
# no special transform needed, but should update frame info
return new_frame.realize_frame(self.data)
msg = "Cannot transform from {0} to {1}"
raise ConvertError(msg.format(self.__class__, new_frame.__class__))
return trans(self, new_frame)
def is_transformable_to(self, new_frame):
"""
Determines if this coordinate frame can be transformed to another
given frame.
Parameters
----------
new_frame : `BaseCoordinateFrame` subclass or instance
The proposed frame to transform into.
Returns
-------
transformable : bool or str
`True` if this can be transformed to ``new_frame``, `False` if
not, or the string 'same' if ``new_frame`` is the same system as
this object but no transformation is defined.
Notes
-----
A return value of 'same' means the transformation will work, but it will
just give back a copy of this object. The intended usage is::
if coord.is_transformable_to(some_unknown_frame):
coord2 = coord.transform_to(some_unknown_frame)
This will work even if ``some_unknown_frame`` turns out to be the same
frame class as ``coord``. This is intended for cases where the frame
is the same regardless of the frame attributes (e.g. ICRS), but be
aware that it *might* also indicate that someone forgot to define the
transformation between two objects of the same frame class but with
different attributes.
"""
new_frame_cls = new_frame if inspect.isclass(new_frame) else new_frame.__class__
trans = frame_transform_graph.get_transform(self.__class__, new_frame_cls)
if trans is None:
if new_frame_cls is self.__class__:
return "same"
else:
return False
else:
return True
def is_frame_attr_default(self, attrnm):
"""
Determine whether or not a frame attribute has its value because it's
the default value, or because this frame was created with that value
explicitly requested.
Parameters
----------
attrnm : str
The name of the attribute to check.
Returns
-------
isdefault : bool
True if the attribute ``attrnm`` has its value by default, False if
it was specified at creation of this frame.
"""
return attrnm in self._attr_names_with_defaults
@staticmethod
def _frameattr_equiv(left_fattr, right_fattr):
"""
Determine if two frame attributes are equivalent. Implemented as a
staticmethod mainly as a convenient location, although conceivable it
might be desirable for subclasses to override this behavior.
Primary purpose is to check for equality of representations. This
aspect can actually be simplified/removed now that representations have
equality defined.
Secondary purpose is to check for equality of coordinate attributes,
which first checks whether they themselves are in equivalent frames
before checking for equality in the normal fashion. This is because
checking for equality with non-equivalent frames raises an error.
"""
if left_fattr is right_fattr:
# shortcut if it's exactly the same object
return True
elif left_fattr is None or right_fattr is None:
# shortcut if one attribute is unspecified and the other isn't
return False
left_is_repr = isinstance(left_fattr, r.BaseRepresentationOrDifferential)
right_is_repr = isinstance(right_fattr, r.BaseRepresentationOrDifferential)
if left_is_repr and right_is_repr:
# both are representations.
if getattr(left_fattr, "differentials", False) or getattr(
right_fattr, "differentials", False
):
warnings.warn(
"Two representation frame attributes were checked for equivalence"
" when at least one of them has differentials. This yields False"
" even if the underlying representations are equivalent (although"
" this may change in future versions of Astropy)",
AstropyWarning,
)
return False
if isinstance(right_fattr, left_fattr.__class__):
# if same representation type, compare components.
return np.all(
[
(getattr(left_fattr, comp) == getattr(right_fattr, comp))
for comp in left_fattr.components
]
)
else:
# convert to cartesian and see if they match
return np.all(
left_fattr.to_cartesian().xyz == right_fattr.to_cartesian().xyz
)
elif left_is_repr or right_is_repr:
return False
left_is_coord = isinstance(left_fattr, BaseCoordinateFrame)
right_is_coord = isinstance(right_fattr, BaseCoordinateFrame)
if left_is_coord and right_is_coord:
# both are coordinates
if left_fattr.is_equivalent_frame(right_fattr):
return np.all(left_fattr == right_fattr)
else:
return False
elif left_is_coord or right_is_coord:
return False
return np.all(left_fattr == right_fattr)
def is_equivalent_frame(self, other):
"""
Checks if this object is the same frame as the ``other`` object.
To be the same frame, two objects must be the same frame class and have
the same frame attributes. Note that it does *not* matter what, if any,
data either object has.
Parameters
----------
other : :class:`~astropy.coordinates.BaseCoordinateFrame`
the other frame to check
Returns
-------
isequiv : bool
True if the frames are the same, False if not.
Raises
------
TypeError
If ``other`` isn't a `BaseCoordinateFrame` or subclass.
"""
if self.__class__ == other.__class__:
for frame_attr_name in self.frame_attributes:
if not self._frameattr_equiv(
getattr(self, frame_attr_name), getattr(other, frame_attr_name)
):
return False
return True
elif not isinstance(other, BaseCoordinateFrame):
raise TypeError(
"Tried to do is_equivalent_frame on something that isn't a frame"
)
else:
return False
def __repr__(self):
frameattrs = self._frame_attrs_repr()
data_repr = self._data_repr()
if frameattrs:
frameattrs = f" ({frameattrs})"
if data_repr:
return f"<{self.__class__.__name__} Coordinate{frameattrs}: {data_repr}>"
else:
return f"<{self.__class__.__name__} Frame{frameattrs}>"
def _data_repr(self):
"""Returns a string representation of the coordinate data."""
if not self.has_data:
return ""
if self.representation_type:
if hasattr(self.representation_type, "_unit_representation") and isinstance(
self.data, self.representation_type._unit_representation
):
rep_cls = self.data.__class__
else:
rep_cls = self.representation_type
if "s" in self.data.differentials:
dif_cls = self.get_representation_cls("s")
dif_data = self.data.differentials["s"]
if isinstance(
dif_data,
(
r.UnitSphericalDifferential,
r.UnitSphericalCosLatDifferential,
r.RadialDifferential,
),
):
dif_cls = dif_data.__class__
else:
dif_cls = None
data = self.represent_as(rep_cls, dif_cls, in_frame_units=True)
data_repr = repr(data)
# Generate the list of component names out of the repr string
part1, _, remainder = data_repr.partition("(")
if remainder != "":
comp_str, _, part2 = remainder.partition(")")
comp_names = comp_str.split(", ")
# Swap in frame-specific component names
invnames = {
nmrepr: nmpref
for nmpref, nmrepr in self.representation_component_names.items()
}
for i, name in enumerate(comp_names):
comp_names[i] = invnames.get(name, name)
# Reassemble the repr string
data_repr = part1 + "(" + ", ".join(comp_names) + ")" + part2
else:
data = self.data
data_repr = repr(self.data)
if data_repr.startswith("<" + data.__class__.__name__):
# remove both the leading "<" and the space after the name, as well
# as the trailing ">"
data_repr = data_repr[(len(data.__class__.__name__) + 2) : -1]
else:
data_repr = "Data:\n" + data_repr
if "s" in self.data.differentials:
data_repr_spl = data_repr.split("\n")
if "has differentials" in data_repr_spl[-1]:
diffrepr = repr(data.differentials["s"]).split("\n")
if diffrepr[0].startswith("<"):
diffrepr[0] = " " + " ".join(diffrepr[0].split(" ")[1:])
for frm_nm, rep_nm in self.get_representation_component_names(
"s"
).items():
diffrepr[0] = diffrepr[0].replace(rep_nm, frm_nm)
if diffrepr[-1].endswith(">"):
diffrepr[-1] = diffrepr[-1][:-1]
data_repr_spl[-1] = "\n".join(diffrepr)
data_repr = "\n".join(data_repr_spl)
return data_repr
def _frame_attrs_repr(self):
"""
Returns a string representation of the frame's attributes, if any.
"""
attr_strs = []
for attribute_name in self.frame_attributes:
attr = getattr(self, attribute_name)
# Check to see if this object has a way of representing itself
# specific to being an attribute of a frame. (Note, this is not the
# Attribute class, it's the actual object).
if hasattr(attr, "_astropy_repr_in_frame"):
attrstr = attr._astropy_repr_in_frame()
else:
attrstr = str(attr)
attr_strs.append(f"{attribute_name}={attrstr}")
return ", ".join(attr_strs)
def _apply(self, method, *args, **kwargs):
"""Create a new instance, applying a method to the underlying data.
In typical usage, the method is any of the shape-changing methods for
`~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those
picking particular elements (``__getitem__``, ``take``, etc.), which
are all defined in `~astropy.utils.shapes.ShapedLikeNDArray`. It will be
applied to the underlying arrays in the representation (e.g., ``x``,
``y``, and ``z`` for `~astropy.coordinates.CartesianRepresentation`),
as well as to any frame attributes that have a shape, with the results
used to create a new instance.
Internally, it is also used to apply functions to the above parts
(in particular, `~numpy.broadcast_to`).
Parameters
----------
method : str or callable
If str, it is the name of a method that is applied to the internal
``components``. If callable, the function is applied.
*args : tuple
Any positional arguments for ``method``.
**kwargs : dict
Any keyword arguments for ``method``.
"""
def apply_method(value):
if isinstance(value, ShapedLikeNDArray):
return value._apply(method, *args, **kwargs)
else:
if callable(method):
return method(value, *args, **kwargs)
else:
return getattr(value, method)(*args, **kwargs)
new = super().__new__(self.__class__)
if hasattr(self, "_representation"):
new._representation = self._representation.copy()
new._attr_names_with_defaults = self._attr_names_with_defaults.copy()
for attr in self.frame_attributes:
_attr = "_" + attr
if attr in self._attr_names_with_defaults:
setattr(new, _attr, getattr(self, _attr))
else:
value = getattr(self, _attr)
if getattr(value, "shape", ()):
value = apply_method(value)
elif method == "copy" or method == "flatten":
# flatten should copy also for a single element array, but
# we cannot use it directly for array scalars, since it
# always returns a one-dimensional array. So, just copy.
value = copy.copy(value)
setattr(new, _attr, value)
if self.has_data:
new._data = apply_method(self.data)
else:
new._data = None
shapes = [
getattr(new, "_" + attr).shape
for attr in new.frame_attributes
if (
attr not in new._attr_names_with_defaults
and getattr(getattr(new, "_" + attr), "shape", ())
)
]
if shapes:
new._no_data_shape = (
check_broadcast(*shapes) if len(shapes) > 1 else shapes[0]
)
else:
new._no_data_shape = ()
return new
def __setitem__(self, item, value):
if self.__class__ is not value.__class__:
raise TypeError(
f"can only set from object of same class: {self.__class__.__name__} vs."
f" {value.__class__.__name__}"
)
if not self.is_equivalent_frame(value):
raise ValueError("can only set frame item from an equivalent frame")
if value._data is None:
raise ValueError("can only set frame with value that has data")
if self._data is None:
raise ValueError("cannot set frame which has no data")
if self.shape == ():
raise TypeError(
f"scalar '{self.__class__.__name__}' frame object "
"does not support item assignment"
)
if self._data is None:
raise ValueError("can only set frame if it has data")
if self._data.__class__ is not value._data.__class__:
raise TypeError(
"can only set from object of same class: "
f"{self._data.__class__.__name__} vs. {value._data.__class__.__name__}"
)
if self._data._differentials:
# Can this ever occur? (Same class but different differential keys).
# This exception is not tested since it is not clear how to generate it.
if self._data._differentials.keys() != value._data._differentials.keys():
raise ValueError("setitem value must have same differentials")
for key, self_diff in self._data._differentials.items():
if self_diff.__class__ is not value._data._differentials[key].__class__:
raise TypeError(
"can only set from object of same class: "
f"{self_diff.__class__.__name__} vs. "
f"{value._data._differentials[key].__class__.__name__}"
)
# Set representation data
self._data[item] = value._data
# Frame attributes required to be identical by is_equivalent_frame,
# no need to set them here.
self.cache.clear()
def __dir__(self):
"""
Override the builtin `dir` behavior to include representation
names.
TODO: dynamic representation transforms (i.e. include cylindrical et al.).
"""
return sorted(
set(super().__dir__())
| set(self.representation_component_names)
| set(self.get_representation_component_names("s"))
)
def __getattr__(self, attr):
"""
Allow access to attributes on the representation and differential as
found via ``self.get_representation_component_names``.
TODO: We should handle dynamic representation transforms here (e.g.,
`.cylindrical`) instead of defining properties as below.
"""
# attr == '_representation' is likely from the hasattr() test in the
# representation property which is used for
# self.representation_component_names.
#
# Prevent infinite recursion here.
if attr.startswith("_"):
return self.__getattribute__(attr) # Raise AttributeError.
repr_names = self.representation_component_names
if attr in repr_names:
if self._data is None:
self.data # this raises the "no data" error by design - doing it
# this way means we don't have to replicate the error message here
rep = self.represent_as(self.representation_type, in_frame_units=True)
val = getattr(rep, repr_names[attr])
return val
diff_names = self.get_representation_component_names("s")
if attr in diff_names:
if self._data is None:
self.data # see above.
# TODO: this doesn't work for the case when there is only
# unitspherical information. The differential_type gets set to the
# default_differential, which expects full information, so the
# units don't work out
rep = self.represent_as(
in_frame_units=True, **self.get_representation_cls(None)
)
val = getattr(rep.differentials["s"], diff_names[attr])
return val
return self.__getattribute__(attr) # Raise AttributeError.
def __setattr__(self, attr, value):
# Don't slow down access of private attributes!
if not attr.startswith("_"):
if hasattr(self, "representation_info"):
repr_attr_names = set()
for representation_attr in self.representation_info.values():
repr_attr_names.update(representation_attr["names"])
if attr in repr_attr_names:
raise AttributeError(f"Cannot set any frame attribute {attr}")
super().__setattr__(attr, value)
def __eq__(self, value):
"""Equality operator for frame.
This implements strict equality and requires that the frames are
equivalent and that the representation data are exactly equal.
"""
if not isinstance(value, BaseCoordinateFrame):
return NotImplemented
is_equiv = self.is_equivalent_frame(value)
if self._data is None and value._data is None:
# For Frame with no data, == compare is same as is_equivalent_frame()
return is_equiv
if not is_equiv:
raise TypeError(
"cannot compare: objects must have equivalent frames: "
f"{self.replicate_without_data()} vs. {value.replicate_without_data()}"
)
if (value._data is None) != (self._data is None):
raise ValueError(
"cannot compare: one frame has data and the other does not"
)
return self._data == value._data
def __ne__(self, value):
return np.logical_not(self == value)
def separation(self, other):
"""
Computes on-sky separation between this coordinate and another.
.. note::
If the ``other`` coordinate object is in a different frame, it is
first transformed to the frame of this object. This can lead to
unintuitive behavior if not accounted for. Particularly of note is
that ``self.separation(other)`` and ``other.separation(self)`` may
not give the same answer in this case.
Parameters
----------
other : `~astropy.coordinates.BaseCoordinateFrame`
The coordinate to get the separation to.
Returns
-------
sep : `~astropy.coordinates.Angle`
The on-sky separation between this and the ``other`` coordinate.
Notes
-----
The separation is calculated using the Vincenty formula, which
is stable at all locations, including poles and antipodes [1]_.
.. [1] https://en.wikipedia.org/wiki/Great-circle_distance
"""
from .angle_utilities import angular_separation
from .angles import Angle
self_unit_sph = self.represent_as(r.UnitSphericalRepresentation)
other_transformed = other.transform_to(self)
other_unit_sph = other_transformed.represent_as(r.UnitSphericalRepresentation)
# Get the separation as a Quantity, convert to Angle in degrees
sep = angular_separation(
self_unit_sph.lon, self_unit_sph.lat, other_unit_sph.lon, other_unit_sph.lat
)
return Angle(sep, unit=u.degree)
def separation_3d(self, other):
"""
Computes three dimensional separation between this coordinate
and another.
Parameters
----------
other : `~astropy.coordinates.BaseCoordinateFrame`
The coordinate system to get the distance to.
Returns
-------
sep : `~astropy.coordinates.Distance`
The real-space distance between these two coordinates.
Raises
------
ValueError
If this or the other coordinate do not have distances.
"""
from .distances import Distance
if issubclass(self.data.__class__, r.UnitSphericalRepresentation):
raise ValueError(
"This object does not have a distance; cannot compute 3d separation."
)
# do this first just in case the conversion somehow creates a distance
other_in_self_system = other.transform_to(self)
if issubclass(other_in_self_system.__class__, r.UnitSphericalRepresentation):
raise ValueError(
"The other object does not have a distance; "
"cannot compute 3d separation."
)
# drop the differentials to ensure they don't do anything odd in the
# subtraction
self_car = self.data.without_differentials().represent_as(
r.CartesianRepresentation
)
other_car = other_in_self_system.data.without_differentials().represent_as(
r.CartesianRepresentation
)
dist = (self_car - other_car).norm()
if dist.unit == u.one:
return dist
else:
return Distance(dist)
@property
def cartesian(self):
"""
Shorthand for a cartesian representation of the coordinates in this
object.
"""
# TODO: if representations are updated to use a full transform graph,
# the representation aliases should not be hard-coded like this
return self.represent_as("cartesian", in_frame_units=True)
@property
def cylindrical(self):
"""
Shorthand for a cylindrical representation of the coordinates in this
object.
"""
# TODO: if representations are updated to use a full transform graph,
# the representation aliases should not be hard-coded like this
return self.represent_as("cylindrical", in_frame_units=True)
@property
def spherical(self):
"""
Shorthand for a spherical representation of the coordinates in this
object.
"""
# TODO: if representations are updated to use a full transform graph,
# the representation aliases should not be hard-coded like this
return self.represent_as("spherical", in_frame_units=True)
@property
def sphericalcoslat(self):
"""
Shorthand for a spherical representation of the positional data and a
`SphericalCosLatDifferential` for the velocity data in this object.
"""
# TODO: if representations are updated to use a full transform graph,
# the representation aliases should not be hard-coded like this
return self.represent_as("spherical", "sphericalcoslat", in_frame_units=True)
@property
def velocity(self):
"""
Shorthand for retrieving the Cartesian space-motion as a
`CartesianDifferential` object. This is equivalent to calling
``self.cartesian.differentials['s']``.
"""
if "s" not in self.data.differentials:
raise ValueError(
"Frame has no associated velocity (Differential) data information."
)
return self.cartesian.differentials["s"]
@property
def proper_motion(self):
"""
Shorthand for the two-dimensional proper motion as a
`~astropy.units.Quantity` object with angular velocity units. In the
returned `~astropy.units.Quantity`, ``axis=0`` is the longitude/latitude
dimension so that ``.proper_motion[0]`` is the longitudinal proper
motion and ``.proper_motion[1]`` is latitudinal. The longitudinal proper
motion already includes the cos(latitude) term.
"""
if "s" not in self.data.differentials:
raise ValueError(
"Frame has no associated velocity (Differential) data information."
)
sph = self.represent_as("spherical", "sphericalcoslat", in_frame_units=True)
pm_lon = sph.differentials["s"].d_lon_coslat
pm_lat = sph.differentials["s"].d_lat
return (
np.stack((pm_lon.value, pm_lat.to(pm_lon.unit).value), axis=0) * pm_lon.unit
)
@property
def radial_velocity(self):
"""
Shorthand for the radial or line-of-sight velocity as a
`~astropy.units.Quantity` object.
"""
if "s" not in self.data.differentials:
raise ValueError(
"Frame has no associated velocity (Differential) data information."
)
sph = self.represent_as("spherical", in_frame_units=True)
return sph.differentials["s"].d_distance
class GenericFrame(BaseCoordinateFrame):
"""
A frame object that can't store data but can hold any arbitrary frame
attributes. Mostly useful as a utility for the high-level class to store
intermediate frame attributes.
Parameters
----------
frame_attrs : dict
A dictionary of attributes to be used as the frame attributes for this
frame.
"""
name = None # it's not a "real" frame so it doesn't have a name
def __init__(self, frame_attrs):
self.frame_attributes = {}
for name, default in frame_attrs.items():
self.frame_attributes[name] = Attribute(default)
setattr(self, "_" + name, default)
super().__init__(None)
def __getattr__(self, name):
if "_" + name in self.__dict__:
return getattr(self, "_" + name)
else:
raise AttributeError(f"no {name}")
def __setattr__(self, name, value):
if name in self.frame_attributes:
raise AttributeError(f"can't set frame attribute '{name}'")
else:
super().__setattr__(name, value)
| bsd-3-clause | 26f64b604465b4e77f368e0c08aac9b3 | 40.050123 | 110 | 0.575134 | 4.693354 | false | false | false | false |
astropy/astropy | astropy/modeling/tests/irafutil.py | 3 | 7039 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module provides functions to help with testing against iraf tasks
"""
import numpy as np
from astropy.logger import log
iraf_models_map = {1.0: "Chebyshev", 2.0: "Legendre", 3.0: "Spline3", 4.0: "Spline1"}
def get_records(fname):
"""
Read the records of an IRAF database file into a python list
Parameters
----------
fname : str
name of an IRAF database file
Returns
-------
A list of records
"""
f = open(fname)
dtb = f.read()
f.close()
recs = dtb.split("begin")[1:]
records = [Record(r) for r in recs]
return records
def get_database_string(fname):
"""
Read an IRAF database file
Parameters
----------
fname : str
name of an IRAF database file
Returns
-------
the database file as a string
"""
f = open(fname)
dtb = f.read()
f.close()
return dtb
class Record:
"""
A base class for all records - represents an IRAF database record
Attributes
----------
recstr: string
the record as a string
fields: dict
the fields in the record
taskname: string
the name of the task which created the database file
"""
def __init__(self, recstr):
self.recstr = recstr
self.fields = self.get_fields()
self.taskname = self.get_task_name()
def aslist(self):
reclist = self.recstr.split("\n")
reclist = [entry.strip() for entry in reclist]
[reclist.remove(entry) for entry in reclist if len(entry) == 0]
return reclist
def get_fields(self):
# read record fields as an array
fields = {}
flist = self.aslist()
numfields = len(flist)
for i in range(numfields):
line = flist[i]
if line and line[0].isalpha():
field = line.split()
if i + 1 < numfields:
if not flist[i + 1][0].isalpha():
fields[field[0]] = self.read_array_field(
flist[i : i + int(field[1]) + 1]
)
else:
fields[field[0]] = " ".join(s for s in field[1:])
else:
fields[field[0]] = " ".join(s for s in field[1:])
else:
continue
return fields
def get_task_name(self):
try:
return self.fields["task"]
except KeyError:
return None
def read_array_field(self, fieldlist):
# Turn an iraf record array field into a numpy array
fieldline = [entry.split() for entry in fieldlist[1:]]
# take only the first 3 columns
# identify writes also strings at the end of some field lines
xyz = [entry[:3] for entry in fieldline]
try:
farr = np.array(xyz)
except Exception:
log.debug(f"Could not read array field {fieldlist[0].split()[0]}")
return farr.astype(np.float64)
class IdentifyRecord(Record):
"""
Represents a database record for the onedspec.identify task
Attributes
----------
x: array
the X values of the identified features
this represents values on axis1 (image rows)
y: int
the Y values of the identified features
(image columns)
z: array
the values which X maps into
modelname: string
the function used to fit the data
nterms: int
degree of the polynomial which was fit to the data
in IRAF this is the number of coefficients, not the order
mrange: list
the range of the data
coeff: array
function (modelname) coefficients
"""
def __init__(self, recstr):
super().__init__(recstr)
self._flatcoeff = self.fields["coefficients"].flatten()
self.x = self.fields["features"][:, 0]
self.y = self.get_ydata()
self.z = self.fields["features"][:, 1]
self.modelname = self.get_model_name()
self.nterms = self.get_nterms()
self.mrange = self.get_range()
self.coeff = self.get_coeff()
def get_model_name(self):
return iraf_models_map[self._flatcoeff[0]]
def get_nterms(self):
return self._flatcoeff[1]
def get_range(self):
low = self._flatcoeff[2]
high = self._flatcoeff[3]
return [low, high]
def get_coeff(self):
return self._flatcoeff[4:]
def get_ydata(self):
image = self.fields["image"]
left = image.find("[") + 1
right = image.find("]")
section = image[left:right]
if "," in section:
yind = image.find(",") + 1
return int(image[yind:-1])
else:
return int(section)
class FitcoordsRecord(Record):
"""
Represents a database record for the longslit.fitccords task
Attributes
----------
modelname: string
the function used to fit the data
xorder: int
number of terms in x
yorder: int
number of terms in y
xbounds: list
data range in x
ybounds: list
data range in y
coeff: array
function coefficients
"""
def __init__(self, recstr):
super().__init__(recstr)
self._surface = self.fields["surface"].flatten()
self.modelname = iraf_models_map[self._surface[0]]
self.xorder = self._surface[1]
self.yorder = self._surface[2]
self.xbounds = [self._surface[4], self._surface[5]]
self.ybounds = [self._surface[6], self._surface[7]]
self.coeff = self.get_coeff()
def get_coeff(self):
return self._surface[8:]
class IDB:
"""
Base class for an IRAF identify database
Attributes
----------
records: list
a list of all `IdentifyRecord` in the database
numrecords: int
number of records
"""
def __init__(self, dtbstr):
self.records = [IdentifyRecord(rstr) for rstr in self.aslist(dtbstr)]
self.numrecords = len(self.records)
def aslist(self, dtb):
# return a list of records
# if the first one is a comment remove it from the list
rl = dtb.split("begin")
try:
rl0 = rl[0].split("\n")
except Exception:
return rl
if len(rl0) == 2 and rl0[0].startswith("#") and not rl0[1].strip():
return rl[1:]
else:
return rl
class ReidentifyRecord(IDB):
"""
Represents a database record for the onedspec.reidentify task
"""
def __init__(self, databasestr):
super().__init__(databasestr)
self.x = np.array([r.x for r in self.records])
self.y = self.get_ydata()
self.z = np.array([r.z for r in self.records])
def get_ydata(self):
y = np.ones(self.x.shape)
y = y * np.array([r.y for r in self.records])[:, np.newaxis]
return y
| bsd-3-clause | b4c5541186a52e3f4ab11ad9d4f44dc3 | 25.462406 | 85 | 0.553346 | 3.897564 | false | false | false | false |
astropy/astropy | astropy/units/utils.py | 3 | 8991 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Miscellaneous utilities for `astropy.units`.
None of the functions in the module are meant for use outside of the
package.
"""
import io
import re
from fractions import Fraction
import numpy as np
from numpy import finfo
_float_finfo = finfo(float)
# take float here to ensure comparison with another float is fast
# give a little margin since often multiple calculations happened
_JUST_BELOW_UNITY = float(1.0 - 4.0 * _float_finfo.epsneg)
_JUST_ABOVE_UNITY = float(1.0 + 4.0 * _float_finfo.eps)
def _get_first_sentence(s):
"""
Get the first sentence from a string and remove any carriage
returns.
"""
x = re.match(r".*?\S\.\s", s)
if x is not None:
s = x.group(0)
return s.replace("\n", " ")
def _iter_unit_summary(namespace):
"""
Generates the ``(unit, doc, represents, aliases, prefixes)``
tuple used to format the unit summary docs in `generate_unit_summary`.
"""
from . import core
# Get all of the units, and keep track of which ones have SI
# prefixes
units = []
has_prefixes = set()
for key, val in namespace.items():
# Skip non-unit items
if not isinstance(val, core.UnitBase):
continue
# Skip aliases
if key != val.name:
continue
if isinstance(val, core.PrefixUnit):
# This will return the root unit that is scaled by the prefix
# attached to it
has_prefixes.add(val._represents.bases[0].name)
else:
units.append(val)
# Sort alphabetically, case insensitive
units.sort(key=lambda x: x.name.lower())
for unit in units:
doc = _get_first_sentence(unit.__doc__).strip()
represents = ""
if isinstance(unit, core.Unit):
represents = f":math:`{unit._represents.to_string('latex')[1:-1]}`"
aliases = ", ".join(f"``{x}``" for x in unit.aliases)
yield (
unit,
doc,
represents,
aliases,
"Yes" if unit.name in has_prefixes else "No",
)
def generate_unit_summary(namespace):
"""
Generates a summary of units from a given namespace. This is used
to generate the docstring for the modules that define the actual
units.
Parameters
----------
namespace : dict
A namespace containing units.
Returns
-------
docstring : str
A docstring containing a summary table of the units.
"""
docstring = io.StringIO()
docstring.write(
"""
.. list-table:: Available Units
:header-rows: 1
:widths: 10 20 20 20 1
* - Unit
- Description
- Represents
- Aliases
- SI Prefixes
"""
)
template = """
* - ``{}``
- {}
- {}
- {}
- {}
"""
for unit_summary in _iter_unit_summary(namespace):
docstring.write(template.format(*unit_summary))
return docstring.getvalue()
def generate_prefixonly_unit_summary(namespace):
"""
Generates table entries for units in a namespace that are just prefixes
without the base unit. Note that this is intended to be used *after*
`generate_unit_summary` and therefore does not include the table header.
Parameters
----------
namespace : dict
A namespace containing units that are prefixes but do *not* have the
base unit in their namespace.
Returns
-------
docstring : str
A docstring containing a summary table of the units.
"""
from . import PrefixUnit
faux_namespace = {}
for nm, unit in namespace.items():
if isinstance(unit, PrefixUnit):
base_unit = unit.represents.bases[0]
faux_namespace[base_unit.name] = base_unit
docstring = io.StringIO()
template = """
* - Prefixes for ``{}``
- {} prefixes
- {}
- {}
- Only
"""
for unit_summary in _iter_unit_summary(faux_namespace):
docstring.write(template.format(*unit_summary))
return docstring.getvalue()
def is_effectively_unity(value):
# value is *almost* always real, except, e.g., for u.mag**0.5, when
# it will be complex. Use try/except to ensure normal case is fast
try:
return _JUST_BELOW_UNITY <= value <= _JUST_ABOVE_UNITY
except TypeError: # value is complex
return (
_JUST_BELOW_UNITY <= value.real <= _JUST_ABOVE_UNITY
and _JUST_BELOW_UNITY <= value.imag + 1 <= _JUST_ABOVE_UNITY
)
def sanitize_scale(scale):
if is_effectively_unity(scale):
return 1.0
# Maximum speed for regular case where scale is a float.
if scale.__class__ is float:
return scale
# We cannot have numpy scalars, since they don't autoconvert to
# complex if necessary. They are also slower.
if hasattr(scale, "dtype"):
scale = scale.item()
# All classes that scale can be (int, float, complex, Fraction)
# have an "imag" attribute.
if scale.imag:
if abs(scale.real) > abs(scale.imag):
if is_effectively_unity(scale.imag / scale.real + 1):
return scale.real
elif is_effectively_unity(scale.real / scale.imag + 1):
return complex(0.0, scale.imag)
return scale
else:
return scale.real
def maybe_simple_fraction(p, max_denominator=100):
"""Fraction very close to x with denominator at most max_denominator.
The fraction has to be such that fraction/x is unity to within 4 ulp.
If such a fraction does not exist, returns the float number.
The algorithm is that of `fractions.Fraction.limit_denominator`, but
sped up by not creating a fraction to start with.
"""
if p == 0 or p.__class__ is int:
return p
n, d = p.as_integer_ratio()
a = n // d
# Normally, start with 0,1 and 1,0; here we have applied first iteration.
n0, d0 = 1, 0
n1, d1 = a, 1
while d1 <= max_denominator:
if _JUST_BELOW_UNITY <= n1 / (d1 * p) <= _JUST_ABOVE_UNITY:
return Fraction(n1, d1)
n, d = d, n - a * d
a = n // d
n0, n1 = n1, n0 + a * n1
d0, d1 = d1, d0 + a * d1
return p
def validate_power(p):
"""Convert a power to a floating point value, an integer, or a Fraction.
If a fractional power can be represented exactly as a floating point
number, convert it to a float, to make the math much faster; otherwise,
retain it as a `fractions.Fraction` object to avoid losing precision.
Conversely, if the value is indistinguishable from a rational number with a
low-numbered denominator, convert to a Fraction object.
Parameters
----------
p : float, int, Rational, Fraction
Power to be converted
"""
denom = getattr(p, "denominator", None)
if denom is None:
try:
p = float(p)
except Exception:
if not np.isscalar(p):
raise ValueError(
"Quantities and Units may only be raised to a scalar power"
)
else:
raise
# This returns either a (simple) Fraction or the same float.
p = maybe_simple_fraction(p)
# If still a float, nothing more to be done.
if isinstance(p, float):
return p
# Otherwise, check for simplifications.
denom = p.denominator
if denom == 1:
p = p.numerator
elif (denom & (denom - 1)) == 0:
# Above is a bit-twiddling hack to see if denom is a power of two.
# If so, float does not lose precision and will speed things up.
p = float(p)
return p
def resolve_fractions(a, b):
"""
If either input is a Fraction, convert the other to a Fraction
(at least if it does not have a ridiculous denominator).
This ensures that any operation involving a Fraction will use
rational arithmetic and preserve precision.
"""
# We short-circuit on the most common cases of int and float, since
# isinstance(a, Fraction) is very slow for any non-Fraction instances.
a_is_fraction = (
a.__class__ is not int and a.__class__ is not float and isinstance(a, Fraction)
)
b_is_fraction = (
b.__class__ is not int and b.__class__ is not float and isinstance(b, Fraction)
)
if a_is_fraction and not b_is_fraction:
b = maybe_simple_fraction(b)
elif not a_is_fraction and b_is_fraction:
a = maybe_simple_fraction(a)
return a, b
def quantity_asanyarray(a, dtype=None):
from .quantity import Quantity
if (
not isinstance(a, np.ndarray)
and not np.isscalar(a)
and any(isinstance(x, Quantity) for x in a)
):
return Quantity(a, dtype=dtype)
else:
# skip over some dtype deprecation deprecation.
dtype = np.float64 if dtype is np.inexact else dtype
return np.asanyarray(a, dtype=dtype)
| bsd-3-clause | b8126c342557652290fe443fbaf2666a | 27.633758 | 87 | 0.60605 | 3.860455 | false | false | false | false |
astropy/astropy | astropy/cosmology/io/html.py | 3 | 7434 | import astropy.cosmology.units as cu
import astropy.units as u
from astropy.cosmology.connect import readwrite_registry
from astropy.cosmology.core import Cosmology
from astropy.cosmology.parameter import Parameter
from astropy.table import QTable
from .table import from_table, to_table
# Format look-up for conversion, {original_name: new_name}
# TODO! move this information into the Parameters themselves
_FORMAT_TABLE = {
"H0": "$$H_{0}$$",
"Om0": "$$\\Omega_{m,0}$$",
"Ode0": "$$\\Omega_{\\Lambda,0}$$",
"Tcmb0": "$$T_{0}$$",
"Neff": "$$N_{eff}$$",
"m_nu": "$$m_{nu}$$",
"Ob0": "$$\\Omega_{b,0}$$",
"w0": "$$w_{0}$$",
"wa": "$$w_{a}$$",
"wz": "$$w_{z}$$",
"wp": "$$w_{p}$$",
"zp": "$$z_{p}$$",
}
def read_html_table(
filename,
index=None,
*,
move_to_meta=False,
cosmology=None,
latex_names=True,
**kwargs,
):
"""Read a |Cosmology| from an HTML file.
Parameters
----------
filename : path-like or file-like
From where to read the Cosmology.
index : int or str or None, optional
Needed to select the row in tables with multiple rows. ``index`` can be
an integer for the row number or, if the table is indexed by a column,
the value of that column. If the table is not indexed and ``index`` is a
string, the "name" column is used as the indexing column.
move_to_meta : bool, optional keyword-only
Whether to move keyword arguments that are not in the Cosmology class'
signature to the Cosmology's metadata. This will only be applied if the
Cosmology does NOT have a keyword-only argument (e.g. ``**kwargs``).
Arguments moved to the metadata will be merged with existing metadata,
preferring specified metadata in the case of a merge conflict (e.g. for
``Cosmology(meta={'key':10}, key=42)``, the ``Cosmology.meta`` will be
``{'key': 10}``).
cosmology : str or |Cosmology| class or None, optional keyword-only
The cosmology class (or string name thereof) to use when constructing
the cosmology instance. The class also provides default parameter
values, filling in any non-mandatory arguments missing in 'table'.
latex_names : bool, optional keyword-only
Whether the |Table| (might) have latex column names for the parameters
that need to be mapped to the correct parameter name -- e.g. $$H_{0}$$
to 'H0'. This is `True` by default, but can be turned off (set to
`False`) if there is a known name conflict (e.g. both an 'H0' and
'$$H_{0}$$' column) as this will raise an error. In this case, the
correct name ('H0') is preferred.
**kwargs : Any
Passed to :attr:`astropy.table.QTable.read`. ``format`` is set to
'ascii.html', regardless of input.
Returns
-------
|Cosmology| subclass instance
Raises
------
ValueError
If the keyword argument 'format' is given and is not "ascii.html".
"""
# Check that the format is 'ascii.html' (or not specified)
format = kwargs.pop("format", "ascii.html")
if format != "ascii.html":
raise ValueError(f"format must be 'ascii.html', not {format}")
# Reading is handled by `QTable`.
with u.add_enabled_units(cu): # (cosmology units not turned on by default)
table = QTable.read(filename, format="ascii.html", **kwargs)
# Need to map the table's column names to Cosmology inputs (parameter
# names).
# TODO! move the `latex_names` into `from_table`
if latex_names:
table_columns = set(table.colnames)
for name, latex in _FORMAT_TABLE.items():
if latex in table_columns:
table.rename_column(latex, name)
# Build the cosmology from table, using the private backend.
return from_table(
table, index=index, move_to_meta=move_to_meta, cosmology=cosmology
)
def write_html_table(
cosmology, file, *, overwrite=False, cls=QTable, latex_names=False, **kwargs
):
r"""Serialize the |Cosmology| into a HTML table.
Parameters
----------
cosmology : |Cosmology| subclass instance file : path-like or file-like
Location to save the serialized cosmology.
file : path-like or file-like
Where to write the html table.
overwrite : bool, optional keyword-only
Whether to overwrite the file, if it exists.
cls : |Table| class, optional keyword-only
Astropy |Table| (sub)class to use when writing. Default is |QTable|
class.
latex_names : bool, optional keyword-only
Whether to format the parameters (column) names to latex -- e.g. 'H0' to
$$H_{0}$$.
**kwargs : Any
Passed to ``cls.write``.
Raises
------
TypeError
If the optional keyword-argument 'cls' is not a subclass of |Table|.
ValueError
If the keyword argument 'format' is given and is not "ascii.html".
Notes
-----
A HTML file containing a Cosmology HTML table should have scripts enabling
MathJax.
::
<script
src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script type="text/javascript" id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js">
</script>
"""
# Check that the format is 'ascii.html' (or not specified)
format = kwargs.pop("format", "ascii.html")
if format != "ascii.html":
raise ValueError(f"format must be 'ascii.html', not {format}")
# Set cosmology_in_meta as false for now since there is no metadata being kept
table = to_table(cosmology, cls=cls, cosmology_in_meta=False)
cosmo_cls = type(cosmology)
for name, col in table.columns.items():
param = getattr(cosmo_cls, name, None)
if not isinstance(param, Parameter) or param.unit in (None, u.one):
continue
# Replace column with unitless version
table.replace_column(name, (col << param.unit).value, copy=False)
# TODO! move the `latex_names` into `to_table`
if latex_names:
new_names = [_FORMAT_TABLE.get(k, k) for k in cosmology.__parameters__]
table.rename_columns(cosmology.__parameters__, new_names)
# Write HTML, using table I/O
table.write(file, overwrite=overwrite, format="ascii.html", **kwargs)
def html_identify(origin, filepath, fileobj, *args, **kwargs):
"""Identify if an object uses the HTML Table format.
Parameters
----------
origin : Any
Not used.
filepath : str or Any
From where to read the Cosmology.
fileobj : Any
Not used.
*args : Any
Not used.
**kwargs : Any
Not used.
Returns
-------
bool
If the filepath is a string ending with '.html'.
"""
return isinstance(filepath, str) and filepath.endswith(".html")
# ===================================================================
# Register
readwrite_registry.register_reader("ascii.html", Cosmology, read_html_table)
readwrite_registry.register_writer("ascii.html", Cosmology, write_html_table)
readwrite_registry.register_identifier("ascii.html", Cosmology, html_identify)
| bsd-3-clause | 1f6bbd729dee8c8dbe0b2cc2e65ed738 | 34.985075 | 82 | 0.60869 | 3.745088 | false | false | false | false |
astropy/astropy | astropy/coordinates/representation.py | 3 | 141494 | """
In this module, we define the coordinate representation classes, which are
used to represent low-level cartesian, spherical, cylindrical, and other
coordinates.
"""
import abc
import functools
import inspect
import operator
import warnings
import numpy as np
from erfa import ufunc as erfa_ufunc
import astropy.units as u
from astropy.utils import ShapedLikeNDArray, classproperty
from astropy.utils.data_info import MixinInfo
from astropy.utils.exceptions import DuplicateRepresentationWarning
from .angles import Angle, Latitude, Longitude
from .distances import Distance
from .matrix_utilities import is_O3
__all__ = [
"BaseRepresentationOrDifferential",
"BaseRepresentation",
"CartesianRepresentation",
"SphericalRepresentation",
"UnitSphericalRepresentation",
"RadialRepresentation",
"PhysicsSphericalRepresentation",
"CylindricalRepresentation",
"BaseDifferential",
"CartesianDifferential",
"BaseSphericalDifferential",
"BaseSphericalCosLatDifferential",
"SphericalDifferential",
"SphericalCosLatDifferential",
"UnitSphericalDifferential",
"UnitSphericalCosLatDifferential",
"RadialDifferential",
"CylindricalDifferential",
"PhysicsSphericalDifferential",
]
# Module-level dict mapping representation string alias names to classes.
# This is populated by __init_subclass__ when called by Representation or
# Differential classes so that they are all registered automatically.
REPRESENTATION_CLASSES = {}
DIFFERENTIAL_CLASSES = {}
# set for tracking duplicates
DUPLICATE_REPRESENTATIONS = set()
# a hash for the content of the above two dicts, cached for speed.
_REPRDIFF_HASH = None
def _fqn_class(cls):
"""Get the fully qualified name of a class"""
return cls.__module__ + "." + cls.__qualname__
def get_reprdiff_cls_hash():
"""
Returns a hash value that should be invariable if the
`REPRESENTATION_CLASSES` and `DIFFERENTIAL_CLASSES` dictionaries have not
changed.
"""
global _REPRDIFF_HASH
if _REPRDIFF_HASH is None:
_REPRDIFF_HASH = hash(tuple(REPRESENTATION_CLASSES.items())) + hash(
tuple(DIFFERENTIAL_CLASSES.items())
)
return _REPRDIFF_HASH
def _invalidate_reprdiff_cls_hash():
global _REPRDIFF_HASH
_REPRDIFF_HASH = None
def _array2string(values, prefix=""):
# Work around version differences for array2string.
kwargs = {"separator": ", ", "prefix": prefix}
kwargs["formatter"] = {}
return np.array2string(values, **kwargs)
class BaseRepresentationOrDifferentialInfo(MixinInfo):
"""
Container for meta information like name, description, format. This is
required when the object is used as a mixin column within a table, but can
be used as a general way to store meta information.
"""
attrs_from_parent = {"unit"} # Indicates unit is read-only
_supports_indexing = False
@staticmethod
def default_format(val):
# Create numpy dtype so that numpy formatting will work.
components = val.components
values = tuple(getattr(val, component).value for component in components)
a = np.empty(
getattr(val, "shape", ()),
[(component, value.dtype) for component, value in zip(components, values)],
)
for component, value in zip(components, values):
a[component] = value
return str(a)
@property
def _represent_as_dict_attrs(self):
return self._parent.components
@property
def unit(self):
if self._parent is None:
return None
unit = self._parent._unitstr
return unit[1:-1] if unit.startswith("(") else unit
def new_like(self, reps, length, metadata_conflicts="warn", name=None):
"""
Return a new instance like ``reps`` with ``length`` rows.
This is intended for creating an empty column object whose elements can
be set in-place for table operations like join or vstack.
Parameters
----------
reps : list
List of input representations or differentials.
length : int
Length of the output column object
metadata_conflicts : str ('warn'|'error'|'silent')
How to handle metadata conflicts
name : str
Output column name
Returns
-------
col : `BaseRepresentation` or `BaseDifferential` subclass instance
Empty instance of this class consistent with ``cols``
"""
# Get merged info attributes like shape, dtype, format, description, etc.
attrs = self.merge_cols_attributes(
reps, metadata_conflicts, name, ("meta", "description")
)
# Make a new representation or differential with the desired length
# using the _apply / __getitem__ machinery to effectively return
# rep0[[0, 0, ..., 0, 0]]. This will have the right shape, and
# include possible differentials.
indexes = np.zeros(length, dtype=np.int64)
out = reps[0][indexes]
# Use __setitem__ machinery to check whether all representations
# can represent themselves as this one without loss of information.
for rep in reps[1:]:
try:
out[0] = rep[0]
except Exception as err:
raise ValueError("input representations are inconsistent.") from err
# Set (merged) info attributes.
for attr in ("name", "meta", "description"):
if attr in attrs:
setattr(out.info, attr, attrs[attr])
return out
class BaseRepresentationOrDifferential(ShapedLikeNDArray):
"""3D coordinate representations and differentials.
Parameters
----------
comp1, comp2, comp3 : `~astropy.units.Quantity` or subclass
The components of the 3D point or differential. The names are the
keys and the subclasses the values of the ``attr_classes`` attribute.
copy : bool, optional
If `True` (default), arrays will be copied; if `False`, they will be
broadcast together but not use new memory.
"""
# Ensure multiplication/division with ndarray or Quantity doesn't lead to
# object arrays.
__array_priority__ = 50000
info = BaseRepresentationOrDifferentialInfo()
def __init__(self, *args, **kwargs):
# make argument a list, so we can pop them off.
args = list(args)
components = self.components
if (
args
and isinstance(args[0], self.__class__)
and all(arg is None for arg in args[1:])
):
rep_or_diff = args[0]
copy = kwargs.pop("copy", True)
attrs = [getattr(rep_or_diff, component) for component in components]
if "info" in rep_or_diff.__dict__:
self.info = rep_or_diff.info
if kwargs:
raise TypeError(
"unexpected keyword arguments for case "
f"where class instance is passed in: {kwargs}"
)
else:
attrs = []
for component in components:
try:
attr = args.pop(0) if args else kwargs.pop(component)
except KeyError:
raise TypeError(
"__init__() missing 1 required positional "
f"argument: {component!r}"
) from None
if attr is None:
raise TypeError(
"__init__() missing 1 required positional argument:"
f" {component!r} (or first argument should be an instance of"
f" {self.__class__.__name__})."
)
attrs.append(attr)
copy = args.pop(0) if args else kwargs.pop("copy", True)
if args:
raise TypeError(f"unexpected arguments: {args}")
if kwargs:
for component in components:
if component in kwargs:
raise TypeError(
f"__init__() got multiple values for argument {component!r}"
)
raise TypeError(f"unexpected keyword arguments: {kwargs}")
# Pass attributes through the required initializing classes.
attrs = [
self.attr_classes[component](attr, copy=copy, subok=True)
for component, attr in zip(components, attrs)
]
try:
bc_attrs = np.broadcast_arrays(*attrs, subok=True)
except ValueError as err:
if len(components) <= 2:
c_str = " and ".join(components)
else:
c_str = ", ".join(components[:2]) + ", and " + components[2]
raise ValueError(f"Input parameters {c_str} cannot be broadcast") from err
# The output of np.broadcast_arrays() has limitations on writeability, so we perform
# additional handling to enable writeability in most situations. This is primarily
# relevant for allowing the changing of the wrap angle of longitude components.
#
# If the shape has changed for a given component, broadcasting is needed:
# If copy=True, we make a copy of the broadcasted array to ensure writeability.
# Note that array had already been copied prior to the broadcasting.
# TODO: Find a way to avoid the double copy.
# If copy=False, we use the broadcasted array, and writeability may still be
# limited.
# If the shape has not changed for a given component, we can proceed with using the
# non-broadcasted array, which avoids writeability issues from np.broadcast_arrays().
attrs = [
(bc_attr.copy() if copy else bc_attr)
if bc_attr.shape != attr.shape
else attr
for attr, bc_attr in zip(attrs, bc_attrs)
]
# Set private attributes for the attributes. (If not defined explicitly
# on the class, the metaclass will define properties to access these.)
for component, attr in zip(components, attrs):
setattr(self, "_" + component, attr)
@classmethod
def get_name(cls):
"""Name of the representation or differential.
In lower case, with any trailing 'representation' or 'differential'
removed. (E.g., 'spherical' for
`~astropy.coordinates.SphericalRepresentation` or
`~astropy.coordinates.SphericalDifferential`.)
"""
name = cls.__name__.lower()
if name.endswith("representation"):
name = name[:-14]
elif name.endswith("differential"):
name = name[:-12]
return name
# The two methods that any subclass has to define.
@classmethod
@abc.abstractmethod
def from_cartesian(cls, other):
"""Create a representation of this class from a supplied Cartesian one.
Parameters
----------
other : `CartesianRepresentation`
The representation to turn into this class
Returns
-------
representation : `BaseRepresentation` subclass instance
A new representation of this class's type.
"""
# Note: the above docstring gets overridden for differentials.
raise NotImplementedError()
@abc.abstractmethod
def to_cartesian(self):
"""Convert the representation to its Cartesian form.
Note that any differentials get dropped.
Also note that orientation information at the origin is *not* preserved by
conversions through Cartesian coordinates. For example, transforming
an angular position defined at distance=0 through cartesian coordinates
and back will lose the original angular coordinates::
>>> import astropy.units as u
>>> import astropy.coordinates as coord
>>> rep = coord.SphericalRepresentation(
... lon=15*u.deg,
... lat=-11*u.deg,
... distance=0*u.pc)
>>> rep.to_cartesian().represent_as(coord.SphericalRepresentation)
<SphericalRepresentation (lon, lat, distance) in (rad, rad, pc)
(0., 0., 0.)>
Returns
-------
cartrepr : `CartesianRepresentation`
The representation in Cartesian form.
"""
# Note: the above docstring gets overridden for differentials.
raise NotImplementedError()
@property
def components(self):
"""A tuple with the in-order names of the coordinate components."""
return tuple(self.attr_classes)
def __eq__(self, value):
"""Equality operator
This implements strict equality and requires that the representation
classes are identical and that the representation data are exactly equal.
"""
if self.__class__ is not value.__class__:
raise TypeError(
"cannot compare: objects must have same class: "
f"{self.__class__.__name__} vs. {value.__class__.__name__}"
)
try:
np.broadcast(self, value)
except ValueError as exc:
raise ValueError(f"cannot compare: {exc}") from exc
out = True
for comp in self.components:
out &= getattr(self, "_" + comp) == getattr(value, "_" + comp)
return out
def __ne__(self, value):
return np.logical_not(self == value)
def _apply(self, method, *args, **kwargs):
"""Create a new representation or differential with ``method`` applied
to the component data.
In typical usage, the method is any of the shape-changing methods for
`~numpy.ndarray` (``reshape``, ``swapaxes``, etc.), as well as those
picking particular elements (``__getitem__``, ``take``, etc.), which
are all defined in `~astropy.utils.shapes.ShapedLikeNDArray`. It will be
applied to the underlying arrays (e.g., ``x``, ``y``, and ``z`` for
`~astropy.coordinates.CartesianRepresentation`), with the results used
to create a new instance.
Internally, it is also used to apply functions to the components
(in particular, `~numpy.broadcast_to`).
Parameters
----------
method : str or callable
If str, it is the name of a method that is applied to the internal
``components``. If callable, the function is applied.
*args : tuple
Any positional arguments for ``method``.
**kwargs : dict
Any keyword arguments for ``method``.
"""
if callable(method):
apply_method = lambda array: method(array, *args, **kwargs)
else:
apply_method = operator.methodcaller(method, *args, **kwargs)
new = super().__new__(self.__class__)
for component in self.components:
setattr(new, "_" + component, apply_method(getattr(self, component)))
# Copy other 'info' attr only if it has actually been defined.
# See PR #3898 for further explanation and justification, along
# with Quantity.__array_finalize__
if "info" in self.__dict__:
new.info = self.info
return new
def __setitem__(self, item, value):
if value.__class__ is not self.__class__:
raise TypeError(
"can only set from object of same class: "
f"{self.__class__.__name__} vs. {value.__class__.__name__}"
)
for component in self.components:
getattr(self, "_" + component)[item] = getattr(value, "_" + component)
@property
def shape(self):
"""The shape of the instance and underlying arrays.
Like `~numpy.ndarray.shape`, can be set to a new shape by assigning a
tuple. Note that if different instances share some but not all
underlying data, setting the shape of one instance can make the other
instance unusable. Hence, it is strongly recommended to get new,
reshaped instances with the ``reshape`` method.
Raises
------
ValueError
If the new shape has the wrong total number of elements.
AttributeError
If the shape of any of the components cannot be changed without the
arrays being copied. For these cases, use the ``reshape`` method
(which copies any arrays that cannot be reshaped in-place).
"""
return getattr(self, self.components[0]).shape
@shape.setter
def shape(self, shape):
# We keep track of arrays that were already reshaped since we may have
# to return those to their original shape if a later shape-setting
# fails. (This can happen since coordinates are broadcast together.)
reshaped = []
oldshape = self.shape
for component in self.components:
val = getattr(self, component)
if val.size > 1:
try:
val.shape = shape
except Exception:
for val2 in reshaped:
val2.shape = oldshape
raise
else:
reshaped.append(val)
# Required to support multiplication and division, and defined by the base
# representation and differential classes.
@abc.abstractmethod
def _scale_operation(self, op, *args):
raise NotImplementedError()
def __mul__(self, other):
return self._scale_operation(operator.mul, other)
def __rmul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
return self._scale_operation(operator.truediv, other)
def __neg__(self):
return self._scale_operation(operator.neg)
# Follow numpy convention and make an independent copy.
def __pos__(self):
return self.copy()
# Required to support addition and subtraction, and defined by the base
# representation and differential classes.
@abc.abstractmethod
def _combine_operation(self, op, other, reverse=False):
raise NotImplementedError()
def __add__(self, other):
return self._combine_operation(operator.add, other)
def __radd__(self, other):
return self._combine_operation(operator.add, other, reverse=True)
def __sub__(self, other):
return self._combine_operation(operator.sub, other)
def __rsub__(self, other):
return self._combine_operation(operator.sub, other, reverse=True)
# The following are used for repr and str
@property
def _values(self):
"""Turn the coordinates into a record array with the coordinate values.
The record array fields will have the component names.
"""
coo_items = [(c, getattr(self, c)) for c in self.components]
result = np.empty(self.shape, [(c, coo.dtype) for c, coo in coo_items])
for c, coo in coo_items:
result[c] = coo.value
return result
@property
def _units(self):
"""Return a dictionary with the units of the coordinate components."""
return {cmpnt: getattr(self, cmpnt).unit for cmpnt in self.components}
@property
def _unitstr(self):
units_set = set(self._units.values())
if len(units_set) == 1:
unitstr = units_set.pop().to_string()
else:
unitstr = "({})".format(
", ".join(
self._units[component].to_string() for component in self.components
)
)
return unitstr
def __str__(self):
return f"{_array2string(self._values)} {self._unitstr:s}"
def __repr__(self):
prefixstr = " "
arrstr = _array2string(self._values, prefix=prefixstr)
diffstr = ""
if getattr(self, "differentials", None):
diffstr = "\n (has differentials w.r.t.: {})".format(
", ".join([repr(key) for key in self.differentials.keys()])
)
unitstr = ("in " + self._unitstr) if self._unitstr else "[dimensionless]"
return (
f"<{self.__class__.__name__} ({', '.join(self.components)})"
f" {unitstr:s}\n{prefixstr}{arrstr}{diffstr}>"
)
def _make_getter(component):
"""Make an attribute getter for use in a property.
Parameters
----------
component : str
The name of the component that should be accessed. This assumes the
actual value is stored in an attribute of that name prefixed by '_'.
"""
# This has to be done in a function to ensure the reference to component
# is not lost/redirected.
component = "_" + component
def get_component(self):
return getattr(self, component)
return get_component
class RepresentationInfo(BaseRepresentationOrDifferentialInfo):
@property
def _represent_as_dict_attrs(self):
attrs = super()._represent_as_dict_attrs
if self._parent._differentials:
attrs += ("differentials",)
return attrs
def _represent_as_dict(self, attrs=None):
out = super()._represent_as_dict(attrs)
for key, value in out.pop("differentials", {}).items():
out[f"differentials.{key}"] = value
return out
def _construct_from_dict(self, map):
differentials = {}
for key in list(map.keys()):
if key.startswith("differentials."):
differentials[key[14:]] = map.pop(key)
map["differentials"] = differentials
return super()._construct_from_dict(map)
class BaseRepresentation(BaseRepresentationOrDifferential):
"""Base for representing a point in a 3D coordinate system.
Parameters
----------
comp1, comp2, comp3 : `~astropy.units.Quantity` or subclass
The components of the 3D points. The names are the keys and the
subclasses the values of the ``attr_classes`` attribute.
differentials : dict, `~astropy.coordinates.BaseDifferential`, optional
Any differential classes that should be associated with this
representation. The input must either be a single `~astropy.coordinates.BaseDifferential`
subclass instance, or a dictionary with keys set to a string
representation of the SI unit with which the differential (derivative)
is taken. For example, for a velocity differential on a positional
representation, the key would be ``'s'`` for seconds, indicating that
the derivative is a time derivative.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
Notes
-----
All representation classes should subclass this base representation class,
and define an ``attr_classes`` attribute, a `dict`
which maps component names to the class that creates them. They must also
define a ``to_cartesian`` method and a ``from_cartesian`` class method. By
default, transformations are done via the cartesian system, but classes
that want to define a smarter transformation path can overload the
``represent_as`` method. If one wants to use an associated differential
class, one should also define ``unit_vectors`` and ``scale_factors``
methods (see those methods for details).
"""
info = RepresentationInfo()
def __init_subclass__(cls, **kwargs):
# Register representation name (except for BaseRepresentation)
if cls.__name__ == "BaseRepresentation":
return
if not hasattr(cls, "attr_classes"):
raise NotImplementedError(
'Representations must have an "attr_classes" class attribute.'
)
repr_name = cls.get_name()
# first time a duplicate is added
# remove first entry and add both using their qualnames
if repr_name in REPRESENTATION_CLASSES:
DUPLICATE_REPRESENTATIONS.add(repr_name)
fqn_cls = _fqn_class(cls)
existing = REPRESENTATION_CLASSES[repr_name]
fqn_existing = _fqn_class(existing)
if fqn_cls == fqn_existing:
raise ValueError(f'Representation "{fqn_cls}" already defined')
msg = (
f'Representation "{repr_name}" already defined, removing it to avoid'
f' confusion.Use qualnames "{fqn_cls}" and "{fqn_existing}" or class'
" instances directly"
)
warnings.warn(msg, DuplicateRepresentationWarning)
del REPRESENTATION_CLASSES[repr_name]
REPRESENTATION_CLASSES[fqn_existing] = existing
repr_name = fqn_cls
# further definitions with the same name, just add qualname
elif repr_name in DUPLICATE_REPRESENTATIONS:
fqn_cls = _fqn_class(cls)
warnings.warn(
f'Representation "{repr_name}" already defined, using qualname '
f'"{fqn_cls}".'
)
repr_name = fqn_cls
if repr_name in REPRESENTATION_CLASSES:
raise ValueError(f'Representation "{repr_name}" already defined')
REPRESENTATION_CLASSES[repr_name] = cls
_invalidate_reprdiff_cls_hash()
# define getters for any component that does not yet have one.
for component in cls.attr_classes:
if not hasattr(cls, component):
setattr(
cls,
component,
property(
_make_getter(component),
doc=f"The '{component}' component of the points(s).",
),
)
super().__init_subclass__(**kwargs)
def __init__(self, *args, differentials=None, **kwargs):
# Handle any differentials passed in.
super().__init__(*args, **kwargs)
if differentials is None and args and isinstance(args[0], self.__class__):
differentials = args[0]._differentials
self._differentials = self._validate_differentials(differentials)
def _validate_differentials(self, differentials):
"""
Validate that the provided differentials are appropriate for this
representation and recast/reshape as necessary and then return.
Note that this does *not* set the differentials on
``self._differentials``, but rather leaves that for the caller.
"""
# Now handle the actual validation of any specified differential classes
if differentials is None:
differentials = dict()
elif isinstance(differentials, BaseDifferential):
# We can't handle auto-determining the key for this combo
if isinstance(differentials, RadialDifferential) and isinstance(
self, UnitSphericalRepresentation
):
raise ValueError(
"To attach a RadialDifferential to a UnitSphericalRepresentation,"
" you must supply a dictionary with an appropriate key."
)
key = differentials._get_deriv_key(self)
differentials = {key: differentials}
for key in differentials:
try:
diff = differentials[key]
except TypeError as err:
raise TypeError(
"'differentials' argument must be a dictionary-like object"
) from err
diff._check_base(self)
if isinstance(diff, RadialDifferential) and isinstance(
self, UnitSphericalRepresentation
):
# We trust the passing of a key for a RadialDifferential
# attached to a UnitSphericalRepresentation because it will not
# have a paired component name (UnitSphericalRepresentation has
# no .distance) to automatically determine the expected key
pass
else:
expected_key = diff._get_deriv_key(self)
if key != expected_key:
raise ValueError(
f"For differential object '{repr(diff)}', expected "
f"unit key = '{expected_key}' but received key = '{key}'"
)
# For now, we are very rigid: differentials must have the same shape
# as the representation. This makes it easier to handle __getitem__
# and any other shape-changing operations on representations that
# have associated differentials
if diff.shape != self.shape:
# TODO: message of IncompatibleShapeError is not customizable,
# so use a valueerror instead?
raise ValueError(
"Shape of differentials must be the same "
f"as the shape of the representation ({diff.shape} vs {self.shape})"
)
return differentials
def _raise_if_has_differentials(self, op_name):
"""
Used to raise a consistent exception for any operation that is not
supported when a representation has differentials attached.
"""
if self.differentials:
raise TypeError(
f"Operation '{op_name}' is not supported when "
f"differentials are attached to a {self.__class__.__name__}."
)
@classproperty
def _compatible_differentials(cls):
return [DIFFERENTIAL_CLASSES[cls.get_name()]]
@property
def differentials(self):
"""A dictionary of differential class instances.
The keys of this dictionary must be a string representation of the SI
unit with which the differential (derivative) is taken. For example, for
a velocity differential on a positional representation, the key would be
``'s'`` for seconds, indicating that the derivative is a time
derivative.
"""
return self._differentials
# We do not make unit_vectors and scale_factors abstract methods, since
# they are only necessary if one also defines an associated Differential.
# Also, doing so would break pre-differential representation subclasses.
def unit_vectors(self):
r"""Cartesian unit vectors in the direction of each component.
Given unit vectors :math:`\hat{e}_c` and scale factors :math:`f_c`,
a change in one component of :math:`\delta c` corresponds to a change
in representation of :math:`\delta c \times f_c \times \hat{e}_c`.
Returns
-------
unit_vectors : dict of `CartesianRepresentation`
The keys are the component names.
"""
raise NotImplementedError(f"{type(self)} has not implemented unit vectors")
def scale_factors(self):
r"""Scale factors for each component's direction.
Given unit vectors :math:`\hat{e}_c` and scale factors :math:`f_c`,
a change in one component of :math:`\delta c` corresponds to a change
in representation of :math:`\delta c \times f_c \times \hat{e}_c`.
Returns
-------
scale_factors : dict of `~astropy.units.Quantity`
The keys are the component names.
"""
raise NotImplementedError(f"{type(self)} has not implemented scale factors.")
def _re_represent_differentials(self, new_rep, differential_class):
"""Re-represent the differentials to the specified classes.
This returns a new dictionary with the same keys but with the
attached differentials converted to the new differential classes.
"""
if differential_class is None:
return dict()
if not self.differentials and differential_class:
raise ValueError("No differentials associated with this representation!")
elif (
len(self.differentials) == 1
and inspect.isclass(differential_class)
and issubclass(differential_class, BaseDifferential)
):
# TODO: is there a better way to do this?
differential_class = {
list(self.differentials.keys())[0]: differential_class
}
elif differential_class.keys() != self.differentials.keys():
raise ValueError(
"Desired differential classes must be passed in as a dictionary with"
" keys equal to a string representation of the unit of the derivative"
" for each differential stored with this "
f"representation object ({self.differentials})"
)
new_diffs = dict()
for k in self.differentials:
diff = self.differentials[k]
try:
new_diffs[k] = diff.represent_as(differential_class[k], base=self)
except Exception as err:
if differential_class[k] not in new_rep._compatible_differentials:
raise TypeError(
f"Desired differential class {differential_class[k]} is not "
"compatible with the desired "
f"representation class {new_rep.__class__}"
) from err
else:
raise
return new_diffs
def represent_as(self, other_class, differential_class=None):
"""Convert coordinates to another representation.
If the instance is of the requested class, it is returned unmodified.
By default, conversion is done via Cartesian coordinates.
Also note that orientation information at the origin is *not* preserved by
conversions through Cartesian coordinates. See the docstring for
:meth:`~astropy.coordinates.BaseRepresentationOrDifferential.to_cartesian`
for an example.
Parameters
----------
other_class : `~astropy.coordinates.BaseRepresentation` subclass
The type of representation to turn the coordinates into.
differential_class : dict of `~astropy.coordinates.BaseDifferential`, optional
Classes in which the differentials should be represented.
Can be a single class if only a single differential is attached,
otherwise it should be a `dict` keyed by the same keys as the
differentials.
"""
if other_class is self.__class__ and not differential_class:
return self.without_differentials()
else:
if isinstance(other_class, str):
raise ValueError(
"Input to a representation's represent_as must be a class, not "
"a string. For strings, use frame objects."
)
if other_class is not self.__class__:
# The default is to convert via cartesian coordinates
new_rep = other_class.from_cartesian(self.to_cartesian())
else:
new_rep = self
new_rep._differentials = self._re_represent_differentials(
new_rep, differential_class
)
return new_rep
def transform(self, matrix):
"""Transform coordinates using a 3x3 matrix in a Cartesian basis.
This returns a new representation and does not modify the original one.
Any differentials attached to this representation will also be
transformed.
Parameters
----------
matrix : (3,3) array-like
A 3x3 (or stack thereof) matrix, such as a rotation matrix.
"""
# route transformation through Cartesian
difs_cls = {k: CartesianDifferential for k in self.differentials.keys()}
crep = self.represent_as(
CartesianRepresentation, differential_class=difs_cls
).transform(matrix)
# move back to original representation
difs_cls = {k: diff.__class__ for k, diff in self.differentials.items()}
rep = crep.represent_as(self.__class__, difs_cls)
return rep
def with_differentials(self, differentials):
"""
Create a new representation with the same positions as this
representation, but with these new differentials.
Differential keys that already exist in this object's differential dict
are overwritten.
Parameters
----------
differentials : sequence of `~astropy.coordinates.BaseDifferential` subclass instance
The differentials for the new representation to have.
Returns
-------
`~astropy.coordinates.BaseRepresentation` subclass instance
A copy of this representation, but with the ``differentials`` as
its differentials.
"""
if not differentials:
return self
args = [getattr(self, component) for component in self.components]
# We shallow copy the differentials dictionary so we don't update the
# current object's dictionary when adding new keys
new_rep = self.__class__(
*args, differentials=self.differentials.copy(), copy=False
)
new_rep._differentials.update(new_rep._validate_differentials(differentials))
return new_rep
def without_differentials(self):
"""Return a copy of the representation without attached differentials.
Returns
-------
`~astropy.coordinates.BaseRepresentation` subclass instance
A shallow copy of this representation, without any differentials.
If no differentials were present, no copy is made.
"""
if not self._differentials:
return self
args = [getattr(self, component) for component in self.components]
return self.__class__(*args, copy=False)
@classmethod
def from_representation(cls, representation):
"""Create a new instance of this representation from another one.
Parameters
----------
representation : `~astropy.coordinates.BaseRepresentation` instance
The presentation that should be converted to this class.
"""
return representation.represent_as(cls)
def __eq__(self, value):
"""Equality operator for BaseRepresentation
This implements strict equality and requires that the representation
classes are identical, the differentials are identical, and that the
representation data are exactly equal.
"""
# BaseRepresentationOrDifferental (checks classes and compares components)
out = super().__eq__(value)
# super() checks that the class is identical so can this even happen?
# (same class, different differentials ?)
if self._differentials.keys() != value._differentials.keys():
raise ValueError("cannot compare: objects must have same differentials")
for self_diff, value_diff in zip(
self._differentials.values(), value._differentials.values()
):
out &= self_diff == value_diff
return out
def __ne__(self, value):
return np.logical_not(self == value)
def _apply(self, method, *args, **kwargs):
"""Create a new representation with ``method`` applied to the component
data.
This is not a simple inherit from ``BaseRepresentationOrDifferential``
because we need to call ``._apply()`` on any associated differential
classes.
See docstring for `BaseRepresentationOrDifferential._apply`.
Parameters
----------
method : str or callable
If str, it is the name of a method that is applied to the internal
``components``. If callable, the function is applied.
*args : tuple
Any positional arguments for ``method``.
**kwargs : dict
Any keyword arguments for ``method``.
"""
rep = super()._apply(method, *args, **kwargs)
rep._differentials = {
k: diff._apply(method, *args, **kwargs)
for k, diff in self._differentials.items()
}
return rep
def __setitem__(self, item, value):
if not isinstance(value, BaseRepresentation):
raise TypeError(
f"value must be a representation instance, not {type(value)}."
)
if not (
isinstance(value, self.__class__)
or len(value.attr_classes) == len(self.attr_classes)
):
raise ValueError(
f"value must be representable as {self.__class__.__name__} "
"without loss of information."
)
diff_classes = {}
if self._differentials:
if self._differentials.keys() != value._differentials.keys():
raise ValueError("value must have the same differentials.")
for key, self_diff in self._differentials.items():
diff_classes[key] = self_diff_cls = self_diff.__class__
value_diff_cls = value._differentials[key].__class__
if not (
isinstance(value_diff_cls, self_diff_cls)
or (
len(value_diff_cls.attr_classes)
== len(self_diff_cls.attr_classes)
)
):
raise ValueError(
f"value differential {key!r} must be representable as "
f"{self_diff.__class__.__name__} without loss of information."
)
value = value.represent_as(self.__class__, diff_classes)
super().__setitem__(item, value)
for key, differential in self._differentials.items():
differential[item] = value._differentials[key]
def _scale_operation(self, op, *args):
"""Scale all non-angular components, leaving angular ones unchanged.
Parameters
----------
op : `~operator` callable
Operator to apply (e.g., `~operator.mul`, `~operator.neg`, etc.
*args
Any arguments required for the operator (typically, what is to
be multiplied with, divided by).
"""
results = []
for component, cls in self.attr_classes.items():
value = getattr(self, component)
if issubclass(cls, Angle):
results.append(value)
else:
results.append(op(value, *args))
# try/except catches anything that cannot initialize the class, such
# as operations that returned NotImplemented or a representation
# instead of a quantity (as would happen for, e.g., rep * rep).
try:
result = self.__class__(*results)
except Exception:
return NotImplemented
for key, differential in self.differentials.items():
diff_result = differential._scale_operation(op, *args, scaled_base=True)
result.differentials[key] = diff_result
return result
def _combine_operation(self, op, other, reverse=False):
"""Combine two representation.
By default, operate on the cartesian representations of both.
Parameters
----------
op : `~operator` callable
Operator to apply (e.g., `~operator.add`, `~operator.sub`, etc.
other : `~astropy.coordinates.BaseRepresentation` subclass instance
The other representation.
reverse : bool
Whether the operands should be reversed (e.g., as we got here via
``self.__rsub__`` because ``self`` is a subclass of ``other``).
"""
self._raise_if_has_differentials(op.__name__)
result = self.to_cartesian()._combine_operation(op, other, reverse)
if result is NotImplemented:
return NotImplemented
else:
return self.from_cartesian(result)
# We need to override this setter to support differentials
@BaseRepresentationOrDifferential.shape.setter
def shape(self, shape):
orig_shape = self.shape
# See: https://stackoverflow.com/questions/3336767/ for an example
BaseRepresentationOrDifferential.shape.fset(self, shape)
# also try to perform shape-setting on any associated differentials
try:
for k in self.differentials:
self.differentials[k].shape = shape
except Exception:
BaseRepresentationOrDifferential.shape.fset(self, orig_shape)
for k in self.differentials:
self.differentials[k].shape = orig_shape
raise
def norm(self):
"""Vector norm.
The norm is the standard Frobenius norm, i.e., the square root of the
sum of the squares of all components with non-angular units.
Note that any associated differentials will be dropped during this
operation.
Returns
-------
norm : `astropy.units.Quantity`
Vector norm, with the same shape as the representation.
"""
return np.sqrt(
sum(
getattr(self, component) ** 2
for component, cls in self.attr_classes.items()
if not issubclass(cls, Angle)
)
)
def mean(self, *args, **kwargs):
"""Vector mean.
Averaging is done by converting the representation to cartesian, and
taking the mean of the x, y, and z components. The result is converted
back to the same representation as the input.
Refer to `~numpy.mean` for full documentation of the arguments, noting
that ``axis`` is the entry in the ``shape`` of the representation, and
that the ``out`` argument cannot be used.
Returns
-------
mean : `~astropy.coordinates.BaseRepresentation` subclass instance
Vector mean, in the same representation as that of the input.
"""
self._raise_if_has_differentials("mean")
return self.from_cartesian(self.to_cartesian().mean(*args, **kwargs))
def sum(self, *args, **kwargs):
"""Vector sum.
Adding is done by converting the representation to cartesian, and
summing the x, y, and z components. The result is converted back to the
same representation as the input.
Refer to `~numpy.sum` for full documentation of the arguments, noting
that ``axis`` is the entry in the ``shape`` of the representation, and
that the ``out`` argument cannot be used.
Returns
-------
sum : `~astropy.coordinates.BaseRepresentation` subclass instance
Vector sum, in the same representation as that of the input.
"""
self._raise_if_has_differentials("sum")
return self.from_cartesian(self.to_cartesian().sum(*args, **kwargs))
def dot(self, other):
"""Dot product of two representations.
The calculation is done by converting both ``self`` and ``other``
to `~astropy.coordinates.CartesianRepresentation`.
Note that any associated differentials will be dropped during this
operation.
Parameters
----------
other : `~astropy.coordinates.BaseRepresentation`
The representation to take the dot product with.
Returns
-------
dot_product : `~astropy.units.Quantity`
The sum of the product of the x, y, and z components of the
cartesian representations of ``self`` and ``other``.
"""
return self.to_cartesian().dot(other)
def cross(self, other):
"""Vector cross product of two representations.
The calculation is done by converting both ``self`` and ``other``
to `~astropy.coordinates.CartesianRepresentation`, and converting the
result back to the type of representation of ``self``.
Parameters
----------
other : `~astropy.coordinates.BaseRepresentation` subclass instance
The representation to take the cross product with.
Returns
-------
cross_product : `~astropy.coordinates.BaseRepresentation` subclass instance
With vectors perpendicular to both ``self`` and ``other``, in the
same type of representation as ``self``.
"""
self._raise_if_has_differentials("cross")
return self.from_cartesian(self.to_cartesian().cross(other))
class CartesianRepresentation(BaseRepresentation):
"""
Representation of points in 3D cartesian coordinates.
Parameters
----------
x, y, z : `~astropy.units.Quantity` or array
The x, y, and z coordinates of the point(s). If ``x``, ``y``, and ``z``
have different shapes, they should be broadcastable. If not quantity,
``unit`` should be set. If only ``x`` is given, it is assumed that it
contains an array with the 3 coordinates stored along ``xyz_axis``.
unit : unit-like
If given, the coordinates will be converted to this unit (or taken to
be in this unit if not given.
xyz_axis : int, optional
The axis along which the coordinates are stored when a single array is
provided rather than distinct ``x``, ``y``, and ``z`` (default: 0).
differentials : dict, `CartesianDifferential`, optional
Any differential classes that should be associated with this
representation. The input must either be a single
`CartesianDifferential` instance, or a dictionary of
`CartesianDifferential` s with keys set to a string representation of
the SI unit with which the differential (derivative) is taken. For
example, for a velocity differential on a positional representation, the
key would be ``'s'`` for seconds, indicating that the derivative is a
time derivative.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
attr_classes = {"x": u.Quantity, "y": u.Quantity, "z": u.Quantity}
_xyz = None
def __init__(
self, x, y=None, z=None, unit=None, xyz_axis=None, differentials=None, copy=True
):
if y is None and z is None:
if isinstance(x, np.ndarray) and x.dtype.kind not in "OV":
# Short-cut for 3-D array input.
x = u.Quantity(x, unit, copy=copy, subok=True)
# Keep a link to the array with all three coordinates
# so that we can return it quickly if needed in get_xyz.
self._xyz = x
if xyz_axis:
x = np.moveaxis(x, xyz_axis, 0)
self._xyz_axis = xyz_axis
else:
self._xyz_axis = 0
self._x, self._y, self._z = x
self._differentials = self._validate_differentials(differentials)
return
elif (
isinstance(x, CartesianRepresentation)
and unit is None
and xyz_axis is None
):
if differentials is None:
differentials = x._differentials
return super().__init__(x, differentials=differentials, copy=copy)
else:
x, y, z = x
if xyz_axis is not None:
raise ValueError(
"xyz_axis should only be set if x, y, and z are in a single array"
" passed in through x, i.e., y and z should not be not given."
)
if y is None or z is None:
raise ValueError(
f"x, y, and z are required to instantiate {self.__class__.__name__}"
)
if unit is not None:
x = u.Quantity(x, unit, copy=copy, subok=True)
y = u.Quantity(y, unit, copy=copy, subok=True)
z = u.Quantity(z, unit, copy=copy, subok=True)
copy = False
super().__init__(x, y, z, copy=copy, differentials=differentials)
if not (
self._x.unit.is_equivalent(self._y.unit)
and self._x.unit.is_equivalent(self._z.unit)
):
raise u.UnitsError("x, y, and z should have matching physical types")
def unit_vectors(self):
l = np.broadcast_to(1.0 * u.one, self.shape, subok=True)
o = np.broadcast_to(0.0 * u.one, self.shape, subok=True)
return {
"x": CartesianRepresentation(l, o, o, copy=False),
"y": CartesianRepresentation(o, l, o, copy=False),
"z": CartesianRepresentation(o, o, l, copy=False),
}
def scale_factors(self):
l = np.broadcast_to(1.0 * u.one, self.shape, subok=True)
return {"x": l, "y": l, "z": l}
def get_xyz(self, xyz_axis=0):
"""Return a vector array of the x, y, and z coordinates.
Parameters
----------
xyz_axis : int, optional
The axis in the final array along which the x, y, z components
should be stored (default: 0).
Returns
-------
xyz : `~astropy.units.Quantity`
With dimension 3 along ``xyz_axis``. Note that, if possible,
this will be a view.
"""
if self._xyz is not None:
if self._xyz_axis == xyz_axis:
return self._xyz
else:
return np.moveaxis(self._xyz, self._xyz_axis, xyz_axis)
# Create combined array. TO DO: keep it in _xyz for repeated use?
# But then in-place changes have to cancel it. Likely best to
# also update components.
return np.stack([self._x, self._y, self._z], axis=xyz_axis)
xyz = property(get_xyz)
@classmethod
def from_cartesian(cls, other):
return other
def to_cartesian(self):
return self
def transform(self, matrix):
"""
Transform the cartesian coordinates using a 3x3 matrix.
This returns a new representation and does not modify the original one.
Any differentials attached to this representation will also be
transformed.
Parameters
----------
matrix : ndarray
A 3x3 transformation matrix, such as a rotation matrix.
Examples
--------
We can start off by creating a cartesian representation object:
>>> from astropy import units as u
>>> from astropy.coordinates import CartesianRepresentation
>>> rep = CartesianRepresentation([1, 2] * u.pc,
... [2, 3] * u.pc,
... [3, 4] * u.pc)
We now create a rotation matrix around the z axis:
>>> from astropy.coordinates.matrix_utilities import rotation_matrix
>>> rotation = rotation_matrix(30 * u.deg, axis='z')
Finally, we can apply this transformation:
>>> rep_new = rep.transform(rotation)
>>> rep_new.xyz # doctest: +FLOAT_CMP
<Quantity [[ 1.8660254 , 3.23205081],
[ 1.23205081, 1.59807621],
[ 3. , 4. ]] pc>
"""
# erfa rxp: Multiply a p-vector by an r-matrix.
p = erfa_ufunc.rxp(matrix, self.get_xyz(xyz_axis=-1))
# transformed representation
rep = self.__class__(p, xyz_axis=-1, copy=False)
# Handle differentials attached to this representation
new_diffs = {
k: d.transform(matrix, self, rep) for k, d in self.differentials.items()
}
return rep.with_differentials(new_diffs)
def _combine_operation(self, op, other, reverse=False):
self._raise_if_has_differentials(op.__name__)
try:
other_c = other.to_cartesian()
except Exception:
return NotImplemented
first, second = (self, other_c) if not reverse else (other_c, self)
return self.__class__(
*(
op(getattr(first, component), getattr(second, component))
for component in first.components
)
)
def norm(self):
"""Vector norm.
The norm is the standard Frobenius norm, i.e., the square root of the
sum of the squares of all components with non-angular units.
Note that any associated differentials will be dropped during this
operation.
Returns
-------
norm : `astropy.units.Quantity`
Vector norm, with the same shape as the representation.
"""
# erfa pm: Modulus of p-vector.
return erfa_ufunc.pm(self.get_xyz(xyz_axis=-1))
def mean(self, *args, **kwargs):
"""Vector mean.
Returns a new CartesianRepresentation instance with the means of the
x, y, and z components.
Refer to `~numpy.mean` for full documentation of the arguments, noting
that ``axis`` is the entry in the ``shape`` of the representation, and
that the ``out`` argument cannot be used.
"""
self._raise_if_has_differentials("mean")
return self._apply("mean", *args, **kwargs)
def sum(self, *args, **kwargs):
"""Vector sum.
Returns a new CartesianRepresentation instance with the sums of the
x, y, and z components.
Refer to `~numpy.sum` for full documentation of the arguments, noting
that ``axis`` is the entry in the ``shape`` of the representation, and
that the ``out`` argument cannot be used.
"""
self._raise_if_has_differentials("sum")
return self._apply("sum", *args, **kwargs)
def dot(self, other):
"""Dot product of two representations.
Note that any associated differentials will be dropped during this
operation.
Parameters
----------
other : `~astropy.coordinates.BaseRepresentation` subclass instance
If not already cartesian, it is converted.
Returns
-------
dot_product : `~astropy.units.Quantity`
The sum of the product of the x, y, and z components of ``self``
and ``other``.
"""
try:
other_c = other.to_cartesian()
except Exception as err:
raise TypeError(
"can only take dot product with another "
f"representation, not a {type(other)} instance."
) from err
# erfa pdp: p-vector inner (=scalar=dot) product.
return erfa_ufunc.pdp(self.get_xyz(xyz_axis=-1), other_c.get_xyz(xyz_axis=-1))
def cross(self, other):
"""Cross product of two representations.
Parameters
----------
other : `~astropy.coordinates.BaseRepresentation` subclass instance
If not already cartesian, it is converted.
Returns
-------
cross_product : `~astropy.coordinates.CartesianRepresentation`
With vectors perpendicular to both ``self`` and ``other``.
"""
self._raise_if_has_differentials("cross")
try:
other_c = other.to_cartesian()
except Exception as err:
raise TypeError(
"cannot only take cross product with another "
f"representation, not a {type(other)} instance."
) from err
# erfa pxp: p-vector outer (=vector=cross) product.
sxo = erfa_ufunc.pxp(self.get_xyz(xyz_axis=-1), other_c.get_xyz(xyz_axis=-1))
return self.__class__(sxo, xyz_axis=-1)
class UnitSphericalRepresentation(BaseRepresentation):
"""
Representation of points on a unit sphere.
Parameters
----------
lon, lat : `~astropy.units.Quantity` ['angle'] or str
The longitude and latitude of the point(s), in angular units. The
latitude should be between -90 and 90 degrees, and the longitude will
be wrapped to an angle between 0 and 360 degrees. These can also be
instances of `~astropy.coordinates.Angle`,
`~astropy.coordinates.Longitude`, or `~astropy.coordinates.Latitude`.
differentials : dict, `~astropy.coordinates.BaseDifferential`, optional
Any differential classes that should be associated with this
representation. The input must either be a single `~astropy.coordinates.BaseDifferential`
instance (see `._compatible_differentials` for valid types), or a
dictionary of of differential instances with keys set to a string
representation of the SI unit with which the differential (derivative)
is taken. For example, for a velocity differential on a positional
representation, the key would be ``'s'`` for seconds, indicating that
the derivative is a time derivative.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
attr_classes = {"lon": Longitude, "lat": Latitude}
@classproperty
def _dimensional_representation(cls):
return SphericalRepresentation
def __init__(self, lon, lat=None, differentials=None, copy=True):
super().__init__(lon, lat, differentials=differentials, copy=copy)
@classproperty
def _compatible_differentials(cls):
return [
UnitSphericalDifferential,
UnitSphericalCosLatDifferential,
SphericalDifferential,
SphericalCosLatDifferential,
RadialDifferential,
]
# Could let the metaclass define these automatically, but good to have
# a bit clearer docstrings.
@property
def lon(self):
"""
The longitude of the point(s).
"""
return self._lon
@property
def lat(self):
"""
The latitude of the point(s).
"""
return self._lat
def unit_vectors(self):
sinlon, coslon = np.sin(self.lon), np.cos(self.lon)
sinlat, coslat = np.sin(self.lat), np.cos(self.lat)
return {
"lon": CartesianRepresentation(-sinlon, coslon, 0.0, copy=False),
"lat": CartesianRepresentation(
-sinlat * coslon, -sinlat * sinlon, coslat, copy=False
),
}
def scale_factors(self, omit_coslat=False):
sf_lat = np.broadcast_to(1.0 / u.radian, self.shape, subok=True)
sf_lon = sf_lat if omit_coslat else np.cos(self.lat) / u.radian
return {"lon": sf_lon, "lat": sf_lat}
def to_cartesian(self):
"""
Converts spherical polar coordinates to 3D rectangular cartesian
coordinates.
"""
# erfa s2c: Convert [unit]spherical coordinates to Cartesian.
p = erfa_ufunc.s2c(self.lon, self.lat)
return CartesianRepresentation(p, xyz_axis=-1, copy=False)
@classmethod
def from_cartesian(cls, cart):
"""
Converts 3D rectangular cartesian coordinates to spherical polar
coordinates.
"""
p = cart.get_xyz(xyz_axis=-1)
# erfa c2s: P-vector to [unit]spherical coordinates.
return cls(*erfa_ufunc.c2s(p), copy=False)
def represent_as(self, other_class, differential_class=None):
# Take a short cut if the other class is a spherical representation
# TODO! for differential_class. This cannot (currently) be implemented
# like in the other Representations since `_re_represent_differentials`
# keeps differentials' unit keys, but this can result in a mismatch
# between the UnitSpherical expected key (e.g. "s") and that expected
# in the other class (here "s / m"). For more info, see PR #11467
if inspect.isclass(other_class) and not differential_class:
if issubclass(other_class, PhysicsSphericalRepresentation):
return other_class(
phi=self.lon, theta=90 * u.deg - self.lat, r=1.0, copy=False
)
elif issubclass(other_class, SphericalRepresentation):
return other_class(lon=self.lon, lat=self.lat, distance=1.0, copy=False)
return super().represent_as(other_class, differential_class)
def transform(self, matrix):
r"""Transform the unit-spherical coordinates using a 3x3 matrix.
This returns a new representation and does not modify the original one.
Any differentials attached to this representation will also be
transformed.
Parameters
----------
matrix : (3,3) array-like
A 3x3 matrix, such as a rotation matrix (or a stack of matrices).
Returns
-------
`UnitSphericalRepresentation` or `SphericalRepresentation`
If ``matrix`` is O(3) -- :math:`M \dot M^T = I` -- like a rotation,
then the result is a `UnitSphericalRepresentation`.
All other matrices will change the distance, so the dimensional
representation is used instead.
"""
# the transformation matrix does not need to be a rotation matrix,
# so the unit-distance is not guaranteed. For speed, we check if the
# matrix is in O(3) and preserves lengths.
if np.all(is_O3(matrix)): # remain in unit-rep
xyz = erfa_ufunc.s2c(self.lon, self.lat)
p = erfa_ufunc.rxp(matrix, xyz)
lon, lat = erfa_ufunc.c2s(p)
rep = self.__class__(lon=lon, lat=lat)
# handle differentials
new_diffs = {
k: d.transform(matrix, self, rep) for k, d in self.differentials.items()
}
rep = rep.with_differentials(new_diffs)
else: # switch to dimensional representation
rep = self._dimensional_representation(
lon=self.lon, lat=self.lat, distance=1, differentials=self.differentials
).transform(matrix)
return rep
def _scale_operation(self, op, *args):
return self._dimensional_representation(
lon=self.lon, lat=self.lat, distance=1.0, differentials=self.differentials
)._scale_operation(op, *args)
def __neg__(self):
if any(
differential.base_representation is not self.__class__
for differential in self.differentials.values()
):
return super().__neg__()
result = self.__class__(self.lon + 180.0 * u.deg, -self.lat, copy=False)
for key, differential in self.differentials.items():
new_comps = (
op(getattr(differential, comp))
for op, comp in zip(
(operator.pos, operator.neg), differential.components
)
)
result.differentials[key] = differential.__class__(*new_comps, copy=False)
return result
def norm(self):
"""Vector norm.
The norm is the standard Frobenius norm, i.e., the square root of the
sum of the squares of all components with non-angular units, which is
always unity for vectors on the unit sphere.
Returns
-------
norm : `~astropy.units.Quantity` ['dimensionless']
Dimensionless ones, with the same shape as the representation.
"""
return u.Quantity(np.ones(self.shape), u.dimensionless_unscaled, copy=False)
def _combine_operation(self, op, other, reverse=False):
self._raise_if_has_differentials(op.__name__)
result = self.to_cartesian()._combine_operation(op, other, reverse)
if result is NotImplemented:
return NotImplemented
else:
return self._dimensional_representation.from_cartesian(result)
def mean(self, *args, **kwargs):
"""Vector mean.
The representation is converted to cartesian, the means of the x, y,
and z components are calculated, and the result is converted to a
`~astropy.coordinates.SphericalRepresentation`.
Refer to `~numpy.mean` for full documentation of the arguments, noting
that ``axis`` is the entry in the ``shape`` of the representation, and
that the ``out`` argument cannot be used.
"""
self._raise_if_has_differentials("mean")
return self._dimensional_representation.from_cartesian(
self.to_cartesian().mean(*args, **kwargs)
)
def sum(self, *args, **kwargs):
"""Vector sum.
The representation is converted to cartesian, the sums of the x, y,
and z components are calculated, and the result is converted to a
`~astropy.coordinates.SphericalRepresentation`.
Refer to `~numpy.sum` for full documentation of the arguments, noting
that ``axis`` is the entry in the ``shape`` of the representation, and
that the ``out`` argument cannot be used.
"""
self._raise_if_has_differentials("sum")
return self._dimensional_representation.from_cartesian(
self.to_cartesian().sum(*args, **kwargs)
)
def cross(self, other):
"""Cross product of two representations.
The calculation is done by converting both ``self`` and ``other``
to `~astropy.coordinates.CartesianRepresentation`, and converting the
result back to `~astropy.coordinates.SphericalRepresentation`.
Parameters
----------
other : `~astropy.coordinates.BaseRepresentation` subclass instance
The representation to take the cross product with.
Returns
-------
cross_product : `~astropy.coordinates.SphericalRepresentation`
With vectors perpendicular to both ``self`` and ``other``.
"""
self._raise_if_has_differentials("cross")
return self._dimensional_representation.from_cartesian(
self.to_cartesian().cross(other)
)
class RadialRepresentation(BaseRepresentation):
"""
Representation of the distance of points from the origin.
Note that this is mostly intended as an internal helper representation.
It can do little else but being used as a scale in multiplication.
Parameters
----------
distance : `~astropy.units.Quantity` ['length']
The distance of the point(s) from the origin.
differentials : dict, `~astropy.coordinates.BaseDifferential`, optional
Any differential classes that should be associated with this
representation. The input must either be a single `~astropy.coordinates.BaseDifferential`
instance (see `._compatible_differentials` for valid types), or a
dictionary of of differential instances with keys set to a string
representation of the SI unit with which the differential (derivative)
is taken. For example, for a velocity differential on a positional
representation, the key would be ``'s'`` for seconds, indicating that
the derivative is a time derivative.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
attr_classes = {"distance": u.Quantity}
def __init__(self, distance, differentials=None, copy=True):
super().__init__(distance, differentials=differentials, copy=copy)
@property
def distance(self):
"""
The distance from the origin to the point(s).
"""
return self._distance
def unit_vectors(self):
"""Cartesian unit vectors are undefined for radial representation."""
raise NotImplementedError(
f"Cartesian unit vectors are undefined for {self.__class__} instances"
)
def scale_factors(self):
l = np.broadcast_to(1.0 * u.one, self.shape, subok=True)
return {"distance": l}
def to_cartesian(self):
"""Cannot convert radial representation to cartesian."""
raise NotImplementedError(
f"cannot convert {self.__class__} instance to cartesian."
)
@classmethod
def from_cartesian(cls, cart):
"""
Converts 3D rectangular cartesian coordinates to radial coordinate.
"""
return cls(distance=cart.norm(), copy=False)
def __mul__(self, other):
if isinstance(other, BaseRepresentation):
return self.distance * other
else:
return super().__mul__(other)
def norm(self):
"""Vector norm.
Just the distance itself.
Returns
-------
norm : `~astropy.units.Quantity` ['dimensionless']
Dimensionless ones, with the same shape as the representation.
"""
return self.distance
def _combine_operation(self, op, other, reverse=False):
return NotImplemented
def transform(self, matrix):
"""Radial representations cannot be transformed by a Cartesian matrix.
Parameters
----------
matrix : array-like
The transformation matrix in a Cartesian basis.
Must be a multiplication: a diagonal matrix with identical elements.
Must have shape (..., 3, 3), where the last 2 indices are for the
matrix on each other axis. Make sure that the matrix shape is
compatible with the shape of this representation.
Raises
------
ValueError
If the matrix is not a multiplication.
"""
scl = matrix[..., 0, 0]
# check that the matrix is a scaled identity matrix on the last 2 axes.
if np.any(matrix != scl[..., np.newaxis, np.newaxis] * np.identity(3)):
raise ValueError(
"Radial representations can only be "
"transformed by a scaled identity matrix"
)
return self * scl
def _spherical_op_funcs(op, *args):
"""For given operator, return functions that adjust lon, lat, distance."""
if op is operator.neg:
return lambda x: x + 180 * u.deg, operator.neg, operator.pos
try:
scale_sign = np.sign(args[0])
except Exception:
# This should always work, even if perhaps we get a negative distance.
return operator.pos, operator.pos, lambda x: op(x, *args)
scale = abs(args[0])
return (
lambda x: x + 180 * u.deg * np.signbit(scale_sign),
lambda x: x * scale_sign,
lambda x: op(x, scale),
)
class SphericalRepresentation(BaseRepresentation):
"""
Representation of points in 3D spherical coordinates.
Parameters
----------
lon, lat : `~astropy.units.Quantity` ['angle']
The longitude and latitude of the point(s), in angular units. The
latitude should be between -90 and 90 degrees, and the longitude will
be wrapped to an angle between 0 and 360 degrees. These can also be
instances of `~astropy.coordinates.Angle`,
`~astropy.coordinates.Longitude`, or `~astropy.coordinates.Latitude`.
distance : `~astropy.units.Quantity` ['length']
The distance to the point(s). If the distance is a length, it is
passed to the :class:`~astropy.coordinates.Distance` class, otherwise
it is passed to the :class:`~astropy.units.Quantity` class.
differentials : dict, `~astropy.coordinates.BaseDifferential`, optional
Any differential classes that should be associated with this
representation. The input must either be a single `~astropy.coordinates.BaseDifferential`
instance (see `._compatible_differentials` for valid types), or a
dictionary of of differential instances with keys set to a string
representation of the SI unit with which the differential (derivative)
is taken. For example, for a velocity differential on a positional
representation, the key would be ``'s'`` for seconds, indicating that
the derivative is a time derivative.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
attr_classes = {"lon": Longitude, "lat": Latitude, "distance": u.Quantity}
_unit_representation = UnitSphericalRepresentation
def __init__(self, lon, lat=None, distance=None, differentials=None, copy=True):
super().__init__(lon, lat, distance, copy=copy, differentials=differentials)
if (
not isinstance(self._distance, Distance)
and self._distance.unit.physical_type == "length"
):
try:
self._distance = Distance(self._distance, copy=False)
except ValueError as e:
if e.args[0].startswith("distance must be >= 0"):
raise ValueError(
"Distance must be >= 0. To allow negative distance values, you"
" must explicitly pass in a `Distance` object with the the "
"argument 'allow_negative=True'."
) from e
else:
raise
@classproperty
def _compatible_differentials(cls):
return [
UnitSphericalDifferential,
UnitSphericalCosLatDifferential,
SphericalDifferential,
SphericalCosLatDifferential,
RadialDifferential,
]
@property
def lon(self):
"""
The longitude of the point(s).
"""
return self._lon
@property
def lat(self):
"""
The latitude of the point(s).
"""
return self._lat
@property
def distance(self):
"""
The distance from the origin to the point(s).
"""
return self._distance
def unit_vectors(self):
sinlon, coslon = np.sin(self.lon), np.cos(self.lon)
sinlat, coslat = np.sin(self.lat), np.cos(self.lat)
return {
"lon": CartesianRepresentation(-sinlon, coslon, 0.0, copy=False),
"lat": CartesianRepresentation(
-sinlat * coslon, -sinlat * sinlon, coslat, copy=False
),
"distance": CartesianRepresentation(
coslat * coslon, coslat * sinlon, sinlat, copy=False
),
}
def scale_factors(self, omit_coslat=False):
sf_lat = self.distance / u.radian
sf_lon = sf_lat if omit_coslat else sf_lat * np.cos(self.lat)
sf_distance = np.broadcast_to(1.0 * u.one, self.shape, subok=True)
return {"lon": sf_lon, "lat": sf_lat, "distance": sf_distance}
def represent_as(self, other_class, differential_class=None):
# Take a short cut if the other class is a spherical representation
if inspect.isclass(other_class):
if issubclass(other_class, PhysicsSphericalRepresentation):
diffs = self._re_represent_differentials(
other_class, differential_class
)
return other_class(
phi=self.lon,
theta=90 * u.deg - self.lat,
r=self.distance,
differentials=diffs,
copy=False,
)
elif issubclass(other_class, UnitSphericalRepresentation):
diffs = self._re_represent_differentials(
other_class, differential_class
)
return other_class(
lon=self.lon, lat=self.lat, differentials=diffs, copy=False
)
return super().represent_as(other_class, differential_class)
def to_cartesian(self):
"""
Converts spherical polar coordinates to 3D rectangular cartesian
coordinates.
"""
# We need to convert Distance to Quantity to allow negative values.
if isinstance(self.distance, Distance):
d = self.distance.view(u.Quantity)
else:
d = self.distance
# erfa s2p: Convert spherical polar coordinates to p-vector.
p = erfa_ufunc.s2p(self.lon, self.lat, d)
return CartesianRepresentation(p, xyz_axis=-1, copy=False)
@classmethod
def from_cartesian(cls, cart):
"""
Converts 3D rectangular cartesian coordinates to spherical polar
coordinates.
"""
p = cart.get_xyz(xyz_axis=-1)
# erfa p2s: P-vector to spherical polar coordinates.
return cls(*erfa_ufunc.p2s(p), copy=False)
def transform(self, matrix):
"""Transform the spherical coordinates using a 3x3 matrix.
This returns a new representation and does not modify the original one.
Any differentials attached to this representation will also be
transformed.
Parameters
----------
matrix : (3,3) array-like
A 3x3 matrix, such as a rotation matrix (or a stack of matrices).
"""
xyz = erfa_ufunc.s2c(self.lon, self.lat)
p = erfa_ufunc.rxp(matrix, xyz)
lon, lat, ur = erfa_ufunc.p2s(p)
rep = self.__class__(lon=lon, lat=lat, distance=self.distance * ur)
# handle differentials
new_diffs = {
k: d.transform(matrix, self, rep) for k, d in self.differentials.items()
}
return rep.with_differentials(new_diffs)
def norm(self):
"""Vector norm.
The norm is the standard Frobenius norm, i.e., the square root of the
sum of the squares of all components with non-angular units. For
spherical coordinates, this is just the absolute value of the distance.
Returns
-------
norm : `astropy.units.Quantity`
Vector norm, with the same shape as the representation.
"""
return np.abs(self.distance)
def _scale_operation(self, op, *args):
# TODO: expand special-casing to UnitSpherical and RadialDifferential.
if any(
differential.base_representation is not self.__class__
for differential in self.differentials.values()
):
return super()._scale_operation(op, *args)
lon_op, lat_op, distance_op = _spherical_op_funcs(op, *args)
result = self.__class__(
lon_op(self.lon), lat_op(self.lat), distance_op(self.distance), copy=False
)
for key, differential in self.differentials.items():
new_comps = (
op(getattr(differential, comp))
for op, comp in zip(
(operator.pos, lat_op, distance_op), differential.components
)
)
result.differentials[key] = differential.__class__(*new_comps, copy=False)
return result
class PhysicsSphericalRepresentation(BaseRepresentation):
"""
Representation of points in 3D spherical coordinates (using the physics
convention of using ``phi`` and ``theta`` for azimuth and inclination
from the pole).
Parameters
----------
phi, theta : `~astropy.units.Quantity` or str
The azimuth and inclination of the point(s), in angular units. The
inclination should be between 0 and 180 degrees, and the azimuth will
be wrapped to an angle between 0 and 360 degrees. These can also be
instances of `~astropy.coordinates.Angle`. If ``copy`` is False, `phi`
will be changed inplace if it is not between 0 and 360 degrees.
r : `~astropy.units.Quantity`
The distance to the point(s). If the distance is a length, it is
passed to the :class:`~astropy.coordinates.Distance` class, otherwise
it is passed to the :class:`~astropy.units.Quantity` class.
differentials : dict, `PhysicsSphericalDifferential`, optional
Any differential classes that should be associated with this
representation. The input must either be a single
`PhysicsSphericalDifferential` instance, or a dictionary of of
differential instances with keys set to a string representation of the
SI unit with which the differential (derivative) is taken. For example,
for a velocity differential on a positional representation, the key
would be ``'s'`` for seconds, indicating that the derivative is a time
derivative.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
attr_classes = {"phi": Angle, "theta": Angle, "r": u.Quantity}
def __init__(self, phi, theta=None, r=None, differentials=None, copy=True):
super().__init__(phi, theta, r, copy=copy, differentials=differentials)
# Wrap/validate phi/theta
# Note that _phi already holds our own copy if copy=True.
self._phi.wrap_at(360 * u.deg, inplace=True)
if np.any(self._theta < 0.0 * u.deg) or np.any(self._theta > 180.0 * u.deg):
raise ValueError(
"Inclination angle(s) must be within 0 deg <= angle <= 180 deg, "
f"got {theta.to(u.degree)}"
)
if self._r.unit.physical_type == "length":
self._r = self._r.view(Distance)
@property
def phi(self):
"""
The azimuth of the point(s).
"""
return self._phi
@property
def theta(self):
"""
The elevation of the point(s).
"""
return self._theta
@property
def r(self):
"""
The distance from the origin to the point(s).
"""
return self._r
def unit_vectors(self):
sinphi, cosphi = np.sin(self.phi), np.cos(self.phi)
sintheta, costheta = np.sin(self.theta), np.cos(self.theta)
return {
"phi": CartesianRepresentation(-sinphi, cosphi, 0.0, copy=False),
"theta": CartesianRepresentation(
costheta * cosphi, costheta * sinphi, -sintheta, copy=False
),
"r": CartesianRepresentation(
sintheta * cosphi, sintheta * sinphi, costheta, copy=False
),
}
def scale_factors(self):
r = self.r / u.radian
sintheta = np.sin(self.theta)
l = np.broadcast_to(1.0 * u.one, self.shape, subok=True)
return {"phi": r * sintheta, "theta": r, "r": l}
def represent_as(self, other_class, differential_class=None):
# Take a short cut if the other class is a spherical representation
if inspect.isclass(other_class):
if issubclass(other_class, SphericalRepresentation):
diffs = self._re_represent_differentials(
other_class, differential_class
)
return other_class(
lon=self.phi,
lat=90 * u.deg - self.theta,
distance=self.r,
differentials=diffs,
copy=False,
)
elif issubclass(other_class, UnitSphericalRepresentation):
diffs = self._re_represent_differentials(
other_class, differential_class
)
return other_class(
lon=self.phi,
lat=90 * u.deg - self.theta,
differentials=diffs,
copy=False,
)
return super().represent_as(other_class, differential_class)
def to_cartesian(self):
"""
Converts spherical polar coordinates to 3D rectangular cartesian
coordinates.
"""
# We need to convert Distance to Quantity to allow negative values.
if isinstance(self.r, Distance):
d = self.r.view(u.Quantity)
else:
d = self.r
x = d * np.sin(self.theta) * np.cos(self.phi)
y = d * np.sin(self.theta) * np.sin(self.phi)
z = d * np.cos(self.theta)
return CartesianRepresentation(x=x, y=y, z=z, copy=False)
@classmethod
def from_cartesian(cls, cart):
"""
Converts 3D rectangular cartesian coordinates to spherical polar
coordinates.
"""
s = np.hypot(cart.x, cart.y)
r = np.hypot(s, cart.z)
phi = np.arctan2(cart.y, cart.x)
theta = np.arctan2(s, cart.z)
return cls(phi=phi, theta=theta, r=r, copy=False)
def transform(self, matrix):
"""Transform the spherical coordinates using a 3x3 matrix.
This returns a new representation and does not modify the original one.
Any differentials attached to this representation will also be
transformed.
Parameters
----------
matrix : (3,3) array-like
A 3x3 matrix, such as a rotation matrix (or a stack of matrices).
"""
# apply transformation in unit-spherical coordinates
xyz = erfa_ufunc.s2c(self.phi, 90 * u.deg - self.theta)
p = erfa_ufunc.rxp(matrix, xyz)
lon, lat, ur = erfa_ufunc.p2s(p) # `ur` is transformed unit-`r`
# create transformed physics-spherical representation,
# reapplying the distance scaling
rep = self.__class__(phi=lon, theta=90 * u.deg - lat, r=self.r * ur)
new_diffs = {
k: d.transform(matrix, self, rep) for k, d in self.differentials.items()
}
return rep.with_differentials(new_diffs)
def norm(self):
"""Vector norm.
The norm is the standard Frobenius norm, i.e., the square root of the
sum of the squares of all components with non-angular units. For
spherical coordinates, this is just the absolute value of the radius.
Returns
-------
norm : `astropy.units.Quantity`
Vector norm, with the same shape as the representation.
"""
return np.abs(self.r)
def _scale_operation(self, op, *args):
if any(
differential.base_representation is not self.__class__
for differential in self.differentials.values()
):
return super()._scale_operation(op, *args)
phi_op, adjust_theta_sign, r_op = _spherical_op_funcs(op, *args)
# Also run phi_op on theta to ensure theta remains between 0 and 180:
# any time the scale is negative, we do -theta + 180 degrees.
result = self.__class__(
phi_op(self.phi),
phi_op(adjust_theta_sign(self.theta)),
r_op(self.r),
copy=False,
)
for key, differential in self.differentials.items():
new_comps = (
op(getattr(differential, comp))
for op, comp in zip(
(operator.pos, adjust_theta_sign, r_op), differential.components
)
)
result.differentials[key] = differential.__class__(*new_comps, copy=False)
return result
class CylindricalRepresentation(BaseRepresentation):
"""
Representation of points in 3D cylindrical coordinates.
Parameters
----------
rho : `~astropy.units.Quantity`
The distance from the z axis to the point(s).
phi : `~astropy.units.Quantity` or str
The azimuth of the point(s), in angular units, which will be wrapped
to an angle between 0 and 360 degrees. This can also be instances of
`~astropy.coordinates.Angle`,
z : `~astropy.units.Quantity`
The z coordinate(s) of the point(s)
differentials : dict, `CylindricalDifferential`, optional
Any differential classes that should be associated with this
representation. The input must either be a single
`CylindricalDifferential` instance, or a dictionary of of differential
instances with keys set to a string representation of the SI unit with
which the differential (derivative) is taken. For example, for a
velocity differential on a positional representation, the key would be
``'s'`` for seconds, indicating that the derivative is a time
derivative.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
attr_classes = {"rho": u.Quantity, "phi": Angle, "z": u.Quantity}
def __init__(self, rho, phi=None, z=None, differentials=None, copy=True):
super().__init__(rho, phi, z, copy=copy, differentials=differentials)
if not self._rho.unit.is_equivalent(self._z.unit):
raise u.UnitsError("rho and z should have matching physical types")
@property
def rho(self):
"""
The distance of the point(s) from the z-axis.
"""
return self._rho
@property
def phi(self):
"""
The azimuth of the point(s).
"""
return self._phi
@property
def z(self):
"""
The height of the point(s).
"""
return self._z
def unit_vectors(self):
sinphi, cosphi = np.sin(self.phi), np.cos(self.phi)
l = np.broadcast_to(1.0, self.shape)
return {
"rho": CartesianRepresentation(cosphi, sinphi, 0, copy=False),
"phi": CartesianRepresentation(-sinphi, cosphi, 0, copy=False),
"z": CartesianRepresentation(0, 0, l, unit=u.one, copy=False),
}
def scale_factors(self):
rho = self.rho / u.radian
l = np.broadcast_to(1.0 * u.one, self.shape, subok=True)
return {"rho": l, "phi": rho, "z": l}
@classmethod
def from_cartesian(cls, cart):
"""
Converts 3D rectangular cartesian coordinates to cylindrical polar
coordinates.
"""
rho = np.hypot(cart.x, cart.y)
phi = np.arctan2(cart.y, cart.x)
z = cart.z
return cls(rho=rho, phi=phi, z=z, copy=False)
def to_cartesian(self):
"""
Converts cylindrical polar coordinates to 3D rectangular cartesian
coordinates.
"""
x = self.rho * np.cos(self.phi)
y = self.rho * np.sin(self.phi)
z = self.z
return CartesianRepresentation(x=x, y=y, z=z, copy=False)
def _scale_operation(self, op, *args):
if any(
differential.base_representation is not self.__class__
for differential in self.differentials.values()
):
return super()._scale_operation(op, *args)
phi_op, _, rho_op = _spherical_op_funcs(op, *args)
z_op = lambda x: op(x, *args)
result = self.__class__(
rho_op(self.rho), phi_op(self.phi), z_op(self.z), copy=False
)
for key, differential in self.differentials.items():
new_comps = (
op(getattr(differential, comp))
for op, comp in zip(
(rho_op, operator.pos, z_op), differential.components
)
)
result.differentials[key] = differential.__class__(*new_comps, copy=False)
return result
class BaseDifferential(BaseRepresentationOrDifferential):
r"""A base class representing differentials of representations.
These represent differences or derivatives along each component.
E.g., for physics spherical coordinates, these would be
:math:`\delta r, \delta \theta, \delta \phi`.
Parameters
----------
d_comp1, d_comp2, d_comp3 : `~astropy.units.Quantity` or subclass
The components of the 3D differentials. The names are the keys and the
subclasses the values of the ``attr_classes`` attribute.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
Notes
-----
All differential representation classes should subclass this base class,
and define an ``base_representation`` attribute with the class of the
regular `~astropy.coordinates.BaseRepresentation` for which differential
coordinates are provided. This will set up a default ``attr_classes``
instance with names equal to the base component names prefixed by ``d_``,
and all classes set to `~astropy.units.Quantity`, plus properties to access
those, and a default ``__init__`` for initialization.
"""
def __init_subclass__(cls, **kwargs):
"""Set default ``attr_classes`` and component getters on a Differential.
class BaseDifferential(BaseRepresentationOrDifferential):
For these, the components are those of the base representation prefixed
by 'd_', and the class is `~astropy.units.Quantity`.
"""
# Don't do anything for base helper classes.
if cls.__name__ in (
"BaseDifferential",
"BaseSphericalDifferential",
"BaseSphericalCosLatDifferential",
):
return
if not hasattr(cls, "base_representation"):
raise NotImplementedError(
"Differential representations must have a"
'"base_representation" class attribute.'
)
# If not defined explicitly, create attr_classes.
if not hasattr(cls, "attr_classes"):
base_attr_classes = cls.base_representation.attr_classes
cls.attr_classes = {"d_" + c: u.Quantity for c in base_attr_classes}
repr_name = cls.get_name()
if repr_name in DIFFERENTIAL_CLASSES:
raise ValueError(f"Differential class {repr_name} already defined")
DIFFERENTIAL_CLASSES[repr_name] = cls
_invalidate_reprdiff_cls_hash()
# If not defined explicitly, create properties for the components.
for component in cls.attr_classes:
if not hasattr(cls, component):
setattr(
cls,
component,
property(
_make_getter(component),
doc=f"Component '{component}' of the Differential.",
),
)
super().__init_subclass__(**kwargs)
@classmethod
def _check_base(cls, base):
if cls not in base._compatible_differentials:
raise TypeError(
f"Differential class {cls} is not compatible with the "
f"base (representation) class {base.__class__}"
)
def _get_deriv_key(self, base):
"""Given a base (representation instance), determine the unit of the
derivative by removing the representation unit from the component units
of this differential.
"""
# This check is just a last resort so we don't return a strange unit key
# from accidentally passing in the wrong base.
self._check_base(base)
for name in base.components:
comp = getattr(base, name)
d_comp = getattr(self, f"d_{name}", None)
if d_comp is not None:
d_unit = comp.unit / d_comp.unit
# This is quite a bit faster than using to_system() or going
# through Quantity()
d_unit_si = d_unit.decompose(u.si.bases)
d_unit_si._scale = 1 # remove the scale from the unit
return str(d_unit_si)
else:
raise RuntimeError(
"Invalid representation-differential units! This likely happened "
"because either the representation or the associated differential "
"have non-standard units. Check that the input positional data have "
"positional units, and the input velocity data have velocity units, "
"or are both dimensionless."
)
@classmethod
def _get_base_vectors(cls, base):
"""Get unit vectors and scale factors from base.
Parameters
----------
base : instance of ``self.base_representation``
The points for which the unit vectors and scale factors should be
retrieved.
Returns
-------
unit_vectors : dict of `CartesianRepresentation`
In the directions of the coordinates of base.
scale_factors : dict of `~astropy.units.Quantity`
Scale factors for each of the coordinates
Raises
------
TypeError : if the base is not of the correct type
"""
cls._check_base(base)
return base.unit_vectors(), base.scale_factors()
def to_cartesian(self, base):
"""Convert the differential to 3D rectangular cartesian coordinates.
Parameters
----------
base : instance of ``self.base_representation``
The points for which the differentials are to be converted: each of
the components is multiplied by its unit vectors and scale factors.
Returns
-------
`CartesianDifferential`
This object, converted.
"""
base_e, base_sf = self._get_base_vectors(base)
return functools.reduce(
operator.add,
(
getattr(self, d_c) * base_sf[c] * base_e[c]
for d_c, c in zip(self.components, base.components)
),
)
@classmethod
def from_cartesian(cls, other, base):
"""Convert the differential from 3D rectangular cartesian coordinates to
the desired class.
Parameters
----------
other
The object to convert into this differential.
base : `BaseRepresentation`
The points for which the differentials are to be converted: each of
the components is multiplied by its unit vectors and scale factors.
Will be converted to ``cls.base_representation`` if needed.
Returns
-------
`BaseDifferential` subclass instance
A new differential object that is this class' type.
"""
base = base.represent_as(cls.base_representation)
base_e, base_sf = cls._get_base_vectors(base)
return cls(
*(other.dot(e / base_sf[component]) for component, e in base_e.items()),
copy=False,
)
def represent_as(self, other_class, base):
"""Convert coordinates to another representation.
If the instance is of the requested class, it is returned unmodified.
By default, conversion is done via cartesian coordinates.
Parameters
----------
other_class : `~astropy.coordinates.BaseRepresentation` subclass
The type of representation to turn the coordinates into.
base : instance of ``self.base_representation``
Base relative to which the differentials are defined. If the other
class is a differential representation, the base will be converted
to its ``base_representation``.
"""
if other_class is self.__class__:
return self
# The default is to convert via cartesian coordinates.
self_cartesian = self.to_cartesian(base)
if issubclass(other_class, BaseDifferential):
return other_class.from_cartesian(self_cartesian, base)
else:
return other_class.from_cartesian(self_cartesian)
@classmethod
def from_representation(cls, representation, base):
"""Create a new instance of this representation from another one.
Parameters
----------
representation : `~astropy.coordinates.BaseRepresentation` instance
The presentation that should be converted to this class.
base : instance of ``cls.base_representation``
The base relative to which the differentials will be defined. If
the representation is a differential itself, the base will be
converted to its ``base_representation`` to help convert it.
"""
if isinstance(representation, BaseDifferential):
cartesian = representation.to_cartesian(
base.represent_as(representation.base_representation)
)
else:
cartesian = representation.to_cartesian()
return cls.from_cartesian(cartesian, base)
def transform(self, matrix, base, transformed_base):
"""Transform differential using a 3x3 matrix in a Cartesian basis.
This returns a new differential and does not modify the original one.
Parameters
----------
matrix : (3,3) array-like
A 3x3 (or stack thereof) matrix, such as a rotation matrix.
base : instance of ``cls.base_representation``
Base relative to which the differentials are defined. If the other
class is a differential representation, the base will be converted
to its ``base_representation``.
transformed_base : instance of ``cls.base_representation``
Base relative to which the transformed differentials are defined.
If the other class is a differential representation, the base will
be converted to its ``base_representation``.
"""
# route transformation through Cartesian
cdiff = self.represent_as(CartesianDifferential, base=base).transform(matrix)
# move back to original representation
diff = cdiff.represent_as(self.__class__, transformed_base)
return diff
def _scale_operation(self, op, *args, scaled_base=False):
"""Scale all components.
Parameters
----------
op : `~operator` callable
Operator to apply (e.g., `~operator.mul`, `~operator.neg`, etc.
*args
Any arguments required for the operator (typically, what is to
be multiplied with, divided by).
scaled_base : bool, optional
Whether the base was scaled the same way. This affects whether
differential components should be scaled. For instance, a differential
in longitude should not be scaled if its spherical base is scaled
in radius.
"""
scaled_attrs = [op(getattr(self, c), *args) for c in self.components]
return self.__class__(*scaled_attrs, copy=False)
def _combine_operation(self, op, other, reverse=False):
"""Combine two differentials, or a differential with a representation.
If ``other`` is of the same differential type as ``self``, the
components will simply be combined. If ``other`` is a representation,
it will be used as a base for which to evaluate the differential,
and the result is a new representation.
Parameters
----------
op : `~operator` callable
Operator to apply (e.g., `~operator.add`, `~operator.sub`, etc.
other : `~astropy.coordinates.BaseRepresentation` subclass instance
The other differential or representation.
reverse : bool
Whether the operands should be reversed (e.g., as we got here via
``self.__rsub__`` because ``self`` is a subclass of ``other``).
"""
if isinstance(self, type(other)):
first, second = (self, other) if not reverse else (other, self)
return self.__class__(
*[op(getattr(first, c), getattr(second, c)) for c in self.components]
)
else:
try:
self_cartesian = self.to_cartesian(other)
except TypeError:
return NotImplemented
return other._combine_operation(op, self_cartesian, not reverse)
def __sub__(self, other):
# avoid "differential - representation".
if isinstance(other, BaseRepresentation):
return NotImplemented
return super().__sub__(other)
def norm(self, base=None):
"""Vector norm.
The norm is the standard Frobenius norm, i.e., the square root of the
sum of the squares of all components with non-angular units.
Parameters
----------
base : instance of ``self.base_representation``
Base relative to which the differentials are defined. This is
required to calculate the physical size of the differential for
all but Cartesian differentials or radial differentials.
Returns
-------
norm : `astropy.units.Quantity`
Vector norm, with the same shape as the representation.
"""
# RadialDifferential overrides this function, so there is no handling here
if not isinstance(self, CartesianDifferential) and base is None:
raise ValueError(
"`base` must be provided to calculate the norm of a"
f" {type(self).__name__}"
)
return self.to_cartesian(base).norm()
class CartesianDifferential(BaseDifferential):
"""Differentials in of points in 3D cartesian coordinates.
Parameters
----------
d_x, d_y, d_z : `~astropy.units.Quantity` or array
The x, y, and z coordinates of the differentials. If ``d_x``, ``d_y``,
and ``d_z`` have different shapes, they should be broadcastable. If not
quantities, ``unit`` should be set. If only ``d_x`` is given, it is
assumed that it contains an array with the 3 coordinates stored along
``xyz_axis``.
unit : `~astropy.units.Unit` or str
If given, the differentials will be converted to this unit (or taken to
be in this unit if not given.
xyz_axis : int, optional
The axis along which the coordinates are stored when a single array is
provided instead of distinct ``d_x``, ``d_y``, and ``d_z`` (default: 0).
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
base_representation = CartesianRepresentation
_d_xyz = None
def __init__(self, d_x, d_y=None, d_z=None, unit=None, xyz_axis=None, copy=True):
if d_y is None and d_z is None:
if isinstance(d_x, np.ndarray) and d_x.dtype.kind not in "OV":
# Short-cut for 3-D array input.
d_x = u.Quantity(d_x, unit, copy=copy, subok=True)
# Keep a link to the array with all three coordinates
# so that we can return it quickly if needed in get_xyz.
self._d_xyz = d_x
if xyz_axis:
d_x = np.moveaxis(d_x, xyz_axis, 0)
self._xyz_axis = xyz_axis
else:
self._xyz_axis = 0
self._d_x, self._d_y, self._d_z = d_x
return
else:
d_x, d_y, d_z = d_x
if xyz_axis is not None:
raise ValueError(
"xyz_axis should only be set if d_x, d_y, and d_z are in a single array"
" passed in through d_x, i.e., d_y and d_z should not be not given."
)
if d_y is None or d_z is None:
raise ValueError(
"d_x, d_y, and d_z are required to instantiate"
f" {self.__class__.__name__}"
)
if unit is not None:
d_x = u.Quantity(d_x, unit, copy=copy, subok=True)
d_y = u.Quantity(d_y, unit, copy=copy, subok=True)
d_z = u.Quantity(d_z, unit, copy=copy, subok=True)
copy = False
super().__init__(d_x, d_y, d_z, copy=copy)
if not (
self._d_x.unit.is_equivalent(self._d_y.unit)
and self._d_x.unit.is_equivalent(self._d_z.unit)
):
raise u.UnitsError("d_x, d_y and d_z should have equivalent units.")
def to_cartesian(self, base=None):
return CartesianRepresentation(*[getattr(self, c) for c in self.components])
@classmethod
def from_cartesian(cls, other, base=None):
return cls(*[getattr(other, c) for c in other.components])
def transform(self, matrix, base=None, transformed_base=None):
"""Transform differentials using a 3x3 matrix in a Cartesian basis.
This returns a new differential and does not modify the original one.
Parameters
----------
matrix : (3,3) array-like
A 3x3 (or stack thereof) matrix, such as a rotation matrix.
base, transformed_base : `~astropy.coordinates.CartesianRepresentation` or None, optional
Not used in the Cartesian transformation.
"""
# erfa rxp: Multiply a p-vector by an r-matrix.
p = erfa_ufunc.rxp(matrix, self.get_d_xyz(xyz_axis=-1))
return self.__class__(p, xyz_axis=-1, copy=False)
def get_d_xyz(self, xyz_axis=0):
"""Return a vector array of the x, y, and z coordinates.
Parameters
----------
xyz_axis : int, optional
The axis in the final array along which the x, y, z components
should be stored (default: 0).
Returns
-------
d_xyz : `~astropy.units.Quantity`
With dimension 3 along ``xyz_axis``. Note that, if possible,
this will be a view.
"""
if self._d_xyz is not None:
if self._xyz_axis == xyz_axis:
return self._d_xyz
else:
return np.moveaxis(self._d_xyz, self._xyz_axis, xyz_axis)
# Create combined array. TO DO: keep it in _d_xyz for repeated use?
# But then in-place changes have to cancel it. Likely best to
# also update components.
return np.stack([self._d_x, self._d_y, self._d_z], axis=xyz_axis)
d_xyz = property(get_d_xyz)
class BaseSphericalDifferential(BaseDifferential):
def _d_lon_coslat(self, base):
"""Convert longitude differential d_lon to d_lon_coslat.
Parameters
----------
base : instance of ``cls.base_representation``
The base from which the latitude will be taken.
"""
self._check_base(base)
return self.d_lon * np.cos(base.lat)
@classmethod
def _get_d_lon(cls, d_lon_coslat, base):
"""Convert longitude differential d_lon_coslat to d_lon.
Parameters
----------
d_lon_coslat : `~astropy.units.Quantity`
Longitude differential that includes ``cos(lat)``.
base : instance of ``cls.base_representation``
The base from which the latitude will be taken.
"""
cls._check_base(base)
return d_lon_coslat / np.cos(base.lat)
def _combine_operation(self, op, other, reverse=False):
"""Combine two differentials, or a differential with a representation.
If ``other`` is of the same differential type as ``self``, the
components will simply be combined. If both are different parts of
a `~astropy.coordinates.SphericalDifferential` (e.g., a
`~astropy.coordinates.UnitSphericalDifferential` and a
`~astropy.coordinates.RadialDifferential`), they will combined
appropriately.
If ``other`` is a representation, it will be used as a base for which
to evaluate the differential, and the result is a new representation.
Parameters
----------
op : `~operator` callable
Operator to apply (e.g., `~operator.add`, `~operator.sub`, etc.
other : `~astropy.coordinates.BaseRepresentation` subclass instance
The other differential or representation.
reverse : bool
Whether the operands should be reversed (e.g., as we got here via
``self.__rsub__`` because ``self`` is a subclass of ``other``).
"""
if (
isinstance(other, BaseSphericalDifferential)
and not isinstance(self, type(other))
or isinstance(other, RadialDifferential)
):
all_components = set(self.components) | set(other.components)
first, second = (self, other) if not reverse else (other, self)
result_args = {
c: op(getattr(first, c, 0.0), getattr(second, c, 0.0))
for c in all_components
}
return SphericalDifferential(**result_args)
return super()._combine_operation(op, other, reverse)
class UnitSphericalDifferential(BaseSphericalDifferential):
"""Differential(s) of points on a unit sphere.
Parameters
----------
d_lon, d_lat : `~astropy.units.Quantity`
The longitude and latitude of the differentials.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
base_representation = UnitSphericalRepresentation
@classproperty
def _dimensional_differential(cls):
return SphericalDifferential
def __init__(self, d_lon, d_lat=None, copy=True):
super().__init__(d_lon, d_lat, copy=copy)
if not self._d_lon.unit.is_equivalent(self._d_lat.unit):
raise u.UnitsError("d_lon and d_lat should have equivalent units.")
@classmethod
def from_cartesian(cls, other, base):
# Go via the dimensional equivalent, so that the longitude and latitude
# differentials correctly take into account the norm of the base.
dimensional = cls._dimensional_differential.from_cartesian(other, base)
return dimensional.represent_as(cls)
def to_cartesian(self, base):
if isinstance(base, SphericalRepresentation):
scale = base.distance
elif isinstance(base, PhysicsSphericalRepresentation):
scale = base.r
else:
return super().to_cartesian(base)
base = base.represent_as(UnitSphericalRepresentation)
return scale * super().to_cartesian(base)
def represent_as(self, other_class, base=None):
# Only have enough information to represent other unit-spherical.
if issubclass(other_class, UnitSphericalCosLatDifferential):
return other_class(self._d_lon_coslat(base), self.d_lat)
return super().represent_as(other_class, base)
@classmethod
def from_representation(cls, representation, base=None):
# All spherical differentials can be done without going to Cartesian,
# though CosLat needs base for the latitude.
if isinstance(representation, SphericalDifferential):
return cls(representation.d_lon, representation.d_lat)
elif isinstance(
representation,
(SphericalCosLatDifferential, UnitSphericalCosLatDifferential),
):
d_lon = cls._get_d_lon(representation.d_lon_coslat, base)
return cls(d_lon, representation.d_lat)
elif isinstance(representation, PhysicsSphericalDifferential):
return cls(representation.d_phi, -representation.d_theta)
return super().from_representation(representation, base)
def transform(self, matrix, base, transformed_base):
"""Transform differential using a 3x3 matrix in a Cartesian basis.
This returns a new differential and does not modify the original one.
Parameters
----------
matrix : (3,3) array-like
A 3x3 (or stack thereof) matrix, such as a rotation matrix.
base : instance of ``cls.base_representation``
Base relative to which the differentials are defined. If the other
class is a differential representation, the base will be converted
to its ``base_representation``.
transformed_base : instance of ``cls.base_representation``
Base relative to which the transformed differentials are defined.
If the other class is a differential representation, the base will
be converted to its ``base_representation``.
"""
# the transformation matrix does not need to be a rotation matrix,
# so the unit-distance is not guaranteed. For speed, we check if the
# matrix is in O(3) and preserves lengths.
if np.all(is_O3(matrix)): # remain in unit-rep
# TODO! implement without Cartesian intermediate step.
# some of this can be moved to the parent class.
diff = super().transform(matrix, base, transformed_base)
else: # switch to dimensional representation
du = self.d_lon.unit / base.lon.unit # derivative unit
diff = self._dimensional_differential(
d_lon=self.d_lon, d_lat=self.d_lat, d_distance=0 * du
).transform(matrix, base, transformed_base)
return diff
def _scale_operation(self, op, *args, scaled_base=False):
if scaled_base:
return self.copy()
else:
return super()._scale_operation(op, *args)
class SphericalDifferential(BaseSphericalDifferential):
"""Differential(s) of points in 3D spherical coordinates.
Parameters
----------
d_lon, d_lat : `~astropy.units.Quantity`
The differential longitude and latitude.
d_distance : `~astropy.units.Quantity`
The differential distance.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
base_representation = SphericalRepresentation
_unit_differential = UnitSphericalDifferential
def __init__(self, d_lon, d_lat=None, d_distance=None, copy=True):
super().__init__(d_lon, d_lat, d_distance, copy=copy)
if not self._d_lon.unit.is_equivalent(self._d_lat.unit):
raise u.UnitsError("d_lon and d_lat should have equivalent units.")
def represent_as(self, other_class, base=None):
# All spherical differentials can be done without going to Cartesian,
# though CosLat needs base for the latitude.
if issubclass(other_class, UnitSphericalDifferential):
return other_class(self.d_lon, self.d_lat)
elif issubclass(other_class, RadialDifferential):
return other_class(self.d_distance)
elif issubclass(other_class, SphericalCosLatDifferential):
return other_class(self._d_lon_coslat(base), self.d_lat, self.d_distance)
elif issubclass(other_class, UnitSphericalCosLatDifferential):
return other_class(self._d_lon_coslat(base), self.d_lat)
elif issubclass(other_class, PhysicsSphericalDifferential):
return other_class(self.d_lon, -self.d_lat, self.d_distance)
else:
return super().represent_as(other_class, base)
@classmethod
def from_representation(cls, representation, base=None):
# Other spherical differentials can be done without going to Cartesian,
# though CosLat needs base for the latitude.
if isinstance(representation, SphericalCosLatDifferential):
d_lon = cls._get_d_lon(representation.d_lon_coslat, base)
return cls(d_lon, representation.d_lat, representation.d_distance)
elif isinstance(representation, PhysicsSphericalDifferential):
return cls(
representation.d_phi, -representation.d_theta, representation.d_r
)
return super().from_representation(representation, base)
def _scale_operation(self, op, *args, scaled_base=False):
if scaled_base:
return self.__class__(self.d_lon, self.d_lat, op(self.d_distance, *args))
else:
return super()._scale_operation(op, *args)
class BaseSphericalCosLatDifferential(BaseDifferential):
"""Differentials from points on a spherical base representation.
With cos(lat) assumed to be included in the longitude differential.
"""
@classmethod
def _get_base_vectors(cls, base):
"""Get unit vectors and scale factors from (unit)spherical base.
Parameters
----------
base : instance of ``self.base_representation``
The points for which the unit vectors and scale factors should be
retrieved.
Returns
-------
unit_vectors : dict of `CartesianRepresentation`
In the directions of the coordinates of base.
scale_factors : dict of `~astropy.units.Quantity`
Scale factors for each of the coordinates. The scale factor for
longitude does not include the cos(lat) factor.
Raises
------
TypeError : if the base is not of the correct type
"""
cls._check_base(base)
return base.unit_vectors(), base.scale_factors(omit_coslat=True)
def _d_lon(self, base):
"""Convert longitude differential with cos(lat) to one without.
Parameters
----------
base : instance of ``cls.base_representation``
The base from which the latitude will be taken.
"""
self._check_base(base)
return self.d_lon_coslat / np.cos(base.lat)
@classmethod
def _get_d_lon_coslat(cls, d_lon, base):
"""Convert longitude differential d_lon to d_lon_coslat.
Parameters
----------
d_lon : `~astropy.units.Quantity`
Value of the longitude differential without ``cos(lat)``.
base : instance of ``cls.base_representation``
The base from which the latitude will be taken.
"""
cls._check_base(base)
return d_lon * np.cos(base.lat)
def _combine_operation(self, op, other, reverse=False):
"""Combine two differentials, or a differential with a representation.
If ``other`` is of the same differential type as ``self``, the
components will simply be combined. If both are different parts of
a `~astropy.coordinates.SphericalDifferential` (e.g., a
`~astropy.coordinates.UnitSphericalDifferential` and a
`~astropy.coordinates.RadialDifferential`), they will combined
appropriately.
If ``other`` is a representation, it will be used as a base for which
to evaluate the differential, and the result is a new representation.
Parameters
----------
op : `~operator` callable
Operator to apply (e.g., `~operator.add`, `~operator.sub`, etc.
other : `~astropy.coordinates.BaseRepresentation` subclass instance
The other differential or representation.
reverse : bool
Whether the operands should be reversed (e.g., as we got here via
``self.__rsub__`` because ``self`` is a subclass of ``other``).
"""
if (
isinstance(other, BaseSphericalCosLatDifferential)
and not isinstance(self, type(other))
or isinstance(other, RadialDifferential)
):
all_components = set(self.components) | set(other.components)
first, second = (self, other) if not reverse else (other, self)
result_args = {
c: op(getattr(first, c, 0.0), getattr(second, c, 0.0))
for c in all_components
}
return SphericalCosLatDifferential(**result_args)
return super()._combine_operation(op, other, reverse)
class UnitSphericalCosLatDifferential(BaseSphericalCosLatDifferential):
"""Differential(s) of points on a unit sphere.
Parameters
----------
d_lon_coslat, d_lat : `~astropy.units.Quantity`
The longitude and latitude of the differentials.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
base_representation = UnitSphericalRepresentation
attr_classes = {"d_lon_coslat": u.Quantity, "d_lat": u.Quantity}
@classproperty
def _dimensional_differential(cls):
return SphericalCosLatDifferential
def __init__(self, d_lon_coslat, d_lat=None, copy=True):
super().__init__(d_lon_coslat, d_lat, copy=copy)
if not self._d_lon_coslat.unit.is_equivalent(self._d_lat.unit):
raise u.UnitsError("d_lon_coslat and d_lat should have equivalent units.")
@classmethod
def from_cartesian(cls, other, base):
# Go via the dimensional equivalent, so that the longitude and latitude
# differentials correctly take into account the norm of the base.
dimensional = cls._dimensional_differential.from_cartesian(other, base)
return dimensional.represent_as(cls)
def to_cartesian(self, base):
if isinstance(base, SphericalRepresentation):
scale = base.distance
elif isinstance(base, PhysicsSphericalRepresentation):
scale = base.r
else:
return super().to_cartesian(base)
base = base.represent_as(UnitSphericalRepresentation)
return scale * super().to_cartesian(base)
def represent_as(self, other_class, base=None):
# Only have enough information to represent other unit-spherical.
if issubclass(other_class, UnitSphericalDifferential):
return other_class(self._d_lon(base), self.d_lat)
return super().represent_as(other_class, base)
@classmethod
def from_representation(cls, representation, base=None):
# All spherical differentials can be done without going to Cartesian,
# though w/o CosLat needs base for the latitude.
if isinstance(representation, SphericalCosLatDifferential):
return cls(representation.d_lon_coslat, representation.d_lat)
elif isinstance(
representation, (SphericalDifferential, UnitSphericalDifferential)
):
d_lon_coslat = cls._get_d_lon_coslat(representation.d_lon, base)
return cls(d_lon_coslat, representation.d_lat)
elif isinstance(representation, PhysicsSphericalDifferential):
d_lon_coslat = cls._get_d_lon_coslat(representation.d_phi, base)
return cls(d_lon_coslat, -representation.d_theta)
return super().from_representation(representation, base)
def transform(self, matrix, base, transformed_base):
"""Transform differential using a 3x3 matrix in a Cartesian basis.
This returns a new differential and does not modify the original one.
Parameters
----------
matrix : (3,3) array-like
A 3x3 (or stack thereof) matrix, such as a rotation matrix.
base : instance of ``cls.base_representation``
Base relative to which the differentials are defined. If the other
class is a differential representation, the base will be converted
to its ``base_representation``.
transformed_base : instance of ``cls.base_representation``
Base relative to which the transformed differentials are defined.
If the other class is a differential representation, the base will
be converted to its ``base_representation``.
"""
# the transformation matrix does not need to be a rotation matrix,
# so the unit-distance is not guaranteed. For speed, we check if the
# matrix is in O(3) and preserves lengths.
if np.all(is_O3(matrix)): # remain in unit-rep
# TODO! implement without Cartesian intermediate step.
diff = super().transform(matrix, base, transformed_base)
else: # switch to dimensional representation
du = self.d_lat.unit / base.lat.unit # derivative unit
diff = self._dimensional_differential(
d_lon_coslat=self.d_lon_coslat, d_lat=self.d_lat, d_distance=0 * du
).transform(matrix, base, transformed_base)
return diff
def _scale_operation(self, op, *args, scaled_base=False):
if scaled_base:
return self.copy()
else:
return super()._scale_operation(op, *args)
class SphericalCosLatDifferential(BaseSphericalCosLatDifferential):
"""Differential(s) of points in 3D spherical coordinates.
Parameters
----------
d_lon_coslat, d_lat : `~astropy.units.Quantity`
The differential longitude (with cos(lat) included) and latitude.
d_distance : `~astropy.units.Quantity`
The differential distance.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
base_representation = SphericalRepresentation
_unit_differential = UnitSphericalCosLatDifferential
attr_classes = {
"d_lon_coslat": u.Quantity,
"d_lat": u.Quantity,
"d_distance": u.Quantity,
}
def __init__(self, d_lon_coslat, d_lat=None, d_distance=None, copy=True):
super().__init__(d_lon_coslat, d_lat, d_distance, copy=copy)
if not self._d_lon_coslat.unit.is_equivalent(self._d_lat.unit):
raise u.UnitsError("d_lon_coslat and d_lat should have equivalent units.")
def represent_as(self, other_class, base=None):
# All spherical differentials can be done without going to Cartesian,
# though some need base for the latitude to remove cos(lat).
if issubclass(other_class, UnitSphericalCosLatDifferential):
return other_class(self.d_lon_coslat, self.d_lat)
elif issubclass(other_class, RadialDifferential):
return other_class(self.d_distance)
elif issubclass(other_class, SphericalDifferential):
return other_class(self._d_lon(base), self.d_lat, self.d_distance)
elif issubclass(other_class, UnitSphericalDifferential):
return other_class(self._d_lon(base), self.d_lat)
elif issubclass(other_class, PhysicsSphericalDifferential):
return other_class(self._d_lon(base), -self.d_lat, self.d_distance)
return super().represent_as(other_class, base)
@classmethod
def from_representation(cls, representation, base=None):
# Other spherical differentials can be done without going to Cartesian,
# though we need base for the latitude to remove coslat.
if isinstance(representation, SphericalDifferential):
d_lon_coslat = cls._get_d_lon_coslat(representation.d_lon, base)
return cls(d_lon_coslat, representation.d_lat, representation.d_distance)
elif isinstance(representation, PhysicsSphericalDifferential):
d_lon_coslat = cls._get_d_lon_coslat(representation.d_phi, base)
return cls(d_lon_coslat, -representation.d_theta, representation.d_r)
return super().from_representation(representation, base)
def _scale_operation(self, op, *args, scaled_base=False):
if scaled_base:
return self.__class__(
self.d_lon_coslat, self.d_lat, op(self.d_distance, *args)
)
else:
return super()._scale_operation(op, *args)
class RadialDifferential(BaseDifferential):
"""Differential(s) of radial distances.
Parameters
----------
d_distance : `~astropy.units.Quantity`
The differential distance.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
base_representation = RadialRepresentation
def to_cartesian(self, base):
unit_vec = base.represent_as(UnitSphericalRepresentation).to_cartesian()
return self.d_distance * unit_vec
def norm(self, base=None):
return self.d_distance
@classmethod
def from_cartesian(cls, other, base):
return cls(
other.dot(base.represent_as(UnitSphericalRepresentation)), copy=False
)
@classmethod
def from_representation(cls, representation, base=None):
if isinstance(
representation, (SphericalDifferential, SphericalCosLatDifferential)
):
return cls(representation.d_distance)
elif isinstance(representation, PhysicsSphericalDifferential):
return cls(representation.d_r)
else:
return super().from_representation(representation, base)
def _combine_operation(self, op, other, reverse=False):
if isinstance(other, self.base_representation):
if reverse:
first, second = other.distance, self.d_distance
else:
first, second = self.d_distance, other.distance
return other.__class__(op(first, second), copy=False)
elif isinstance(
other, (BaseSphericalDifferential, BaseSphericalCosLatDifferential)
):
all_components = set(self.components) | set(other.components)
first, second = (self, other) if not reverse else (other, self)
result_args = {
c: op(getattr(first, c, 0.0), getattr(second, c, 0.0))
for c in all_components
}
return SphericalDifferential(**result_args)
else:
return super()._combine_operation(op, other, reverse)
class PhysicsSphericalDifferential(BaseDifferential):
"""Differential(s) of 3D spherical coordinates using physics convention.
Parameters
----------
d_phi, d_theta : `~astropy.units.Quantity`
The differential azimuth and inclination.
d_r : `~astropy.units.Quantity`
The differential radial distance.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
base_representation = PhysicsSphericalRepresentation
def __init__(self, d_phi, d_theta=None, d_r=None, copy=True):
super().__init__(d_phi, d_theta, d_r, copy=copy)
if not self._d_phi.unit.is_equivalent(self._d_theta.unit):
raise u.UnitsError("d_phi and d_theta should have equivalent units.")
def represent_as(self, other_class, base=None):
# All spherical differentials can be done without going to Cartesian,
# though CosLat needs base for the latitude. For those, explicitly
# do the equivalent of self._d_lon_coslat in SphericalDifferential.
if issubclass(other_class, SphericalDifferential):
return other_class(self.d_phi, -self.d_theta, self.d_r)
elif issubclass(other_class, UnitSphericalDifferential):
return other_class(self.d_phi, -self.d_theta)
elif issubclass(other_class, SphericalCosLatDifferential):
self._check_base(base)
d_lon_coslat = self.d_phi * np.sin(base.theta)
return other_class(d_lon_coslat, -self.d_theta, self.d_r)
elif issubclass(other_class, UnitSphericalCosLatDifferential):
self._check_base(base)
d_lon_coslat = self.d_phi * np.sin(base.theta)
return other_class(d_lon_coslat, -self.d_theta)
elif issubclass(other_class, RadialDifferential):
return other_class(self.d_r)
return super().represent_as(other_class, base)
@classmethod
def from_representation(cls, representation, base=None):
# Other spherical differentials can be done without going to Cartesian,
# though we need base for the latitude to remove coslat. For that case,
# do the equivalent of cls._d_lon in SphericalDifferential.
if isinstance(representation, SphericalDifferential):
return cls(
representation.d_lon, -representation.d_lat, representation.d_distance
)
elif isinstance(representation, SphericalCosLatDifferential):
cls._check_base(base)
d_phi = representation.d_lon_coslat / np.sin(base.theta)
return cls(d_phi, -representation.d_lat, representation.d_distance)
return super().from_representation(representation, base)
def _scale_operation(self, op, *args, scaled_base=False):
if scaled_base:
return self.__class__(self.d_phi, self.d_theta, op(self.d_r, *args))
else:
return super()._scale_operation(op, *args)
class CylindricalDifferential(BaseDifferential):
"""Differential(s) of points in cylindrical coordinates.
Parameters
----------
d_rho : `~astropy.units.Quantity` ['speed']
The differential cylindrical radius.
d_phi : `~astropy.units.Quantity` ['angular speed']
The differential azimuth.
d_z : `~astropy.units.Quantity` ['speed']
The differential height.
copy : bool, optional
If `True` (default), arrays will be copied. If `False`, arrays will
be references, though possibly broadcast to ensure matching shapes.
"""
base_representation = CylindricalRepresentation
def __init__(self, d_rho, d_phi=None, d_z=None, copy=False):
super().__init__(d_rho, d_phi, d_z, copy=copy)
if not self._d_rho.unit.is_equivalent(self._d_z.unit):
raise u.UnitsError("d_rho and d_z should have equivalent units.")
| bsd-3-clause | cced535eeea23bd45822e0aa3152499d | 37.818656 | 97 | 0.605715 | 4.403112 | false | false | false | false |
astropy/astropy | astropy/units/structured.py | 3 | 20282 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module defines structured units and quantities.
"""
from __future__ import annotations # For python < 3.10
# Standard library
import operator
import numpy as np
from .core import UNITY, Unit, UnitBase
__all__ = ["StructuredUnit"]
DTYPE_OBJECT = np.dtype("O")
def _names_from_dtype(dtype):
"""Recursively extract field names from a dtype."""
names = []
for name in dtype.names:
subdtype = dtype.fields[name][0]
if subdtype.names:
names.append([name, _names_from_dtype(subdtype)])
else:
names.append(name)
return tuple(names)
def _normalize_names(names):
"""Recursively normalize, inferring upper level names for unadorned tuples.
Generally, we want the field names to be organized like dtypes, as in
``(['pv', ('p', 'v')], 't')``. But we automatically infer upper
field names if the list is absent from items like ``(('p', 'v'), 't')``,
by concatenating the names inside the tuple.
"""
result = []
for name in names:
if isinstance(name, str) and len(name) > 0:
result.append(name)
elif (
isinstance(name, list)
and len(name) == 2
and isinstance(name[0], str)
and len(name[0]) > 0
and isinstance(name[1], tuple)
and len(name[1]) > 0
):
result.append([name[0], _normalize_names(name[1])])
elif isinstance(name, tuple) and len(name) > 0:
new_tuple = _normalize_names(name)
name = "".join([(i[0] if isinstance(i, list) else i) for i in new_tuple])
result.append([name, new_tuple])
else:
raise ValueError(
f"invalid entry {name!r}. Should be a name, "
"tuple of names, or 2-element list of the "
"form [name, tuple of names]."
)
return tuple(result)
class StructuredUnit:
"""Container for units for a structured Quantity.
Parameters
----------
units : unit-like, tuple of unit-like, or `~astropy.units.StructuredUnit`
Tuples can be nested. If a `~astropy.units.StructuredUnit` is passed
in, it will be returned unchanged unless different names are requested.
names : tuple of str, tuple or list; `~numpy.dtype`; or `~astropy.units.StructuredUnit`, optional
Field names for the units, possibly nested. Can be inferred from a
structured `~numpy.dtype` or another `~astropy.units.StructuredUnit`.
For nested tuples, by default the name of the upper entry will be the
concatenation of the names of the lower levels. One can pass in a
list with the upper-level name and a tuple of lower-level names to
avoid this. For tuples, not all levels have to be given; for any level
not passed in, default field names of 'f0', 'f1', etc., will be used.
Notes
-----
It is recommended to initialze the class indirectly, using
`~astropy.units.Unit`. E.g., ``u.Unit('AU,AU/day')``.
When combined with a structured array to produce a structured
`~astropy.units.Quantity`, array field names will take precedence.
Generally, passing in ``names`` is needed only if the unit is used
unattached to a `~astropy.units.Quantity` and one needs to access its
fields.
Examples
--------
Various ways to initialize a `~astropy.units.StructuredUnit`::
>>> import astropy.units as u
>>> su = u.Unit('(AU,AU/day),yr')
>>> su
Unit("((AU, AU / d), yr)")
>>> su.field_names
(['f0', ('f0', 'f1')], 'f1')
>>> su['f1']
Unit("yr")
>>> su2 = u.StructuredUnit(((u.AU, u.AU/u.day), u.yr), names=(('p', 'v'), 't'))
>>> su2 == su
True
>>> su2.field_names
(['pv', ('p', 'v')], 't')
>>> su3 = u.StructuredUnit((su2['pv'], u.day), names=(['p_v', ('p', 'v')], 't'))
>>> su3.field_names
(['p_v', ('p', 'v')], 't')
>>> su3.keys()
('p_v', 't')
>>> su3.values()
(Unit("(AU, AU / d)"), Unit("d"))
Structured units share most methods with regular units::
>>> su.physical_type
((PhysicalType('length'), PhysicalType({'speed', 'velocity'})), PhysicalType('time'))
>>> su.si
Unit("((1.49598e+11 m, 1.73146e+06 m / s), 3.15576e+07 s)")
"""
def __new__(cls, units, names=None):
dtype = None
if names is not None:
if isinstance(names, StructuredUnit):
dtype = names._units.dtype
names = names.field_names
elif isinstance(names, np.dtype):
if not names.fields:
raise ValueError("dtype should be structured, with fields.")
dtype = np.dtype([(name, DTYPE_OBJECT) for name in names.names])
names = _names_from_dtype(names)
else:
if not isinstance(names, tuple):
names = (names,)
names = _normalize_names(names)
if not isinstance(units, tuple):
units = Unit(units)
if isinstance(units, StructuredUnit):
# Avoid constructing a new StructuredUnit if no field names
# are given, or if all field names are the same already anyway.
if names is None or units.field_names == names:
return units
# Otherwise, turn (the upper level) into a tuple, for renaming.
units = units.values()
else:
# Single regular unit: make a tuple for iteration below.
units = (units,)
if names is None:
names = tuple(f"f{i}" for i in range(len(units)))
elif len(units) != len(names):
raise ValueError("lengths of units and field names must match.")
converted = []
for unit, name in zip(units, names):
if isinstance(name, list):
# For list, the first item is the name of our level,
# and the second another tuple of names, i.e., we recurse.
unit = cls(unit, name[1])
name = name[0]
else:
# We are at the lowest level. Check unit.
unit = Unit(unit)
if dtype is not None and isinstance(unit, StructuredUnit):
raise ValueError(
"units do not match in depth with field "
"names from dtype or structured unit."
)
converted.append(unit)
self = super().__new__(cls)
if dtype is None:
dtype = np.dtype(
[
((name[0] if isinstance(name, list) else name), DTYPE_OBJECT)
for name in names
]
)
# Decay array to void so we can access by field name and number.
self._units = np.array(tuple(converted), dtype)[()]
return self
def __getnewargs__(self):
"""When de-serializing, e.g. pickle, start with a blank structure."""
return (), None
@property
def field_names(self):
"""Possibly nested tuple of the field names of the parts."""
return tuple(
([name, unit.field_names] if isinstance(unit, StructuredUnit) else name)
for name, unit in self.items()
)
# Allow StructuredUnit to be treated as an (ordered) mapping.
def __len__(self):
return len(self._units.dtype.names)
def __getitem__(self, item):
# Since we are based on np.void, indexing by field number works too.
return self._units[item]
def values(self):
return self._units.item()
def keys(self):
return self._units.dtype.names
def items(self):
return tuple(zip(self._units.dtype.names, self._units.item()))
def __iter__(self):
yield from self._units.dtype.names
# Helpers for methods below.
def _recursively_apply(self, func, cls=None):
"""Apply func recursively.
Parameters
----------
func : callable
Function to apply to all parts of the structured unit,
recursing as needed.
cls : type, optional
If given, should be a subclass of `~numpy.void`. By default,
will return a new `~astropy.units.StructuredUnit` instance.
"""
applied = tuple(func(part) for part in self.values())
# Once not NUMPY_LT_1_23: results = np.void(applied, self._units.dtype).
results = np.array(applied, self._units.dtype)[()]
if cls is not None:
return results.view((cls, results.dtype))
# Short-cut; no need to interpret field names, etc.
result = super().__new__(self.__class__)
result._units = results
return result
def _recursively_get_dtype(self, value, enter_lists=True):
"""Get structured dtype according to value, using our field names.
This is useful since ``np.array(value)`` would treat tuples as lower
levels of the array, rather than as elements of a structured array.
The routine does presume that the type of the first tuple is
representative of the rest. Used in ``_get_converter``.
For the special value of ``UNITY``, all fields are assumed to be 1.0,
and hence this will return an all-float dtype.
"""
if enter_lists:
while isinstance(value, list):
value = value[0]
if value is UNITY:
value = (UNITY,) * len(self)
elif not isinstance(value, tuple) or len(self) != len(value):
raise ValueError(f"cannot interpret value {value} for unit {self}.")
descr = []
for (name, unit), part in zip(self.items(), value):
if isinstance(unit, StructuredUnit):
descr.append(
(name, unit._recursively_get_dtype(part, enter_lists=False))
)
else:
# Got a part associated with a regular unit. Gets its dtype.
# Like for Quantity, we cast integers to float.
part = np.array(part)
part_dtype = part.dtype
if part_dtype.kind in "iu":
part_dtype = np.dtype(float)
descr.append((name, part_dtype, part.shape))
return np.dtype(descr)
@property
def si(self):
"""The `StructuredUnit` instance in SI units."""
return self._recursively_apply(operator.attrgetter("si"))
@property
def cgs(self):
"""The `StructuredUnit` instance in cgs units."""
return self._recursively_apply(operator.attrgetter("cgs"))
# Needed to pass through Unit initializer, so might as well use it.
def _get_physical_type_id(self):
return self._recursively_apply(
operator.methodcaller("_get_physical_type_id"), cls=Structure
)
@property
def physical_type(self):
"""Physical types of all the fields."""
return self._recursively_apply(
operator.attrgetter("physical_type"), cls=Structure
)
def decompose(self, bases=set()):
"""The `StructuredUnit` composed of only irreducible units.
Parameters
----------
bases : sequence of `~astropy.units.UnitBase`, optional
The bases to decompose into. When not provided,
decomposes down to any irreducible units. When provided,
the decomposed result will only contain the given units.
This will raises a `UnitsError` if it's not possible
to do so.
Returns
-------
`~astropy.units.StructuredUnit`
With the unit for each field containing only irreducible units.
"""
return self._recursively_apply(operator.methodcaller("decompose", bases=bases))
def is_equivalent(self, other, equivalencies=[]):
"""`True` if all fields are equivalent to the other's fields.
Parameters
----------
other : `~astropy.units.StructuredUnit`
The structured unit to compare with, or what can initialize one.
equivalencies : list of tuple, optional
A list of equivalence pairs to try if the units are not
directly convertible. See :ref:`unit_equivalencies`.
The list will be applied to all fields.
Returns
-------
bool
"""
try:
other = StructuredUnit(other)
except Exception:
return False
if len(self) != len(other):
return False
for self_part, other_part in zip(self.values(), other.values()):
if not self_part.is_equivalent(other_part, equivalencies=equivalencies):
return False
return True
def _get_converter(self, other, equivalencies=[]):
if not isinstance(other, type(self)):
other = self.__class__(other, names=self)
converters = [
self_part._get_converter(other_part, equivalencies=equivalencies)
for (self_part, other_part) in zip(self.values(), other.values())
]
def converter(value):
if not hasattr(value, "dtype"):
value = np.array(value, self._recursively_get_dtype(value))
result = np.empty_like(value)
for name, converter_ in zip(result.dtype.names, converters):
result[name] = converter_(value[name])
# Index with empty tuple to decay array scalars to numpy void.
return result if result.shape else result[()]
return converter
def to(self, other, value=np._NoValue, equivalencies=[]):
"""Return values converted to the specified unit.
Parameters
----------
other : `~astropy.units.StructuredUnit`
The unit to convert to. If necessary, will be converted to
a `~astropy.units.StructuredUnit` using the dtype of ``value``.
value : array-like, optional
Value(s) in the current unit to be converted to the
specified unit. If a sequence, the first element must have
entries of the correct type to represent all elements (i.e.,
not have, e.g., a ``float`` where other elements have ``complex``).
If not given, assumed to have 1. in all fields.
equivalencies : list of tuple, optional
A list of equivalence pairs to try if the units are not
directly convertible. See :ref:`unit_equivalencies`.
This list is in addition to possible global defaults set by, e.g.,
`set_enabled_equivalencies`.
Use `None` to turn off all equivalencies.
Returns
-------
values : scalar or array
Converted value(s).
Raises
------
UnitsError
If units are inconsistent
"""
if value is np._NoValue:
# We do not have UNITY as a default, since then the docstring
# would list 1.0 as default, yet one could not pass that in.
value = UNITY
return self._get_converter(other, equivalencies=equivalencies)(value)
def to_string(self, format="generic"):
"""Output the unit in the given format as a string.
Units are separated by commas.
Parameters
----------
format : `astropy.units.format.Base` instance or str
The name of a format or a formatter object. If not
provided, defaults to the generic format.
Notes
-----
Structured units can be written to all formats, but can be
re-read only with 'generic'.
"""
parts = [part.to_string(format) for part in self.values()]
out_fmt = "({})" if len(self) > 1 else "({},)"
if format.startswith("latex"):
# Strip $ from parts and add them on the outside.
parts = [part[1:-1] for part in parts]
out_fmt = "$" + out_fmt + "$"
return out_fmt.format(", ".join(parts))
def _repr_latex_(self):
return self.to_string("latex")
__array_ufunc__ = None
def __mul__(self, other):
if isinstance(other, str):
try:
other = Unit(other, parse_strict="silent")
except Exception:
return NotImplemented
if isinstance(other, UnitBase):
new_units = tuple(part * other for part in self.values())
return self.__class__(new_units, names=self)
if isinstance(other, StructuredUnit):
return NotImplemented
# Anything not like a unit, try initialising as a structured quantity.
try:
from .quantity import Quantity
return Quantity(other, unit=self)
except Exception:
return NotImplemented
def __rmul__(self, other):
return self.__mul__(other)
def __truediv__(self, other):
if isinstance(other, str):
try:
other = Unit(other, parse_strict="silent")
except Exception:
return NotImplemented
if isinstance(other, UnitBase):
new_units = tuple(part / other for part in self.values())
return self.__class__(new_units, names=self)
return NotImplemented
def __rlshift__(self, m):
try:
from .quantity import Quantity
return Quantity(m, self, copy=False, subok=True)
except Exception:
return NotImplemented
def __str__(self):
return self.to_string()
def __repr__(self):
return f'Unit("{self.to_string()}")'
def __eq__(self, other):
try:
other = StructuredUnit(other)
except Exception:
return NotImplemented
return self.values() == other.values()
def __ne__(self, other):
if not isinstance(other, type(self)):
try:
other = StructuredUnit(other)
except Exception:
return NotImplemented
return self.values() != other.values()
class Structure(np.void):
"""Single element structure for physical type IDs, etc.
Behaves like a `~numpy.void` and thus mostly like a tuple which can also
be indexed with field names, but overrides ``__eq__`` and ``__ne__`` to
compare only the contents, not the field names. Furthermore, this way no
`FutureWarning` about comparisons is given.
"""
# Note that it is important for physical type IDs to not be stored in a
# tuple, since then the physical types would be treated as alternatives in
# :meth:`~astropy.units.UnitBase.is_equivalent`. (Of course, in that
# case, they could also not be indexed by name.)
def __eq__(self, other):
if isinstance(other, np.void):
other = other.item()
return self.item() == other
def __ne__(self, other):
if isinstance(other, np.void):
other = other.item()
return self.item() != other
def _structured_unit_like_dtype(
unit: UnitBase | StructuredUnit, dtype: np.dtype
) -> StructuredUnit:
"""Make a `StructuredUnit` of one unit, with the structure of a `numpy.dtype`.
Parameters
----------
unit : UnitBase
The unit that will be filled into the structure.
dtype : `numpy.dtype`
The structure for the StructuredUnit.
Returns
-------
StructuredUnit
"""
if isinstance(unit, StructuredUnit):
# If unit is structured, it should match the dtype. This function is
# only used in Quantity, which performs this check, so it's fine to
# return as is.
return unit
# Make a structured unit
units = []
for name in dtype.names:
subdtype = dtype.fields[name][0]
if subdtype.names is not None:
units.append(_structured_unit_like_dtype(unit, subdtype))
else:
units.append(unit)
return StructuredUnit(tuple(units), names=dtype.names)
| bsd-3-clause | 907ac10546b8805561ddb2526dc6ab2f | 34.52014 | 101 | 0.571393 | 4.283421 | false | false | false | false |
mozilla/app-validator | tests/js/test_operators.py | 5 | 7174 | from nose.tools import eq_
from js_helper import TestCase
class TestMath(TestCase):
def test_basic_math(self):
"Tests that contexts work and that basic math is executed properly"
self.run_script("""
var x = 1;
var y = 2;
var z = x + y;
var dbz = 1;
var dbz1 = 1;
dbz = dbz / 0;
dbz1 = dbz1 % 0;
var dbz2 = 1;
var dbz3 = 1;
dbz2 /= 0;
dbz3 %= 0;
var a = 2 + 3;
var b = a - 1;
var c = b * 2;
""")
self.assert_silent()
self.assert_var_eq("x", 1)
self.assert_var_eq("y", 2)
self.assert_var_eq("z", 3)
self.assert_var_eq("dbz", 0) # Spidermonkey does this.
self.assert_var_eq("dbz1", 0) # ...and this.
self.assert_var_eq("dbz2", 0)
self.assert_var_eq("dbz3", 0)
self.assert_var_eq("a", 5)
self.assert_var_eq("b", 4)
self.assert_var_eq("c", 8)
def test_in_operator(self):
"Tests the 'in' operator."
self.run_script("""
var list = ["a",1,2,3,"foo"];
var dict = {"abc":123, "foo":"bar"};
// Must be true
var x = 0 in list;
var y = "abc" in dict;
// Must be false
var a = 5 in list;
var b = "asdf" in dict;
""")
self.assert_silent()
self.assert_var_eq("x", True)
self.assert_var_eq("y", True)
self.assert_var_eq("a", False)
self.assert_var_eq("b", False)
def test_function_instanceof(self):
self.run_script("""
var x = foo();
print(x instanceof Function);
""")
self.assert_silent()
def test_unary_typeof(self):
"""Test that the typeof operator does good."""
self.run_script("""
var a = typeof void 0,
b = typeof null,
c = typeof true,
d = typeof false,
e = typeof new Boolean(),
f = typeof new Boolean(true),
g = typeof Boolean(),
h = typeof Boolean(false),
i = typeof Boolean(true),
j = typeof NaN,
k = typeof Infinity,
l = typeof -Infinity,
m = typeof Math.PI,
n = typeof 0,
o = typeof 1,
p = typeof -1,
q = typeof '0',
r = typeof Number(),
s = typeof Number(0),
t = typeof new Number(),
u = typeof new Number(0),
v = typeof new Number(1),
x = typeof function() {},
y = typeof Math.abs;
""")
self.assert_var_eq("a", "undefined")
self.assert_var_eq("b", "object")
self.assert_var_eq("c", "boolean")
self.assert_var_eq("d", "boolean")
self.assert_var_eq("e", "object")
self.assert_var_eq("f", "object")
self.assert_var_eq("g", "boolean")
self.assert_var_eq("h", "boolean")
self.assert_var_eq("i", "boolean")
# TODO: Implement "typeof" for predefined entities
# self.assert_var_eq("j", "number")
# self.assert_var_eq("k", "number")
# self.assert_var_eq("l", "number")
self.assert_var_eq("m", "number")
self.assert_var_eq("n", "number")
self.assert_var_eq("o", "number")
self.assert_var_eq("p", "number")
self.assert_var_eq("q", "string")
self.assert_var_eq("r", "number")
self.assert_var_eq("s", "number")
self.assert_var_eq("t", "object")
self.assert_var_eq("u", "object")
self.assert_var_eq("v", "object")
self.assert_var_eq("x", "function")
self.assert_var_eq("y", "function")
# TODO(basta): Still working on the delete operator...should be done soon.
#def test_delete_operator(self):
# """Test that the delete operator works correctly."""
#
# # Test that array elements can be destroyed.
# eq_(_get_var(_do_test_raw("""
# var x = [1, 2, 3];
# delete(x[2]);
# var value = x.length;
# """), "value"), 2)
#
# # Test that hte right array elements are destroyed.
# eq_(_get_var(_do_test_raw("""
# var x = [1, 2, 3];
# delete(x[2]);
# var value = x.toString();
# """), "value"), "1,2")
#
# eq_(_get_var(_do_test_raw("""
# var x = "asdf";
# delete x;
# var value = x;
# """), "value"), None)
#
# assert _do_test_raw("""
# delete(Math.PI);
# """).failed()
def test_logical_not(self):
"""Test that logical not is evaluated properly."""
self.run_script("""
var a = !(null),
// b = !(var x),
c = !(void 0),
d = !(false),
e = !(true),
// f = !(),
g = !(0),
h = !(-0),
i = !(NaN),
j = !(Infinity),
k = !(-Infinity),
l = !(Math.PI),
m = !(1),
n = !(-1),
o = !(''),
p = !('\\t'),
q = !('0'),
r = !('string'),
s = !(new String('')); // This should cover all type globals.
""")
self.assert_var_eq("a", True)
# self.assert_var_eq("b", True)
self.assert_var_eq("c", True)
self.assert_var_eq("d", True)
self.assert_var_eq("e", False)
# self.assert_var_eq("f", True)
self.assert_var_eq("g", True)
self.assert_var_eq("h", True)
# self.assert_var_eq("i", True)
self.assert_var_eq("j", False)
self.assert_var_eq("k", False)
self.assert_var_eq("l", False)
self.assert_var_eq("m", False)
self.assert_var_eq("n", False)
self.assert_var_eq("o", True)
self.assert_var_eq("p", False)
self.assert_var_eq("q", False)
self.assert_var_eq("r", False)
self.assert_var_eq("s", False)
def test_concat_plus_infinity(self):
"""Test that Infinity is concatenated properly."""
self.run_script("""
var a = Infinity + "foo",
b = (-Infinity) + "foo",
c = "foo" + Infinity,
d = "foo" + (-Infinity);
""")
self.assert_var_eq("a", "Infinityfoo")
self.assert_var_eq("b", "-Infinityfoo")
self.assert_var_eq("c", "fooInfinity")
self.assert_var_eq("d", "foo-Infinity")
def test_simple_operators_when_dirty(self):
"""
Test that when we're dealing with dirty objects, binary operations don't
cave in the roof.
Note that this test (if it fails) may cause some ugly crashes.
"""
self.run_script("""
var x = foo(); // x is now a dirty object.
y = foo(); // y is now a dirty object as well.
""" +
"""y += y + x;""" * 100) # This bit makes the validator's head explode.
def test_wrapped_python_exceptions(self):
"""
Test that OverflowErrors in traversal don't crash the validation
process.
"""
self.run_script("""
var x = Math.exp(-4*1000000*-0.0641515994108);
""")
| bsd-3-clause | 448b5d48ae264e2c505e0d3e1295eb97 | 29.142857 | 80 | 0.474212 | 3.383962 | false | true | false | false |
scikit-learn/scikit-learn | examples/decomposition/plot_sparse_coding.py | 12 | 4027 | """
===========================================
Sparse coding with a precomputed dictionary
===========================================
Transform a signal as a sparse combination of Ricker wavelets. This example
visually compares different sparse coding methods using the
:class:`~sklearn.decomposition.SparseCoder` estimator. The Ricker (also known
as Mexican hat or the second derivative of a Gaussian) is not a particularly
good kernel to represent piecewise constant signals like this one. It can
therefore be seen how much adding different widths of atoms matters and it
therefore motivates learning the dictionary to best fit your type of signals.
The richer dictionary on the right is not larger in size, heavier subsampling
is performed in order to stay on the same order of magnitude.
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import SparseCoder
def ricker_function(resolution, center, width):
"""Discrete sub-sampled Ricker (Mexican hat) wavelet"""
x = np.linspace(0, resolution - 1, resolution)
x = (
(2 / (np.sqrt(3 * width) * np.pi**0.25))
* (1 - (x - center) ** 2 / width**2)
* np.exp(-((x - center) ** 2) / (2 * width**2))
)
return x
def ricker_matrix(width, resolution, n_components):
"""Dictionary of Ricker (Mexican hat) wavelets"""
centers = np.linspace(0, resolution - 1, n_components)
D = np.empty((n_components, resolution))
for i, center in enumerate(centers):
D[i] = ricker_function(resolution, center, width)
D /= np.sqrt(np.sum(D**2, axis=1))[:, np.newaxis]
return D
resolution = 1024
subsampling = 3 # subsampling factor
width = 100
n_components = resolution // subsampling
# Compute a wavelet dictionary
D_fixed = ricker_matrix(width=width, resolution=resolution, n_components=n_components)
D_multi = np.r_[
tuple(
ricker_matrix(width=w, resolution=resolution, n_components=n_components // 5)
for w in (10, 50, 100, 500, 1000)
)
]
# Generate a signal
y = np.linspace(0, resolution - 1, resolution)
first_quarter = y < resolution / 4
y[first_quarter] = 3.0
y[np.logical_not(first_quarter)] = -1.0
# List the different sparse coding methods in the following format:
# (title, transform_algorithm, transform_alpha,
# transform_n_nozero_coefs, color)
estimators = [
("OMP", "omp", None, 15, "navy"),
("Lasso", "lasso_lars", 2, None, "turquoise"),
]
lw = 2
plt.figure(figsize=(13, 6))
for subplot, (D, title) in enumerate(
zip((D_fixed, D_multi), ("fixed width", "multiple widths"))
):
plt.subplot(1, 2, subplot + 1)
plt.title("Sparse coding against %s dictionary" % title)
plt.plot(y, lw=lw, linestyle="--", label="Original signal")
# Do a wavelet approximation
for title, algo, alpha, n_nonzero, color in estimators:
coder = SparseCoder(
dictionary=D,
transform_n_nonzero_coefs=n_nonzero,
transform_alpha=alpha,
transform_algorithm=algo,
)
x = coder.transform(y.reshape(1, -1))
density = len(np.flatnonzero(x))
x = np.ravel(np.dot(x, D))
squared_error = np.sum((y - x) ** 2)
plt.plot(
x,
color=color,
lw=lw,
label="%s: %s nonzero coefs,\n%.2f error" % (title, density, squared_error),
)
# Soft thresholding debiasing
coder = SparseCoder(
dictionary=D, transform_algorithm="threshold", transform_alpha=20
)
x = coder.transform(y.reshape(1, -1))
_, idx = np.where(x != 0)
x[0, idx], _, _, _ = np.linalg.lstsq(D[idx, :].T, y, rcond=None)
x = np.ravel(np.dot(x, D))
squared_error = np.sum((y - x) ** 2)
plt.plot(
x,
color="darkorange",
lw=lw,
label="Thresholding w/ debiasing:\n%d nonzero coefs, %.2f error"
% (len(idx), squared_error),
)
plt.axis("tight")
plt.legend(shadow=False, loc="best")
plt.subplots_adjust(0.04, 0.07, 0.97, 0.90, 0.09, 0.2)
plt.show()
| bsd-3-clause | 0f765a4035ebc147bc97bc510623f72c | 32.558333 | 88 | 0.627266 | 3.361436 | false | false | false | false |
scikit-learn/scikit-learn | sklearn/datasets/_openml.py | 12 | 38558 | import gzip
import hashlib
import json
import os
import shutil
import time
from contextlib import closing
from functools import wraps
from os.path import join
from typing import Callable, Optional, Dict, Tuple, List, Any, Union
from tempfile import TemporaryDirectory
from urllib.error import HTTPError, URLError
from urllib.request import urlopen, Request
from warnings import warn
import numpy as np
from . import get_data_home
from ._arff_parser import load_arff_from_gzip_file
from ..utils import Bunch
from ..utils import check_pandas_support # noqa
__all__ = ["fetch_openml"]
_OPENML_PREFIX = "https://openml.org/"
_SEARCH_NAME = "api/v1/json/data/list/data_name/{}/limit/2"
_DATA_INFO = "api/v1/json/data/{}"
_DATA_FEATURES = "api/v1/json/data/features/{}"
_DATA_QUALITIES = "api/v1/json/data/qualities/{}"
_DATA_FILE = "data/v1/download/{}"
OpenmlQualitiesType = List[Dict[str, str]]
OpenmlFeaturesType = List[Dict[str, str]]
def _get_local_path(openml_path: str, data_home: str) -> str:
return os.path.join(data_home, "openml.org", openml_path + ".gz")
def _retry_with_clean_cache(openml_path: str, data_home: Optional[str]) -> Callable:
"""If the first call to the decorated function fails, the local cached
file is removed, and the function is called again. If ``data_home`` is
``None``, then the function is called once.
"""
def decorator(f):
@wraps(f)
def wrapper(*args, **kw):
if data_home is None:
return f(*args, **kw)
try:
return f(*args, **kw)
except URLError:
raise
except Exception:
warn("Invalid cache, redownloading file", RuntimeWarning)
local_path = _get_local_path(openml_path, data_home)
if os.path.exists(local_path):
os.unlink(local_path)
return f(*args, **kw)
return wrapper
return decorator
def _retry_on_network_error(
n_retries: int = 3, delay: float = 1.0, url: str = ""
) -> Callable:
"""If the function call results in a network error, call the function again
up to ``n_retries`` times with a ``delay`` between each call. If the error
has a 412 status code, don't call the function again as this is a specific
OpenML error.
The url parameter is used to give more information to the user about the
error.
"""
def decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
retry_counter = n_retries
while True:
try:
return f(*args, **kwargs)
except (URLError, TimeoutError) as e:
# 412 is a specific OpenML error code.
if isinstance(e, HTTPError) and e.code == 412:
raise
if retry_counter == 0:
raise
warn(
f"A network error occurred while downloading {url}. Retrying..."
)
retry_counter -= 1
time.sleep(delay)
return wrapper
return decorator
def _open_openml_url(
openml_path: str, data_home: Optional[str], n_retries: int = 3, delay: float = 1.0
):
"""
Returns a resource from OpenML.org. Caches it to data_home if required.
Parameters
----------
openml_path : str
OpenML URL that will be accessed. This will be prefixes with
_OPENML_PREFIX.
data_home : str
Directory to which the files will be cached. If None, no caching will
be applied.
n_retries : int, default=3
Number of retries when HTTP errors are encountered. Error with status
code 412 won't be retried as they represent OpenML generic errors.
delay : float, default=1.0
Number of seconds between retries.
Returns
-------
result : stream
A stream to the OpenML resource.
"""
def is_gzip_encoded(_fsrc):
return _fsrc.info().get("Content-Encoding", "") == "gzip"
req = Request(_OPENML_PREFIX + openml_path)
req.add_header("Accept-encoding", "gzip")
if data_home is None:
fsrc = _retry_on_network_error(n_retries, delay, req.full_url)(urlopen)(req)
if is_gzip_encoded(fsrc):
return gzip.GzipFile(fileobj=fsrc, mode="rb")
return fsrc
local_path = _get_local_path(openml_path, data_home)
dir_name, file_name = os.path.split(local_path)
if not os.path.exists(local_path):
os.makedirs(dir_name, exist_ok=True)
try:
# Create a tmpdir as a subfolder of dir_name where the final file will
# be moved to if the download is successful. This guarantees that the
# renaming operation to the final location is atomic to ensure the
# concurrence safety of the dataset caching mechanism.
with TemporaryDirectory(dir=dir_name) as tmpdir:
with closing(
_retry_on_network_error(n_retries, delay, req.full_url)(urlopen)(
req
)
) as fsrc:
opener: Callable
if is_gzip_encoded(fsrc):
opener = open
else:
opener = gzip.GzipFile
with opener(os.path.join(tmpdir, file_name), "wb") as fdst:
shutil.copyfileobj(fsrc, fdst)
shutil.move(fdst.name, local_path)
except Exception:
if os.path.exists(local_path):
os.unlink(local_path)
raise
# XXX: First time, decompression will not be necessary (by using fsrc), but
# it will happen nonetheless
return gzip.GzipFile(local_path, "rb")
class OpenMLError(ValueError):
"""HTTP 412 is a specific OpenML error code, indicating a generic error"""
pass
def _get_json_content_from_openml_api(
url: str,
error_message: Optional[str],
data_home: Optional[str],
n_retries: int = 3,
delay: float = 1.0,
) -> Dict:
"""
Loads json data from the openml api.
Parameters
----------
url : str
The URL to load from. Should be an official OpenML endpoint.
error_message : str or None
The error message to raise if an acceptable OpenML error is thrown
(acceptable error is, e.g., data id not found. Other errors, like 404's
will throw the native error message).
data_home : str or None
Location to cache the response. None if no cache is required.
n_retries : int, default=3
Number of retries when HTTP errors are encountered. Error with status
code 412 won't be retried as they represent OpenML generic errors.
delay : float, default=1.0
Number of seconds between retries.
Returns
-------
json_data : json
the json result from the OpenML server if the call was successful.
An exception otherwise.
"""
@_retry_with_clean_cache(url, data_home)
def _load_json():
with closing(
_open_openml_url(url, data_home, n_retries=n_retries, delay=delay)
) as response:
return json.loads(response.read().decode("utf-8"))
try:
return _load_json()
except HTTPError as error:
# 412 is an OpenML specific error code, indicating a generic error
# (e.g., data not found)
if error.code != 412:
raise error
# 412 error, not in except for nicer traceback
raise OpenMLError(error_message)
def _get_data_info_by_name(
name: str,
version: Union[int, str],
data_home: Optional[str],
n_retries: int = 3,
delay: float = 1.0,
):
"""
Utilizes the openml dataset listing api to find a dataset by
name/version
OpenML api function:
https://www.openml.org/api_docs#!/data/get_data_list_data_name_data_name
Parameters
----------
name : str
name of the dataset
version : int or str
If version is an integer, the exact name/version will be obtained from
OpenML. If version is a string (value: "active") it will take the first
version from OpenML that is annotated as active. Any other string
values except "active" are treated as integer.
data_home : str or None
Location to cache the response. None if no cache is required.
n_retries : int, default=3
Number of retries when HTTP errors are encountered. Error with status
code 412 won't be retried as they represent OpenML generic errors.
delay : float, default=1.0
Number of seconds between retries.
Returns
-------
first_dataset : json
json representation of the first dataset object that adhired to the
search criteria
"""
if version == "active":
# situation in which we return the oldest active version
url = _SEARCH_NAME.format(name) + "/status/active/"
error_msg = "No active dataset {} found.".format(name)
json_data = _get_json_content_from_openml_api(
url,
error_msg,
data_home=data_home,
n_retries=n_retries,
delay=delay,
)
res = json_data["data"]["dataset"]
if len(res) > 1:
warn(
"Multiple active versions of the dataset matching the name"
" {name} exist. Versions may be fundamentally different, "
"returning version"
" {version}.".format(name=name, version=res[0]["version"])
)
return res[0]
# an integer version has been provided
url = (_SEARCH_NAME + "/data_version/{}").format(name, version)
try:
json_data = _get_json_content_from_openml_api(
url,
error_message=None,
data_home=data_home,
n_retries=n_retries,
delay=delay,
)
except OpenMLError:
# we can do this in 1 function call if OpenML does not require the
# specification of the dataset status (i.e., return datasets with a
# given name / version regardless of active, deactivated, etc. )
# TODO: feature request OpenML.
url += "/status/deactivated"
error_msg = "Dataset {} with version {} not found.".format(name, version)
json_data = _get_json_content_from_openml_api(
url,
error_msg,
data_home=data_home,
n_retries=n_retries,
delay=delay,
)
return json_data["data"]["dataset"][0]
def _get_data_description_by_id(
data_id: int,
data_home: Optional[str],
n_retries: int = 3,
delay: float = 1.0,
) -> Dict[str, Any]:
# OpenML API function: https://www.openml.org/api_docs#!/data/get_data_id
url = _DATA_INFO.format(data_id)
error_message = "Dataset with data_id {} not found.".format(data_id)
json_data = _get_json_content_from_openml_api(
url,
error_message,
data_home=data_home,
n_retries=n_retries,
delay=delay,
)
return json_data["data_set_description"]
def _get_data_features(
data_id: int,
data_home: Optional[str],
n_retries: int = 3,
delay: float = 1.0,
) -> OpenmlFeaturesType:
# OpenML function:
# https://www.openml.org/api_docs#!/data/get_data_features_id
url = _DATA_FEATURES.format(data_id)
error_message = "Dataset with data_id {} not found.".format(data_id)
json_data = _get_json_content_from_openml_api(
url,
error_message,
data_home=data_home,
n_retries=n_retries,
delay=delay,
)
return json_data["data_features"]["feature"]
def _get_data_qualities(
data_id: int,
data_home: Optional[str],
n_retries: int = 3,
delay: float = 1.0,
) -> OpenmlQualitiesType:
# OpenML API function:
# https://www.openml.org/api_docs#!/data/get_data_qualities_id
url = _DATA_QUALITIES.format(data_id)
error_message = "Dataset with data_id {} not found.".format(data_id)
json_data = _get_json_content_from_openml_api(
url,
error_message,
data_home=data_home,
n_retries=n_retries,
delay=delay,
)
# the qualities might not be available, but we still try to process
# the data
return json_data.get("data_qualities", {}).get("quality", [])
def _get_num_samples(data_qualities: OpenmlQualitiesType) -> int:
"""Get the number of samples from data qualities.
Parameters
----------
data_qualities : list of dict
Used to retrieve the number of instances (samples) in the dataset.
Returns
-------
n_samples : int
The number of samples in the dataset or -1 if data qualities are
unavailable.
"""
# If the data qualities are unavailable, we return -1
default_n_samples = -1
qualities = {d["name"]: d["value"] for d in data_qualities}
return int(float(qualities.get("NumberOfInstances", default_n_samples)))
def _load_arff_response(
url: str,
data_home: Optional[str],
parser: str,
output_type: str,
openml_columns_info: dict,
feature_names_to_select: List[str],
target_names_to_select: List[str],
shape: Optional[Tuple[int, int]],
md5_checksum: str,
n_retries: int = 3,
delay: float = 1.0,
):
"""Load the ARFF data associated with the OpenML URL.
In addition of loading the data, this function will also check the
integrity of the downloaded file from OpenML using MD5 checksum.
Parameters
----------
url : str
The URL of the ARFF file on OpenML.
data_home : str
The location where to cache the data.
parser : {"liac-arff", "pandas"}
The parser used to parse the ARFF file.
output_type : {"numpy", "pandas", "sparse"}
The type of the arrays that will be returned. The possibilities are:
- `"numpy"`: both `X` and `y` will be NumPy arrays;
- `"sparse"`: `X` will be sparse matrix and `y` will be a NumPy array;
- `"pandas"`: `X` will be a pandas DataFrame and `y` will be either a
pandas Series or DataFrame.
openml_columns_info : dict
The information provided by OpenML regarding the columns of the ARFF
file.
feature_names_to_select : list of str
The list of the features to be selected.
target_names_to_select : list of str
The list of the target variables to be selected.
shape : tuple or None
With `parser="liac-arff"`, when using a generator to load the data,
one needs to provide the shape of the data beforehand.
md5_checksum : str
The MD5 checksum provided by OpenML to check the data integrity.
Returns
-------
X : {ndarray, sparse matrix, dataframe}
The data matrix.
y : {ndarray, dataframe, series}
The target.
frame : dataframe or None
A dataframe containing both `X` and `y`. `None` if
`output_array_type != "pandas"`.
categories : list of str or None
The names of the features that are categorical. `None` if
`output_array_type == "pandas"`.
"""
gzip_file = _open_openml_url(url, data_home, n_retries=n_retries, delay=delay)
with closing(gzip_file):
md5 = hashlib.md5()
for chunk in iter(lambda: gzip_file.read(4096), b""):
md5.update(chunk)
actual_md5_checksum = md5.hexdigest()
if actual_md5_checksum != md5_checksum:
raise ValueError(
f"md5 checksum of local file for {url} does not match description: "
f"expected: {md5_checksum} but got {actual_md5_checksum}. "
"Downloaded file could have been modified / corrupted, clean cache "
"and retry..."
)
gzip_file = _open_openml_url(url, data_home, n_retries=n_retries, delay=delay)
with closing(gzip_file):
X, y, frame, categories = load_arff_from_gzip_file(
gzip_file,
parser=parser,
output_type=output_type,
openml_columns_info=openml_columns_info,
feature_names_to_select=feature_names_to_select,
target_names_to_select=target_names_to_select,
shape=shape,
)
return X, y, frame, categories
def _download_data_to_bunch(
url: str,
sparse: bool,
data_home: Optional[str],
*,
as_frame: bool,
openml_columns_info: List[dict],
data_columns: List[str],
target_columns: List[str],
shape: Optional[Tuple[int, int]],
md5_checksum: str,
n_retries: int = 3,
delay: float = 1.0,
parser: str,
):
"""Download ARFF data, load it to a specific container and create to Bunch.
This function has a mechanism to retry/cache/clean the data.
Parameters
----------
url : str
The URL of the ARFF file on OpenML.
sparse : bool
Whether the dataset is expected to use the sparse ARFF format.
data_home : str
The location where to cache the data.
as_frame : bool
Whether or not to return the data into a pandas DataFrame.
openml_columns_info : list of dict
The information regarding the columns provided by OpenML for the
ARFF dataset. The information is stored as a list of dictionaries.
data_columns : list of str
The list of the features to be selected.
target_columns : list of str
The list of the target variables to be selected.
shape : tuple or None
With `parser="liac-arff"`, when using a generator to load the data,
one needs to provide the shape of the data beforehand.
md5_checksum : str
The MD5 checksum provided by OpenML to check the data integrity.
n_retries : int, default=3
Number of retries when HTTP errors are encountered. Error with status
code 412 won't be retried as they represent OpenML generic errors.
delay : float, default=1.0
Number of seconds between retries.
parser : {"liac-arff", "pandas"}
The parser used to parse the ARFF file.
Returns
-------
data : :class:`~sklearn.utils.Bunch`
Dictionary-like object, with the following attributes.
X : {ndarray, sparse matrix, dataframe}
The data matrix.
y : {ndarray, dataframe, series}
The target.
frame : dataframe or None
A dataframe containing both `X` and `y`. `None` if
`output_array_type != "pandas"`.
categories : list of str or None
The names of the features that are categorical. `None` if
`output_array_type == "pandas"`.
"""
# Prepare which columns and data types should be returned for the X and y
features_dict = {feature["name"]: feature for feature in openml_columns_info}
if sparse:
output_type = "sparse"
elif as_frame:
output_type = "pandas"
else:
output_type = "numpy"
# XXX: target columns should all be categorical or all numeric
_verify_target_data_type(features_dict, target_columns)
for name in target_columns:
column_info = features_dict[name]
n_missing_values = int(column_info["number_of_missing_values"])
if n_missing_values > 0:
raise ValueError(
f"Target column '{column_info['name']}' has {n_missing_values} missing "
"values. Missing values are not supported for target columns."
)
X, y, frame, categories = _retry_with_clean_cache(url, data_home)(
_load_arff_response
)(
url,
data_home,
parser=parser,
output_type=output_type,
openml_columns_info=features_dict,
feature_names_to_select=data_columns,
target_names_to_select=target_columns,
shape=shape,
md5_checksum=md5_checksum,
n_retries=n_retries,
delay=delay,
)
return Bunch(
data=X,
target=y,
frame=frame,
categories=categories,
feature_names=data_columns,
target_names=target_columns,
)
def _verify_target_data_type(features_dict, target_columns):
# verifies the data type of the y array in case there are multiple targets
# (throws an error if these targets do not comply with sklearn support)
if not isinstance(target_columns, list):
raise ValueError("target_column should be list, got: %s" % type(target_columns))
found_types = set()
for target_column in target_columns:
if target_column not in features_dict:
raise KeyError(f"Could not find target_column='{target_column}'")
if features_dict[target_column]["data_type"] == "numeric":
found_types.add(np.float64)
else:
found_types.add(object)
# note: we compare to a string, not boolean
if features_dict[target_column]["is_ignore"] == "true":
warn(f"target_column='{target_column}' has flag is_ignore.")
if features_dict[target_column]["is_row_identifier"] == "true":
warn(f"target_column='{target_column}' has flag is_row_identifier.")
if len(found_types) > 1:
raise ValueError(
"Can only handle homogeneous multi-target datasets, "
"i.e., all targets are either numeric or "
"categorical."
)
def _valid_data_column_names(features_list, target_columns):
# logic for determining on which columns can be learned. Note that from the
# OpenML guide follows that columns that have the `is_row_identifier` or
# `is_ignore` flag, these can not be learned on. Also target columns are
# excluded.
valid_data_column_names = []
for feature in features_list:
if (
feature["name"] not in target_columns
and feature["is_ignore"] != "true"
and feature["is_row_identifier"] != "true"
):
valid_data_column_names.append(feature["name"])
return valid_data_column_names
def fetch_openml(
name: Optional[str] = None,
*,
version: Union[str, int] = "active",
data_id: Optional[int] = None,
data_home: Optional[str] = None,
target_column: Optional[Union[str, List]] = "default-target",
cache: bool = True,
return_X_y: bool = False,
as_frame: Union[str, bool] = "auto",
n_retries: int = 3,
delay: float = 1.0,
parser: Optional[str] = "warn",
):
"""Fetch dataset from openml by name or dataset id.
Datasets are uniquely identified by either an integer ID or by a
combination of name and version (i.e. there might be multiple
versions of the 'iris' dataset). Please give either name or data_id
(not both). In case a name is given, a version can also be
provided.
Read more in the :ref:`User Guide <openml>`.
.. versionadded:: 0.20
.. note:: EXPERIMENTAL
The API is experimental (particularly the return value structure),
and might have small backward-incompatible changes without notice
or warning in future releases.
Parameters
----------
name : str, default=None
String identifier of the dataset. Note that OpenML can have multiple
datasets with the same name.
version : int or 'active', default='active'
Version of the dataset. Can only be provided if also ``name`` is given.
If 'active' the oldest version that's still active is used. Since
there may be more than one active version of a dataset, and those
versions may fundamentally be different from one another, setting an
exact version is highly recommended.
data_id : int, default=None
OpenML ID of the dataset. The most specific way of retrieving a
dataset. If data_id is not given, name (and potential version) are
used to obtain a dataset.
data_home : str, default=None
Specify another download and cache folder for the data sets. By default
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
target_column : str, list or None, default='default-target'
Specify the column name in the data to use as target. If
'default-target', the standard target column a stored on the server
is used. If ``None``, all columns are returned as data and the
target is ``None``. If list (of strings), all columns with these names
are returned as multi-target (Note: not all scikit-learn classifiers
can handle all types of multi-output combinations).
cache : bool, default=True
Whether to cache the downloaded datasets into `data_home`.
return_X_y : bool, default=False
If True, returns ``(data, target)`` instead of a Bunch object. See
below for more information about the `data` and `target` objects.
as_frame : bool or 'auto', default='auto'
If True, the data is a pandas DataFrame including columns with
appropriate dtypes (numeric, string or categorical). The target is
a pandas DataFrame or Series depending on the number of target_columns.
The Bunch will contain a ``frame`` attribute with the target and the
data. If ``return_X_y`` is True, then ``(data, target)`` will be pandas
DataFrames or Series as describe above.
If `as_frame` is 'auto', the data and target will be converted to
DataFrame or Series as if `as_frame` is set to True, unless the dataset
is stored in sparse format.
If `as_frame` is False, the data and target will be NumPy arrays and
the `data` will only contain numerical values when `parser="liac-arff"`
where the categories are provided in the attribute `categories` of the
`Bunch` instance. When `parser="pandas"`, no ordinal encoding is made.
.. versionchanged:: 0.24
The default value of `as_frame` changed from `False` to `'auto'`
in 0.24.
n_retries : int, default=3
Number of retries when HTTP errors or network timeouts are encountered.
Error with status code 412 won't be retried as they represent OpenML
generic errors.
delay : float, default=1.0
Number of seconds between retries.
parser : {"auto", "pandas", "liac-arff"}, default="liac-arff"
Parser used to load the ARFF file. Two parsers are implemented:
- `"pandas"`: this is the most efficient parser. However, it requires
pandas to be installed and can only open dense datasets.
- `"liac-arff"`: this is a pure Python ARFF parser that is much less
memory- and CPU-efficient. It deals with sparse ARFF dataset.
If `"auto"` (future default), the parser is chosen automatically such that
`"liac-arff"` is selected for sparse ARFF datasets, otherwise
`"pandas"` is selected.
.. versionadded:: 1.2
.. versionchanged:: 1.4
The default value of `parser` will change from `"liac-arff"` to
`"auto"` in 1.4. You can set `parser="auto"` to silence this
warning. Therefore, an `ImportError` will be raised from 1.4 if
the dataset is dense and pandas is not installed.
Returns
-------
data : :class:`~sklearn.utils.Bunch`
Dictionary-like object, with the following attributes.
data : np.array, scipy.sparse.csr_matrix of floats, or pandas DataFrame
The feature matrix. Categorical features are encoded as ordinals.
target : np.array, pandas Series or DataFrame
The regression target or classification labels, if applicable.
Dtype is float if numeric, and object if categorical. If
``as_frame`` is True, ``target`` is a pandas object.
DESCR : str
The full description of the dataset.
feature_names : list
The names of the dataset columns.
target_names: list
The names of the target columns.
.. versionadded:: 0.22
categories : dict or None
Maps each categorical feature name to a list of values, such
that the value encoded as i is ith in the list. If ``as_frame``
is True, this is None.
details : dict
More metadata from OpenML.
frame : pandas DataFrame
Only present when `as_frame=True`. DataFrame with ``data`` and
``target``.
(data, target) : tuple if ``return_X_y`` is True
.. note:: EXPERIMENTAL
This interface is **experimental** and subsequent releases may
change attributes without notice (although there should only be
minor changes to ``data`` and ``target``).
Missing values in the 'data' are represented as NaN's. Missing values
in 'target' are represented as NaN's (numerical target) or None
(categorical target).
Notes
-----
The `"pandas"` and `"liac-arff"` parsers can lead to different data types
in the output. The notable differences are the following:
- The `"liac-arff"` parser always encodes categorical features as `str` objects.
To the contrary, the `"pandas"` parser instead infers the type while
reading and numerical categories will be casted into integers whenever
possible.
- The `"liac-arff"` parser uses float64 to encode numerical features
tagged as 'REAL' and 'NUMERICAL' in the metadata. The `"pandas"`
parser instead infers if these numerical features corresponds
to integers and uses panda's Integer extension dtype.
- In particular, classification datasets with integer categories are
typically loaded as such `(0, 1, ...)` with the `"pandas"` parser while
`"liac-arff"` will force the use of string encoded class labels such as
`"0"`, `"1"` and so on.
- The `"pandas"` parser will not strip single quotes - i.e. `'` - from
string columns. For instance, a string `'my string'` will be kept as is
while the `"liac-arff"` parser will strip the single quotes. For
categorical columns, the single quotes are stripped from the values.
In addition, when `as_frame=False` is used, the `"liac-arff"` parser
returns ordinally encoded data where the categories are provided in the
attribute `categories` of the `Bunch` instance. Instead, `"pandas"` returns
a NumPy array were the categories are not encoded.
"""
if cache is False:
# no caching will be applied
data_home = None
else:
data_home = get_data_home(data_home=data_home)
data_home = join(data_home, "openml")
# check valid function arguments. data_id XOR (name, version) should be
# provided
if name is not None:
# OpenML is case-insensitive, but the caching mechanism is not
# convert all data names (str) to lower case
name = name.lower()
if data_id is not None:
raise ValueError(
"Dataset data_id={} and name={} passed, but you can only "
"specify a numeric data_id or a name, not "
"both.".format(data_id, name)
)
data_info = _get_data_info_by_name(
name, version, data_home, n_retries=n_retries, delay=delay
)
data_id = data_info["did"]
elif data_id is not None:
# from the previous if statement, it is given that name is None
if version != "active":
raise ValueError(
"Dataset data_id={} and version={} passed, but you can only "
"specify a numeric data_id or a version, not "
"both.".format(data_id, version)
)
else:
raise ValueError(
"Neither name nor data_id are provided. Please provide name or data_id."
)
data_description = _get_data_description_by_id(data_id, data_home)
if data_description["status"] != "active":
warn(
"Version {} of dataset {} is inactive, meaning that issues have "
"been found in the dataset. Try using a newer version from "
"this URL: {}".format(
data_description["version"],
data_description["name"],
data_description["url"],
)
)
if "error" in data_description:
warn(
"OpenML registered a problem with the dataset. It might be "
"unusable. Error: {}".format(data_description["error"])
)
if "warning" in data_description:
warn(
"OpenML raised a warning on the dataset. It might be "
"unusable. Warning: {}".format(data_description["warning"])
)
# TODO(1.4): remove "warn" from the valid parser
valid_parsers = ("auto", "pandas", "liac-arff", "warn")
if parser not in valid_parsers:
raise ValueError(
f"`parser` must be one of {', '.join(repr(p) for p in valid_parsers)}. Got"
f" {parser!r} instead."
)
if parser == "warn":
# TODO(1.4): remove this warning
parser = "liac-arff"
warn(
"The default value of `parser` will change from `'liac-arff'` to "
"`'auto'` in 1.4. You can set `parser='auto'` to silence this "
"warning. Therefore, an `ImportError` will be raised from 1.4 if "
"the dataset is dense and pandas is not installed. Note that the pandas "
"parser may return different data types. See the Notes Section in "
"fetch_openml's API doc for details.",
FutureWarning,
)
if as_frame not in ("auto", True, False):
raise ValueError(
f"`as_frame` must be one of 'auto', True, or False. Got {as_frame} instead."
)
return_sparse = data_description["format"].lower() == "sparse_arff"
as_frame = not return_sparse if as_frame == "auto" else as_frame
if parser == "auto":
parser_ = "liac-arff" if return_sparse else "pandas"
else:
parser_ = parser
if as_frame or parser_ == "pandas":
try:
check_pandas_support("`fetch_openml`")
except ImportError as exc:
if as_frame:
err_msg = (
"Returning pandas objects requires pandas to be installed. "
"Alternatively, explicitely set `as_frame=False` and "
"`parser='liac-arff'`."
)
raise ImportError(err_msg) from exc
else:
err_msg = (
f"Using `parser={parser_!r}` requires pandas to be installed. "
"Alternatively, explicitely set `parser='liac-arff'`."
)
if parser == "auto":
# TODO(1.4): In version 1.4, we will raise an error instead of
# a warning.
warn(
"From version 1.4, `parser='auto'` with `as_frame=False` "
"will use pandas. Either install pandas or set explicitely "
"`parser='liac-arff'` to preserve the current behavior.",
FutureWarning,
)
parser_ = "liac-arff"
else:
raise ImportError(err_msg) from exc
if return_sparse:
if as_frame:
raise ValueError(
"Sparse ARFF datasets cannot be loaded with as_frame=True. "
"Use as_frame=False or as_frame='auto' instead."
)
if parser_ == "pandas":
raise ValueError(
f"Sparse ARFF datasets cannot be loaded with parser={parser!r}. "
"Use parser='liac-arff' or parser='auto' instead."
)
# download data features, meta-info about column types
features_list = _get_data_features(data_id, data_home)
if not as_frame:
for feature in features_list:
if "true" in (feature["is_ignore"], feature["is_row_identifier"]):
continue
if feature["data_type"] == "string":
raise ValueError(
"STRING attributes are not supported for "
"array representation. Try as_frame=True"
)
if target_column == "default-target":
# determines the default target based on the data feature results
# (which is currently more reliable than the data description;
# see issue: https://github.com/openml/OpenML/issues/768)
target_columns = [
feature["name"]
for feature in features_list
if feature["is_target"] == "true"
]
elif isinstance(target_column, str):
# for code-simplicity, make target_column by default a list
target_columns = [target_column]
elif target_column is None:
target_columns = []
elif isinstance(target_column, list):
target_columns = target_column
else:
raise TypeError(
"Did not recognize type of target_column"
"Should be str, list or None. Got: "
"{}".format(type(target_column))
)
data_columns = _valid_data_column_names(features_list, target_columns)
shape: Optional[Tuple[int, int]]
# determine arff encoding to return
if not return_sparse:
# The shape must include the ignored features to keep the right indexes
# during the arff data conversion.
data_qualities = _get_data_qualities(data_id, data_home)
shape = _get_num_samples(data_qualities), len(features_list)
else:
shape = None
# obtain the data
url = _DATA_FILE.format(data_description["file_id"])
bunch = _download_data_to_bunch(
url,
return_sparse,
data_home,
as_frame=bool(as_frame),
openml_columns_info=features_list,
shape=shape,
target_columns=target_columns,
data_columns=data_columns,
md5_checksum=data_description["md5_checksum"],
n_retries=n_retries,
delay=delay,
parser=parser_,
)
if return_X_y:
return bunch.data, bunch.target
description = "{}\n\nDownloaded from openml.org.".format(
data_description.pop("description")
)
bunch.update(
DESCR=description,
details=data_description,
url="https://www.openml.org/d/{}".format(data_id),
)
return bunch
| bsd-3-clause | 7517a70ea2cb757a3a1b030492f7612b | 34.968284 | 88 | 0.606022 | 4.059164 | false | false | false | false |
scikit-learn/scikit-learn | sklearn/inspection/_plot/partial_dependence.py | 8 | 51095 | import numbers
import warnings
from itertools import chain
from math import ceil
import numpy as np
from scipy import sparse
from scipy.stats.mstats import mquantiles
from joblib import Parallel
from .. import partial_dependence
from ...base import is_regressor
from ...utils import Bunch
from ...utils import check_array
from ...utils import check_matplotlib_support # noqa
from ...utils import check_random_state
from ...utils import _safe_indexing
from ...utils.fixes import delayed
class PartialDependenceDisplay:
"""Partial Dependence Plot (PDP).
This can also display individual partial dependencies which are often
referred to as: Individual Condition Expectation (ICE).
It is recommended to use
:func:`~sklearn.inspection.PartialDependenceDisplay.from_estimator` to create a
:class:`~sklearn.inspection.PartialDependenceDisplay`. All parameters are
stored as attributes.
Read more in
:ref:`sphx_glr_auto_examples_miscellaneous_plot_partial_dependence_visualization_api.py`
and the :ref:`User Guide <partial_dependence>`.
.. versionadded:: 0.22
Parameters
----------
pd_results : list of Bunch
Results of :func:`~sklearn.inspection.partial_dependence` for
``features``.
features : list of (int,) or list of (int, int)
Indices of features for a given plot. A tuple of one integer will plot
a partial dependence curve of one feature. A tuple of two integers will
plot a two-way partial dependence curve as a contour plot.
feature_names : list of str
Feature names corresponding to the indices in ``features``.
target_idx : int
- In a multiclass setting, specifies the class for which the PDPs
should be computed. Note that for binary classification, the
positive class (index 1) is always used.
- In a multioutput setting, specifies the task for which the PDPs
should be computed.
Ignored in binary classification or classical regression settings.
deciles : dict
Deciles for feature indices in ``features``.
pdp_lim : dict or None
Global min and max average predictions, such that all plots will have
the same scale and y limits. `pdp_lim[1]` is the global min and max for
single partial dependence curves. `pdp_lim[2]` is the global min and
max for two-way partial dependence curves. If `None`, the limit will be
inferred from the global minimum and maximum of all predictions.
.. deprecated:: 1.1
Pass the parameter `pdp_lim` to
:meth:`~sklearn.inspection.PartialDependenceDisplay.plot` instead.
It will be removed in 1.3.
kind : {'average', 'individual', 'both'} or list of such str, \
default='average'
Whether to plot the partial dependence averaged across all the samples
in the dataset or one line per sample or both.
- ``kind='average'`` results in the traditional PD plot;
- ``kind='individual'`` results in the ICE plot;
- ``kind='both'`` results in plotting both the ICE and PD on the same
plot.
A list of such strings can be provided to specify `kind` on a per-plot
basis. The length of the list should be the same as the number of
interaction requested in `features`.
.. note::
ICE ('individual' or 'both') is not a valid option for 2-ways
interactions plot. As a result, an error will be raised.
2-ways interaction plots should always be configured to
use the 'average' kind instead.
.. note::
The fast ``method='recursion'`` option is only available for
``kind='average'``. Plotting individual dependencies requires using
the slower ``method='brute'`` option.
.. versionadded:: 0.24
Add `kind` parameter with `'average'`, `'individual'`, and `'both'`
options.
.. versionadded:: 1.1
Add the possibility to pass a list of string specifying `kind`
for each plot.
subsample : float, int or None, default=1000
Sampling for ICE curves when `kind` is 'individual' or 'both'.
If float, should be between 0.0 and 1.0 and represent the proportion
of the dataset to be used to plot ICE curves. If int, represents the
maximum absolute number of samples to use.
Note that the full dataset is still used to calculate partial
dependence when `kind='both'`.
.. versionadded:: 0.24
random_state : int, RandomState instance or None, default=None
Controls the randomness of the selected samples when subsamples is not
`None`. See :term:`Glossary <random_state>` for details.
.. versionadded:: 0.24
Attributes
----------
bounding_ax_ : matplotlib Axes or None
If `ax` is an axes or None, the `bounding_ax_` is the axes where the
grid of partial dependence plots are drawn. If `ax` is a list of axes
or a numpy array of axes, `bounding_ax_` is None.
axes_ : ndarray of matplotlib Axes
If `ax` is an axes or None, `axes_[i, j]` is the axes on the i-th row
and j-th column. If `ax` is a list of axes, `axes_[i]` is the i-th item
in `ax`. Elements that are None correspond to a nonexisting axes in
that position.
lines_ : ndarray of matplotlib Artists
If `ax` is an axes or None, `lines_[i, j]` is the partial dependence
curve on the i-th row and j-th column. If `ax` is a list of axes,
`lines_[i]` is the partial dependence curve corresponding to the i-th
item in `ax`. Elements that are None correspond to a nonexisting axes
or an axes that does not include a line plot.
deciles_vlines_ : ndarray of matplotlib LineCollection
If `ax` is an axes or None, `vlines_[i, j]` is the line collection
representing the x axis deciles of the i-th row and j-th column. If
`ax` is a list of axes, `vlines_[i]` corresponds to the i-th item in
`ax`. Elements that are None correspond to a nonexisting axes or an
axes that does not include a PDP plot.
.. versionadded:: 0.23
deciles_hlines_ : ndarray of matplotlib LineCollection
If `ax` is an axes or None, `vlines_[i, j]` is the line collection
representing the y axis deciles of the i-th row and j-th column. If
`ax` is a list of axes, `vlines_[i]` corresponds to the i-th item in
`ax`. Elements that are None correspond to a nonexisting axes or an
axes that does not include a 2-way plot.
.. versionadded:: 0.23
contours_ : ndarray of matplotlib Artists
If `ax` is an axes or None, `contours_[i, j]` is the partial dependence
plot on the i-th row and j-th column. If `ax` is a list of axes,
`contours_[i]` is the partial dependence plot corresponding to the i-th
item in `ax`. Elements that are None correspond to a nonexisting axes
or an axes that does not include a contour plot.
figure_ : matplotlib Figure
Figure containing partial dependence plots.
See Also
--------
partial_dependence : Compute Partial Dependence values.
PartialDependenceDisplay.from_estimator : Plot Partial Dependence.
Examples
--------
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from sklearn.datasets import make_friedman1
>>> from sklearn.ensemble import GradientBoostingRegressor
>>> from sklearn.inspection import PartialDependenceDisplay
>>> from sklearn.inspection import partial_dependence
>>> X, y = make_friedman1()
>>> clf = GradientBoostingRegressor(n_estimators=10).fit(X, y)
>>> features, feature_names = [(0,)], [f"Features #{i}" for i in range(X.shape[1])]
>>> deciles = {0: np.linspace(0, 1, num=5)}
>>> pd_results = partial_dependence(
... clf, X, features=0, kind="average", grid_resolution=5)
>>> display = PartialDependenceDisplay(
... [pd_results], features=features, feature_names=feature_names,
... target_idx=0, deciles=deciles
... )
>>> display.plot(pdp_lim={1: (-1.38, 0.66)})
<...>
>>> plt.show()
"""
def __init__(
self,
pd_results,
*,
features,
feature_names,
target_idx,
deciles,
pdp_lim="deprecated",
kind="average",
subsample=1000,
random_state=None,
):
self.pd_results = pd_results
self.features = features
self.feature_names = feature_names
self.target_idx = target_idx
self.pdp_lim = pdp_lim
self.deciles = deciles
self.kind = kind
self.subsample = subsample
self.random_state = random_state
@classmethod
def from_estimator(
cls,
estimator,
X,
features,
*,
feature_names=None,
target=None,
response_method="auto",
n_cols=3,
grid_resolution=100,
percentiles=(0.05, 0.95),
method="auto",
n_jobs=None,
verbose=0,
line_kw=None,
ice_lines_kw=None,
pd_line_kw=None,
contour_kw=None,
ax=None,
kind="average",
centered=False,
subsample=1000,
random_state=None,
):
"""Partial dependence (PD) and individual conditional expectation (ICE) plots.
Partial dependence plots, individual conditional expectation plots or an
overlay of both of them can be plotted by setting the ``kind``
parameter. The ``len(features)`` plots are arranged in a grid with
``n_cols`` columns. Two-way partial dependence plots are plotted as
contour plots. The deciles of the feature values will be shown with tick
marks on the x-axes for one-way plots, and on both axes for two-way
plots.
Read more in the :ref:`User Guide <partial_dependence>`.
.. note::
:func:`PartialDependenceDisplay.from_estimator` does not support using the
same axes with multiple calls. To plot the partial dependence for
multiple estimators, please pass the axes created by the first call to the
second call::
>>> from sklearn.inspection import PartialDependenceDisplay
>>> from sklearn.datasets import make_friedman1
>>> from sklearn.linear_model import LinearRegression
>>> from sklearn.ensemble import RandomForestRegressor
>>> X, y = make_friedman1()
>>> est1 = LinearRegression().fit(X, y)
>>> est2 = RandomForestRegressor().fit(X, y)
>>> disp1 = PartialDependenceDisplay.from_estimator(est1, X,
... [1, 2])
>>> disp2 = PartialDependenceDisplay.from_estimator(est2, X, [1, 2],
... ax=disp1.axes_)
.. warning::
For :class:`~sklearn.ensemble.GradientBoostingClassifier` and
:class:`~sklearn.ensemble.GradientBoostingRegressor`, the
`'recursion'` method (used by default) will not account for the `init`
predictor of the boosting process. In practice, this will produce
the same values as `'brute'` up to a constant offset in the target
response, provided that `init` is a constant estimator (which is the
default). However, if `init` is not a constant estimator, the
partial dependence values are incorrect for `'recursion'` because the
offset will be sample-dependent. It is preferable to use the `'brute'`
method. Note that this only applies to
:class:`~sklearn.ensemble.GradientBoostingClassifier` and
:class:`~sklearn.ensemble.GradientBoostingRegressor`, not to
:class:`~sklearn.ensemble.HistGradientBoostingClassifier` and
:class:`~sklearn.ensemble.HistGradientBoostingRegressor`.
.. versionadded:: 1.0
Parameters
----------
estimator : BaseEstimator
A fitted estimator object implementing :term:`predict`,
:term:`predict_proba`, or :term:`decision_function`.
Multioutput-multiclass classifiers are not supported.
X : {array-like, dataframe} of shape (n_samples, n_features)
``X`` is used to generate a grid of values for the target
``features`` (where the partial dependence will be evaluated), and
also to generate values for the complement features when the
`method` is `'brute'`.
features : list of {int, str, pair of int, pair of str}
The target features for which to create the PDPs.
If `features[i]` is an integer or a string, a one-way PDP is created;
if `features[i]` is a tuple, a two-way PDP is created (only supported
with `kind='average'`). Each tuple must be of size 2.
if any entry is a string, then it must be in ``feature_names``.
feature_names : array-like of shape (n_features,), dtype=str, default=None
Name of each feature; `feature_names[i]` holds the name of the feature
with index `i`.
By default, the name of the feature corresponds to their numerical
index for NumPy array and their column name for pandas dataframe.
target : int, default=None
- In a multiclass setting, specifies the class for which the PDPs
should be computed. Note that for binary classification, the
positive class (index 1) is always used.
- In a multioutput setting, specifies the task for which the PDPs
should be computed.
Ignored in binary classification or classical regression settings.
response_method : {'auto', 'predict_proba', 'decision_function'}, \
default='auto'
Specifies whether to use :term:`predict_proba` or
:term:`decision_function` as the target response. For regressors
this parameter is ignored and the response is always the output of
:term:`predict`. By default, :term:`predict_proba` is tried first
and we revert to :term:`decision_function` if it doesn't exist. If
``method`` is `'recursion'`, the response is always the output of
:term:`decision_function`.
n_cols : int, default=3
The maximum number of columns in the grid plot. Only active when `ax`
is a single axis or `None`.
grid_resolution : int, default=100
The number of equally spaced points on the axes of the plots, for each
target feature.
percentiles : tuple of float, default=(0.05, 0.95)
The lower and upper percentile used to create the extreme values
for the PDP axes. Must be in [0, 1].
method : str, default='auto'
The method used to calculate the averaged predictions:
- `'recursion'` is only supported for some tree-based estimators
(namely
:class:`~sklearn.ensemble.GradientBoostingClassifier`,
:class:`~sklearn.ensemble.GradientBoostingRegressor`,
:class:`~sklearn.ensemble.HistGradientBoostingClassifier`,
:class:`~sklearn.ensemble.HistGradientBoostingRegressor`,
:class:`~sklearn.tree.DecisionTreeRegressor`,
:class:`~sklearn.ensemble.RandomForestRegressor`
but is more efficient in terms of speed.
With this method, the target response of a
classifier is always the decision function, not the predicted
probabilities. Since the `'recursion'` method implicitly computes
the average of the ICEs by design, it is not compatible with ICE and
thus `kind` must be `'average'`.
- `'brute'` is supported for any estimator, but is more
computationally intensive.
- `'auto'`: the `'recursion'` is used for estimators that support it,
and `'brute'` is used otherwise.
Please see :ref:`this note <pdp_method_differences>` for
differences between the `'brute'` and `'recursion'` method.
n_jobs : int, default=None
The number of CPUs to use to compute the partial dependences.
Computation is parallelized over features specified by the `features`
parameter.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
verbose : int, default=0
Verbose output during PD computations.
line_kw : dict, default=None
Dict with keywords passed to the ``matplotlib.pyplot.plot`` call.
For one-way partial dependence plots. It can be used to define common
properties for both `ice_lines_kw` and `pdp_line_kw`.
ice_lines_kw : dict, default=None
Dictionary with keywords passed to the `matplotlib.pyplot.plot` call.
For ICE lines in the one-way partial dependence plots.
The key value pairs defined in `ice_lines_kw` takes priority over
`line_kw`.
pd_line_kw : dict, default=None
Dictionary with keywords passed to the `matplotlib.pyplot.plot` call.
For partial dependence in one-way partial dependence plots.
The key value pairs defined in `pd_line_kw` takes priority over
`line_kw`.
contour_kw : dict, default=None
Dict with keywords passed to the ``matplotlib.pyplot.contourf`` call.
For two-way partial dependence plots.
ax : Matplotlib axes or array-like of Matplotlib axes, default=None
- If a single axis is passed in, it is treated as a bounding axes
and a grid of partial dependence plots will be drawn within
these bounds. The `n_cols` parameter controls the number of
columns in the grid.
- If an array-like of axes are passed in, the partial dependence
plots will be drawn directly into these axes.
- If `None`, a figure and a bounding axes is created and treated
as the single axes case.
kind : {'average', 'individual', 'both'}, default='average'
Whether to plot the partial dependence averaged across all the samples
in the dataset or one line per sample or both.
- ``kind='average'`` results in the traditional PD plot;
- ``kind='individual'`` results in the ICE plot.
Note that the fast ``method='recursion'`` option is only available for
``kind='average'``. Plotting individual dependencies requires using the
slower ``method='brute'`` option.
centered : bool, default=False
If `True`, the ICE and PD lines will start at the origin of the
y-axis. By default, no centering is done.
.. versionadded:: 1.1
subsample : float, int or None, default=1000
Sampling for ICE curves when `kind` is 'individual' or 'both'.
If `float`, should be between 0.0 and 1.0 and represent the proportion
of the dataset to be used to plot ICE curves. If `int`, represents the
absolute number samples to use.
Note that the full dataset is still used to calculate averaged partial
dependence when `kind='both'`.
random_state : int, RandomState instance or None, default=None
Controls the randomness of the selected samples when subsamples is not
`None` and `kind` is either `'both'` or `'individual'`.
See :term:`Glossary <random_state>` for details.
Returns
-------
display : :class:`~sklearn.inspection.PartialDependenceDisplay`
See Also
--------
partial_dependence : Compute Partial Dependence values.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from sklearn.datasets import make_friedman1
>>> from sklearn.ensemble import GradientBoostingRegressor
>>> from sklearn.inspection import PartialDependenceDisplay
>>> X, y = make_friedman1()
>>> clf = GradientBoostingRegressor(n_estimators=10).fit(X, y)
>>> PartialDependenceDisplay.from_estimator(clf, X, [0, (0, 1)])
<...>
>>> plt.show()
"""
check_matplotlib_support(f"{cls.__name__}.from_estimator") # noqa
import matplotlib.pyplot as plt # noqa
# set target_idx for multi-class estimators
if hasattr(estimator, "classes_") and np.size(estimator.classes_) > 2:
if target is None:
raise ValueError("target must be specified for multi-class")
target_idx = np.searchsorted(estimator.classes_, target)
if (
not (0 <= target_idx < len(estimator.classes_))
or estimator.classes_[target_idx] != target
):
raise ValueError("target not in est.classes_, got {}".format(target))
else:
# regression and binary classification
target_idx = 0
# Use check_array only on lists and other non-array-likes / sparse. Do not
# convert DataFrame into a NumPy array.
if not (hasattr(X, "__array__") or sparse.issparse(X)):
X = check_array(X, force_all_finite="allow-nan", dtype=object)
n_features = X.shape[1]
# convert feature_names to list
if feature_names is None:
if hasattr(X, "loc"):
# get the column names for a pandas dataframe
feature_names = X.columns.tolist()
else:
# define a list of numbered indices for a numpy array
feature_names = [str(i) for i in range(n_features)]
elif hasattr(feature_names, "tolist"):
# convert numpy array or pandas index to a list
feature_names = feature_names.tolist()
if len(set(feature_names)) != len(feature_names):
raise ValueError("feature_names should not contain duplicates.")
# expand kind to always be a list of str
kind_ = [kind] * len(features) if isinstance(kind, str) else kind
if len(kind_) != len(features):
raise ValueError(
"When `kind` is provided as a list of strings, it should contain "
f"as many elements as `features`. `kind` contains {len(kind_)} "
f"element(s) and `features` contains {len(features)} element(s)."
)
def convert_feature(fx):
if isinstance(fx, str):
try:
fx = feature_names.index(fx)
except ValueError as e:
raise ValueError("Feature %s not in feature_names" % fx) from e
return int(fx)
# convert features into a seq of int tuples
tmp_features, ice_for_two_way_pd = [], []
for kind_plot, fxs in zip(kind_, features):
if isinstance(fxs, (numbers.Integral, str)):
fxs = (fxs,)
try:
fxs = tuple(convert_feature(fx) for fx in fxs)
except TypeError as e:
raise ValueError(
"Each entry in features must be either an int, "
"a string, or an iterable of size at most 2."
) from e
if not 1 <= np.size(fxs) <= 2:
raise ValueError(
"Each entry in features must be either an int, "
"a string, or an iterable of size at most 2."
)
# store the information if 2-way PD was requested with ICE to later
# raise a ValueError with an exhaustive list of problematic
# settings.
ice_for_two_way_pd.append(kind_plot != "average" and np.size(fxs) > 1)
tmp_features.append(fxs)
if any(ice_for_two_way_pd):
# raise an error an be specific regarding the parameter values
# when 1- and 2-way PD were requested
kind_ = [
"average" if forcing_average else kind_plot
for forcing_average, kind_plot in zip(ice_for_two_way_pd, kind_)
]
raise ValueError(
"ICE plot cannot be rendered for 2-way feature interactions. "
"2-way feature interactions mandates PD plots using the "
"'average' kind: "
f"features={features!r} should be configured to use "
f"kind={kind_!r} explicitly."
)
features = tmp_features
# Early exit if the axes does not have the correct number of axes
if ax is not None and not isinstance(ax, plt.Axes):
axes = np.asarray(ax, dtype=object)
if axes.size != len(features):
raise ValueError(
"Expected ax to have {} axes, got {}".format(
len(features), axes.size
)
)
for i in chain.from_iterable(features):
if i >= len(feature_names):
raise ValueError(
"All entries of features must be less than "
"len(feature_names) = {0}, got {1}.".format(len(feature_names), i)
)
if isinstance(subsample, numbers.Integral):
if subsample <= 0:
raise ValueError(
f"When an integer, subsample={subsample} should be positive."
)
elif isinstance(subsample, numbers.Real):
if subsample <= 0 or subsample >= 1:
raise ValueError(
f"When a floating-point, subsample={subsample} should be in "
"the (0, 1) range."
)
# compute predictions and/or averaged predictions
pd_results = Parallel(n_jobs=n_jobs, verbose=verbose)(
delayed(partial_dependence)(
estimator,
X,
fxs,
response_method=response_method,
method=method,
grid_resolution=grid_resolution,
percentiles=percentiles,
kind=kind_plot,
)
for kind_plot, fxs in zip(kind_, features)
)
# For multioutput regression, we can only check the validity of target
# now that we have the predictions.
# Also note: as multiclass-multioutput classifiers are not supported,
# multiclass and multioutput scenario are mutually exclusive. So there is
# no risk of overwriting target_idx here.
pd_result = pd_results[0] # checking the first result is enough
n_tasks = (
pd_result.average.shape[0]
if kind_[0] == "average"
else pd_result.individual.shape[0]
)
if is_regressor(estimator) and n_tasks > 1:
if target is None:
raise ValueError("target must be specified for multi-output regressors")
if not 0 <= target <= n_tasks:
raise ValueError(
"target must be in [0, n_tasks], got {}.".format(target)
)
target_idx = target
deciles = {}
for fx in chain.from_iterable(features):
if fx not in deciles:
X_col = _safe_indexing(X, fx, axis=1)
deciles[fx] = mquantiles(X_col, prob=np.arange(0.1, 1.0, 0.1))
display = PartialDependenceDisplay(
pd_results=pd_results,
features=features,
feature_names=feature_names,
target_idx=target_idx,
deciles=deciles,
kind=kind,
subsample=subsample,
random_state=random_state,
)
return display.plot(
ax=ax,
n_cols=n_cols,
line_kw=line_kw,
ice_lines_kw=ice_lines_kw,
pd_line_kw=pd_line_kw,
contour_kw=contour_kw,
centered=centered,
)
def _get_sample_count(self, n_samples):
"""Compute the number of samples as an integer."""
if isinstance(self.subsample, numbers.Integral):
if self.subsample < n_samples:
return self.subsample
return n_samples
elif isinstance(self.subsample, numbers.Real):
return ceil(n_samples * self.subsample)
return n_samples
def _plot_ice_lines(
self,
preds,
feature_values,
n_ice_to_plot,
ax,
pd_plot_idx,
n_total_lines_by_plot,
individual_line_kw,
):
"""Plot the ICE lines.
Parameters
----------
preds : ndarray of shape \
(n_instances, n_grid_points)
The predictions computed for all points of `feature_values` for a
given feature for all samples in `X`.
feature_values : ndarray of shape (n_grid_points,)
The feature values for which the predictions have been computed.
n_ice_to_plot : int
The number of ICE lines to plot.
ax : Matplotlib axes
The axis on which to plot the ICE lines.
pd_plot_idx : int
The sequential index of the plot. It will be unraveled to find the
matching 2D position in the grid layout.
n_total_lines_by_plot : int
The total number of lines expected to be plot on the axis.
individual_line_kw : dict
Dict with keywords passed when plotting the ICE lines.
"""
rng = check_random_state(self.random_state)
# subsample ice
ice_lines_idx = rng.choice(
preds.shape[0],
n_ice_to_plot,
replace=False,
)
ice_lines_subsampled = preds[ice_lines_idx, :]
# plot the subsampled ice
for ice_idx, ice in enumerate(ice_lines_subsampled):
line_idx = np.unravel_index(
pd_plot_idx * n_total_lines_by_plot + ice_idx, self.lines_.shape
)
self.lines_[line_idx] = ax.plot(
feature_values, ice.ravel(), **individual_line_kw
)[0]
def _plot_average_dependence(
self,
avg_preds,
feature_values,
ax,
pd_line_idx,
line_kw,
):
"""Plot the average partial dependence.
Parameters
----------
avg_preds : ndarray of shape (n_grid_points,)
The average predictions for all points of `feature_values` for a
given feature for all samples in `X`.
feature_values : ndarray of shape (n_grid_points,)
The feature values for which the predictions have been computed.
ax : Matplotlib axes
The axis on which to plot the average PD.
pd_line_idx : int
The sequential index of the plot. It will be unraveled to find the
matching 2D position in the grid layout.
line_kw : dict
Dict with keywords passed when plotting the PD plot.
centered : bool
Whether or not to center the average PD to start at the origin.
"""
line_idx = np.unravel_index(pd_line_idx, self.lines_.shape)
self.lines_[line_idx] = ax.plot(
feature_values,
avg_preds,
**line_kw,
)[0]
def _plot_one_way_partial_dependence(
self,
kind,
preds,
avg_preds,
feature_values,
feature_idx,
n_ice_lines,
ax,
n_cols,
pd_plot_idx,
n_lines,
ice_lines_kw,
pd_line_kw,
pdp_lim,
):
"""Plot 1-way partial dependence: ICE and PDP.
Parameters
----------
kind : str
The kind of partial plot to draw.
preds : ndarray of shape \
(n_instances, n_grid_points) or None
The predictions computed for all points of `feature_values` for a
given feature for all samples in `X`.
avg_preds : ndarray of shape (n_grid_points,)
The average predictions for all points of `feature_values` for a
given feature for all samples in `X`.
feature_values : ndarray of shape (n_grid_points,)
The feature values for which the predictions have been computed.
feature_idx : int
The index corresponding to the target feature.
n_ice_lines : int
The number of ICE lines to plot.
ax : Matplotlib axes
The axis on which to plot the ICE and PDP lines.
n_cols : int or None
The number of column in the axis.
pd_plot_idx : int
The sequential index of the plot. It will be unraveled to find the
matching 2D position in the grid layout.
n_lines : int
The total number of lines expected to be plot on the axis.
ice_lines_kw : dict
Dict with keywords passed when plotting the ICE lines.
pd_line_kw : dict
Dict with keywords passed when plotting the PD plot.
pdp_lim : dict
Global min and max average predictions, such that all plots will
have the same scale and y limits. `pdp_lim[1]` is the global min
and max for single partial dependence curves.
"""
from matplotlib import transforms # noqa
if kind in ("individual", "both"):
self._plot_ice_lines(
preds[self.target_idx],
feature_values,
n_ice_lines,
ax,
pd_plot_idx,
n_lines,
ice_lines_kw,
)
if kind in ("average", "both"):
# the average is stored as the last line
if kind == "average":
pd_line_idx = pd_plot_idx
else:
pd_line_idx = pd_plot_idx * n_lines + n_ice_lines
self._plot_average_dependence(
avg_preds[self.target_idx].ravel(),
feature_values,
ax,
pd_line_idx,
pd_line_kw,
)
trans = transforms.blended_transform_factory(ax.transData, ax.transAxes)
# create the decile line for the vertical axis
vlines_idx = np.unravel_index(pd_plot_idx, self.deciles_vlines_.shape)
self.deciles_vlines_[vlines_idx] = ax.vlines(
self.deciles[feature_idx[0]],
0,
0.05,
transform=trans,
color="k",
)
# reset ylim which was overwritten by vlines
ax.set_ylim(pdp_lim[1])
# Set xlabel if it is not already set
if not ax.get_xlabel():
ax.set_xlabel(self.feature_names[feature_idx[0]])
if n_cols is None or pd_plot_idx % n_cols == 0:
if not ax.get_ylabel():
ax.set_ylabel("Partial dependence")
else:
ax.set_yticklabels([])
if pd_line_kw.get("label", None) and kind != "individual":
ax.legend()
def _plot_two_way_partial_dependence(
self,
avg_preds,
feature_values,
feature_idx,
ax,
pd_plot_idx,
Z_level,
contour_kw,
):
"""Plot 2-way partial dependence.
Parameters
----------
avg_preds : ndarray of shape \
(n_instances, n_grid_points, n_grid_points)
The average predictions for all points of `feature_values[0]` and
`feature_values[1]` for some given features for all samples in `X`.
feature_values : seq of 1d array
A sequence of array of the feature values for which the predictions
have been computed.
feature_idx : tuple of int
The indices of the target features
ax : Matplotlib axes
The axis on which to plot the ICE and PDP lines.
pd_plot_idx : int
The sequential index of the plot. It will be unraveled to find the
matching 2D position in the grid layout.
Z_level : ndarray of shape (8, 8)
The Z-level used to encode the average predictions.
contour_kw : dict
Dict with keywords passed when plotting the contours.
"""
from matplotlib import transforms # noqa
XX, YY = np.meshgrid(feature_values[0], feature_values[1])
Z = avg_preds[self.target_idx].T
CS = ax.contour(XX, YY, Z, levels=Z_level, linewidths=0.5, colors="k")
contour_idx = np.unravel_index(pd_plot_idx, self.contours_.shape)
self.contours_[contour_idx] = ax.contourf(
XX,
YY,
Z,
levels=Z_level,
vmax=Z_level[-1],
vmin=Z_level[0],
**contour_kw,
)
ax.clabel(CS, fmt="%2.2f", colors="k", fontsize=10, inline=True)
trans = transforms.blended_transform_factory(ax.transData, ax.transAxes)
# create the decile line for the vertical axis
xlim, ylim = ax.get_xlim(), ax.get_ylim()
vlines_idx = np.unravel_index(pd_plot_idx, self.deciles_vlines_.shape)
self.deciles_vlines_[vlines_idx] = ax.vlines(
self.deciles[feature_idx[0]],
0,
0.05,
transform=trans,
color="k",
)
# create the decile line for the horizontal axis
hlines_idx = np.unravel_index(pd_plot_idx, self.deciles_hlines_.shape)
self.deciles_hlines_[hlines_idx] = ax.hlines(
self.deciles[feature_idx[1]],
0,
0.05,
transform=trans,
color="k",
)
# reset xlim and ylim since they are overwritten by hlines and vlines
ax.set_xlim(xlim)
ax.set_ylim(ylim)
# set xlabel if it is not already set
if not ax.get_xlabel():
ax.set_xlabel(self.feature_names[feature_idx[0]])
ax.set_ylabel(self.feature_names[feature_idx[1]])
def plot(
self,
*,
ax=None,
n_cols=3,
line_kw=None,
ice_lines_kw=None,
pd_line_kw=None,
contour_kw=None,
pdp_lim=None,
centered=False,
):
"""Plot partial dependence plots.
Parameters
----------
ax : Matplotlib axes or array-like of Matplotlib axes, default=None
- If a single axis is passed in, it is treated as a bounding axes
and a grid of partial dependence plots will be drawn within
these bounds. The `n_cols` parameter controls the number of
columns in the grid.
- If an array-like of axes are passed in, the partial dependence
plots will be drawn directly into these axes.
- If `None`, a figure and a bounding axes is created and treated
as the single axes case.
n_cols : int, default=3
The maximum number of columns in the grid plot. Only active when
`ax` is a single axes or `None`.
line_kw : dict, default=None
Dict with keywords passed to the `matplotlib.pyplot.plot` call.
For one-way partial dependence plots.
ice_lines_kw : dict, default=None
Dictionary with keywords passed to the `matplotlib.pyplot.plot` call.
For ICE lines in the one-way partial dependence plots.
The key value pairs defined in `ice_lines_kw` takes priority over
`line_kw`.
.. versionadded:: 1.0
pd_line_kw : dict, default=None
Dictionary with keywords passed to the `matplotlib.pyplot.plot` call.
For partial dependence in one-way partial dependence plots.
The key value pairs defined in `pd_line_kw` takes priority over
`line_kw`.
.. versionadded:: 1.0
contour_kw : dict, default=None
Dict with keywords passed to the `matplotlib.pyplot.contourf`
call for two-way partial dependence plots.
pdp_lim : dict, default=None
Global min and max average predictions, such that all plots will have the
same scale and y limits. `pdp_lim[1]` is the global min and max for single
partial dependence curves. `pdp_lim[2]` is the global min and max for
two-way partial dependence curves. If `None` (default), the limit will be
inferred from the global minimum and maximum of all predictions.
.. versionadded:: 1.1
centered : bool, default=False
If `True`, the ICE and PD lines will start at the origin of the
y-axis. By default, no centering is done.
.. versionadded:: 1.1
Returns
-------
display : :class:`~sklearn.inspection.PartialDependenceDisplay`
Returns a :class:`~sklearn.inspection.PartialDependenceDisplay`
object that contains the partial dependence plots.
"""
check_matplotlib_support("plot_partial_dependence")
import matplotlib.pyplot as plt # noqa
from matplotlib.gridspec import GridSpecFromSubplotSpec # noqa
if isinstance(self.kind, str):
kind = [self.kind] * len(self.features)
else:
kind = self.kind
if len(kind) != len(self.features):
raise ValueError(
"When `kind` is provided as a list of strings, it should "
"contain as many elements as `features`. `kind` contains "
f"{len(kind)} element(s) and `features` contains "
f"{len(self.features)} element(s)."
)
valid_kinds = {"average", "individual", "both"}
if any([k not in valid_kinds for k in kind]):
raise ValueError(
f"Values provided to `kind` must be one of: {valid_kinds!r} or a list"
f" of such values. Currently, kind={self.kind!r}"
)
# FIXME: remove in 1.3
if self.pdp_lim != "deprecated":
warnings.warn(
"The `pdp_lim` parameter is deprecated in version 1.1 and will be "
"removed in version 1.3. Provide `pdp_lim` to the `plot` method."
"instead.",
FutureWarning,
)
if pdp_lim is not None and self.pdp_lim != pdp_lim:
warnings.warn(
"`pdp_lim` has been passed in both the constructor and the `plot` "
"method. For backward compatibility, the parameter from the "
"constructor will be used.",
UserWarning,
)
pdp_lim = self.pdp_lim
# Center results before plotting
if not centered:
pd_results_ = self.pd_results
else:
pd_results_ = []
for kind_plot, pd_result in zip(kind, self.pd_results):
current_results = {"values": pd_result["values"]}
if kind_plot in ("individual", "both"):
preds = pd_result.individual
preds = preds - preds[self.target_idx, :, 0, None]
current_results["individual"] = preds
if kind_plot in ("average", "both"):
avg_preds = pd_result.average
avg_preds = avg_preds - avg_preds[self.target_idx, 0, None]
current_results["average"] = avg_preds
pd_results_.append(Bunch(**current_results))
if pdp_lim is None:
# get global min and max average predictions of PD grouped by plot type
pdp_lim = {}
for kind_plot, pdp in zip(kind, pd_results_):
values = pdp["values"]
preds = pdp.average if kind_plot == "average" else pdp.individual
min_pd = preds[self.target_idx].min()
max_pd = preds[self.target_idx].max()
n_fx = len(values)
old_min_pd, old_max_pd = pdp_lim.get(n_fx, (min_pd, max_pd))
min_pd = min(min_pd, old_min_pd)
max_pd = max(max_pd, old_max_pd)
pdp_lim[n_fx] = (min_pd, max_pd)
if line_kw is None:
line_kw = {}
if ice_lines_kw is None:
ice_lines_kw = {}
if pd_line_kw is None:
pd_line_kw = {}
if ax is None:
_, ax = plt.subplots()
if contour_kw is None:
contour_kw = {}
default_contour_kws = {"alpha": 0.75}
contour_kw = {**default_contour_kws, **contour_kw}
n_features = len(self.features)
is_average_plot = [kind_plot == "average" for kind_plot in kind]
if all(is_average_plot):
# only average plots are requested
n_ice_lines = 0
n_lines = 1
else:
# we need to determine the number of ICE samples computed
ice_plot_idx = is_average_plot.index(False)
n_ice_lines = self._get_sample_count(
len(pd_results_[ice_plot_idx].individual[0])
)
if any([kind_plot == "both" for kind_plot in kind]):
n_lines = n_ice_lines + 1 # account for the average line
else:
n_lines = n_ice_lines
if isinstance(ax, plt.Axes):
# If ax was set off, it has most likely been set to off
# by a previous call to plot.
if not ax.axison:
raise ValueError(
"The ax was already used in another plot "
"function, please set ax=display.axes_ "
"instead"
)
ax.set_axis_off()
self.bounding_ax_ = ax
self.figure_ = ax.figure
n_cols = min(n_cols, n_features)
n_rows = int(np.ceil(n_features / float(n_cols)))
self.axes_ = np.empty((n_rows, n_cols), dtype=object)
if all(is_average_plot):
self.lines_ = np.empty((n_rows, n_cols), dtype=object)
else:
self.lines_ = np.empty((n_rows, n_cols, n_lines), dtype=object)
self.contours_ = np.empty((n_rows, n_cols), dtype=object)
axes_ravel = self.axes_.ravel()
gs = GridSpecFromSubplotSpec(
n_rows, n_cols, subplot_spec=ax.get_subplotspec()
)
for i, spec in zip(range(n_features), gs):
axes_ravel[i] = self.figure_.add_subplot(spec)
else: # array-like
ax = np.asarray(ax, dtype=object)
if ax.size != n_features:
raise ValueError(
"Expected ax to have {} axes, got {}".format(n_features, ax.size)
)
if ax.ndim == 2:
n_cols = ax.shape[1]
else:
n_cols = None
self.bounding_ax_ = None
self.figure_ = ax.ravel()[0].figure
self.axes_ = ax
if all(is_average_plot):
self.lines_ = np.empty_like(ax, dtype=object)
else:
self.lines_ = np.empty(ax.shape + (n_lines,), dtype=object)
self.contours_ = np.empty_like(ax, dtype=object)
# create contour levels for two-way plots
if 2 in pdp_lim:
Z_level = np.linspace(*pdp_lim[2], num=8)
self.deciles_vlines_ = np.empty_like(self.axes_, dtype=object)
self.deciles_hlines_ = np.empty_like(self.axes_, dtype=object)
for pd_plot_idx, (axi, feature_idx, pd_result, kind_plot) in enumerate(
zip(self.axes_.ravel(), self.features, pd_results_, kind)
):
avg_preds = None
preds = None
feature_values = pd_result["values"]
if kind_plot == "individual":
preds = pd_result.individual
elif kind_plot == "average":
avg_preds = pd_result.average
else: # kind_plot == 'both'
avg_preds = pd_result.average
preds = pd_result.individual
if len(feature_values) == 1:
# define the line-style for the current plot
default_line_kws = {
"color": "C0",
"label": "average" if kind_plot == "both" else None,
}
if kind_plot == "individual":
default_ice_lines_kws = {"alpha": 0.3, "linewidth": 0.5}
default_pd_lines_kws = {}
elif kind_plot == "both":
# by default, we need to distinguish the average line from
# the individual lines via color and line style
default_ice_lines_kws = {
"alpha": 0.3,
"linewidth": 0.5,
"color": "tab:blue",
}
default_pd_lines_kws = {
"color": "tab:orange",
"linestyle": "--",
}
else:
default_ice_lines_kws = {}
default_pd_lines_kws = {}
ice_lines_kw = {
**default_line_kws,
**default_ice_lines_kws,
**line_kw,
**ice_lines_kw,
}
del ice_lines_kw["label"]
pd_line_kw = {
**default_line_kws,
**default_pd_lines_kws,
**line_kw,
**pd_line_kw,
}
self._plot_one_way_partial_dependence(
kind_plot,
preds,
avg_preds,
feature_values[0],
feature_idx,
n_ice_lines,
axi,
n_cols,
pd_plot_idx,
n_lines,
ice_lines_kw,
pd_line_kw,
pdp_lim,
)
else:
self._plot_two_way_partial_dependence(
avg_preds,
feature_values,
feature_idx,
axi,
pd_plot_idx,
Z_level,
contour_kw,
)
return self
| bsd-3-clause | 5e63e4247da3794104141e1e0b3aebd2 | 39.391304 | 92 | 0.56303 | 4.302737 | false | false | false | false |
scikit-learn/scikit-learn | examples/linear_model/plot_tweedie_regression_insurance_claims.py | 4 | 23583 | """
======================================
Tweedie regression on insurance claims
======================================
This example illustrates the use of Poisson, Gamma and Tweedie regression on
the `French Motor Third-Party Liability Claims dataset
<https://www.openml.org/d/41214>`_, and is inspired by an R tutorial [1]_.
In this dataset, each sample corresponds to an insurance policy, i.e. a
contract within an insurance company and an individual (policyholder).
Available features include driver age, vehicle age, vehicle power, etc.
A few definitions: a *claim* is the request made by a policyholder to the
insurer to compensate for a loss covered by the insurance. The *claim amount*
is the amount of money that the insurer must pay. The *exposure* is the
duration of the insurance coverage of a given policy, in years.
Here our goal is to predict the expected
value, i.e. the mean, of the total claim amount per exposure unit also
referred to as the pure premium.
There are several possibilities to do that, two of which are:
1. Model the number of claims with a Poisson distribution, and the average
claim amount per claim, also known as severity, as a Gamma distribution
and multiply the predictions of both in order to get the total claim
amount.
2. Model the total claim amount per exposure directly, typically with a Tweedie
distribution of Tweedie power :math:`p \\in (1, 2)`.
In this example we will illustrate both approaches. We start by defining a few
helper functions for loading the data and visualizing results.
.. [1] A. Noll, R. Salzmann and M.V. Wuthrich, Case Study: French Motor
Third-Party Liability Claims (November 8, 2018). `doi:10.2139/ssrn.3164764
<http://dx.doi.org/10.2139/ssrn.3164764>`_
"""
# Authors: Christian Lorentzen <lorentzen.ch@gmail.com>
# Roman Yurchak <rth.yurchak@gmail.com>
# Olivier Grisel <olivier.grisel@ensta.org>
# License: BSD 3 clause
# %%
from functools import partial
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import fetch_openml
from sklearn.metrics import mean_tweedie_deviance
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
def load_mtpl2(n_samples=None):
"""Fetch the French Motor Third-Party Liability Claims dataset.
Parameters
----------
n_samples: int, default=None
number of samples to select (for faster run time). Full dataset has
678013 samples.
"""
# freMTPL2freq dataset from https://www.openml.org/d/41214
df_freq = fetch_openml(data_id=41214, as_frame=True, parser="pandas").data
df_freq["IDpol"] = df_freq["IDpol"].astype(int)
df_freq.set_index("IDpol", inplace=True)
# freMTPL2sev dataset from https://www.openml.org/d/41215
df_sev = fetch_openml(data_id=41215, as_frame=True, parser="pandas").data
# sum ClaimAmount over identical IDs
df_sev = df_sev.groupby("IDpol").sum()
df = df_freq.join(df_sev, how="left")
df["ClaimAmount"].fillna(0, inplace=True)
# unquote string fields
for column_name in df.columns[df.dtypes.values == object]:
df[column_name] = df[column_name].str.strip("'")
return df.iloc[:n_samples]
def plot_obs_pred(
df,
feature,
weight,
observed,
predicted,
y_label=None,
title=None,
ax=None,
fill_legend=False,
):
"""Plot observed and predicted - aggregated per feature level.
Parameters
----------
df : DataFrame
input data
feature: str
a column name of df for the feature to be plotted
weight : str
column name of df with the values of weights or exposure
observed : str
a column name of df with the observed target
predicted : DataFrame
a dataframe, with the same index as df, with the predicted target
fill_legend : bool, default=False
whether to show fill_between legend
"""
# aggregate observed and predicted variables by feature level
df_ = df.loc[:, [feature, weight]].copy()
df_["observed"] = df[observed] * df[weight]
df_["predicted"] = predicted * df[weight]
df_ = (
df_.groupby([feature])[[weight, "observed", "predicted"]]
.sum()
.assign(observed=lambda x: x["observed"] / x[weight])
.assign(predicted=lambda x: x["predicted"] / x[weight])
)
ax = df_.loc[:, ["observed", "predicted"]].plot(style=".", ax=ax)
y_max = df_.loc[:, ["observed", "predicted"]].values.max() * 0.8
p2 = ax.fill_between(
df_.index,
0,
y_max * df_[weight] / df_[weight].values.max(),
color="g",
alpha=0.1,
)
if fill_legend:
ax.legend([p2], ["{} distribution".format(feature)])
ax.set(
ylabel=y_label if y_label is not None else None,
title=title if title is not None else "Train: Observed vs Predicted",
)
def score_estimator(
estimator,
X_train,
X_test,
df_train,
df_test,
target,
weights,
tweedie_powers=None,
):
"""Evaluate an estimator on train and test sets with different metrics"""
metrics = [
("D² explained", None), # Use default scorer if it exists
("mean abs. error", mean_absolute_error),
("mean squared error", mean_squared_error),
]
if tweedie_powers:
metrics += [
(
"mean Tweedie dev p={:.4f}".format(power),
partial(mean_tweedie_deviance, power=power),
)
for power in tweedie_powers
]
res = []
for subset_label, X, df in [
("train", X_train, df_train),
("test", X_test, df_test),
]:
y, _weights = df[target], df[weights]
for score_label, metric in metrics:
if isinstance(estimator, tuple) and len(estimator) == 2:
# Score the model consisting of the product of frequency and
# severity models.
est_freq, est_sev = estimator
y_pred = est_freq.predict(X) * est_sev.predict(X)
else:
y_pred = estimator.predict(X)
if metric is None:
if not hasattr(estimator, "score"):
continue
score = estimator.score(X, y, sample_weight=_weights)
else:
score = metric(y, y_pred, sample_weight=_weights)
res.append({"subset": subset_label, "metric": score_label, "score": score})
res = (
pd.DataFrame(res)
.set_index(["metric", "subset"])
.score.unstack(-1)
.round(4)
.loc[:, ["train", "test"]]
)
return res
# %%
# Loading datasets, basic feature extraction and target definitions
# -----------------------------------------------------------------
#
# We construct the freMTPL2 dataset by joining the freMTPL2freq table,
# containing the number of claims (``ClaimNb``), with the freMTPL2sev table,
# containing the claim amount (``ClaimAmount``) for the same policy ids
# (``IDpol``).
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder
from sklearn.preprocessing import StandardScaler, KBinsDiscretizer
from sklearn.compose import ColumnTransformer
df = load_mtpl2()
# Note: filter out claims with zero amount, as the severity model
# requires strictly positive target values.
df.loc[(df["ClaimAmount"] == 0) & (df["ClaimNb"] >= 1), "ClaimNb"] = 0
# Correct for unreasonable observations (that might be data error)
# and a few exceptionally large claim amounts
df["ClaimNb"] = df["ClaimNb"].clip(upper=4)
df["Exposure"] = df["Exposure"].clip(upper=1)
df["ClaimAmount"] = df["ClaimAmount"].clip(upper=200000)
log_scale_transformer = make_pipeline(
FunctionTransformer(func=np.log), StandardScaler()
)
column_trans = ColumnTransformer(
[
(
"binned_numeric",
KBinsDiscretizer(n_bins=10, subsample=int(2e5), random_state=0),
["VehAge", "DrivAge"],
),
(
"onehot_categorical",
OneHotEncoder(),
["VehBrand", "VehPower", "VehGas", "Region", "Area"],
),
("passthrough_numeric", "passthrough", ["BonusMalus"]),
("log_scaled_numeric", log_scale_transformer, ["Density"]),
],
remainder="drop",
)
X = column_trans.fit_transform(df)
# Insurances companies are interested in modeling the Pure Premium, that is
# the expected total claim amount per unit of exposure for each policyholder
# in their portfolio:
df["PurePremium"] = df["ClaimAmount"] / df["Exposure"]
# This can be indirectly approximated by a 2-step modeling: the product of the
# Frequency times the average claim amount per claim:
df["Frequency"] = df["ClaimNb"] / df["Exposure"]
df["AvgClaimAmount"] = df["ClaimAmount"] / np.fmax(df["ClaimNb"], 1)
with pd.option_context("display.max_columns", 15):
print(df[df.ClaimAmount > 0].head())
# %%
#
# Frequency model -- Poisson distribution
# ---------------------------------------
#
# The number of claims (``ClaimNb``) is a positive integer (0 included).
# Thus, this target can be modelled by a Poisson distribution.
# It is then assumed to be the number of discrete events occurring with a
# constant rate in a given time interval (``Exposure``, in units of years).
# Here we model the frequency ``y = ClaimNb / Exposure``, which is still a
# (scaled) Poisson distribution, and use ``Exposure`` as `sample_weight`.
from sklearn.model_selection import train_test_split
from sklearn.linear_model import PoissonRegressor
df_train, df_test, X_train, X_test = train_test_split(df, X, random_state=0)
# %%
#
# Let us keep in mind that despite the seemingly large number of data points in
# this dataset, the number of evaluation points where the claim amount is
# non-zero is quite small:
len(df_test)
# %%
len(df_test[df_test["ClaimAmount"] > 0])
# %%
#
# As a consequence, we expect a significant variability in our
# evaluation upon random resampling of the train test split.
#
# The parameters of the model are estimated by minimizing the Poisson deviance
# on the training set via a Newton solver. Some of the features are collinear
# (e.g. because we did not drop any categorical level in the `OneHotEncoder`),
# we use a weak L2 penalization to avoid numerical issues.
glm_freq = PoissonRegressor(alpha=1e-4, solver="newton-cholesky")
glm_freq.fit(X_train, df_train["Frequency"], sample_weight=df_train["Exposure"])
scores = score_estimator(
glm_freq,
X_train,
X_test,
df_train,
df_test,
target="Frequency",
weights="Exposure",
)
print("Evaluation of PoissonRegressor on target Frequency")
print(scores)
# %%
#
# Note that the score measured on the test set is surprisingly better than on
# the training set. This might be specific to this random train-test split.
# Proper cross-validation could help us to assess the sampling variability of
# these results.
#
# We can visually compare observed and predicted values, aggregated by the
# drivers age (``DrivAge``), vehicle age (``VehAge``) and the insurance
# bonus/malus (``BonusMalus``).
fig, ax = plt.subplots(ncols=2, nrows=2, figsize=(16, 8))
fig.subplots_adjust(hspace=0.3, wspace=0.2)
plot_obs_pred(
df=df_train,
feature="DrivAge",
weight="Exposure",
observed="Frequency",
predicted=glm_freq.predict(X_train),
y_label="Claim Frequency",
title="train data",
ax=ax[0, 0],
)
plot_obs_pred(
df=df_test,
feature="DrivAge",
weight="Exposure",
observed="Frequency",
predicted=glm_freq.predict(X_test),
y_label="Claim Frequency",
title="test data",
ax=ax[0, 1],
fill_legend=True,
)
plot_obs_pred(
df=df_test,
feature="VehAge",
weight="Exposure",
observed="Frequency",
predicted=glm_freq.predict(X_test),
y_label="Claim Frequency",
title="test data",
ax=ax[1, 0],
fill_legend=True,
)
plot_obs_pred(
df=df_test,
feature="BonusMalus",
weight="Exposure",
observed="Frequency",
predicted=glm_freq.predict(X_test),
y_label="Claim Frequency",
title="test data",
ax=ax[1, 1],
fill_legend=True,
)
# %%
# According to the observed data, the frequency of accidents is higher for
# drivers younger than 30 years old, and is positively correlated with the
# `BonusMalus` variable. Our model is able to mostly correctly model this
# behaviour.
#
# Severity Model - Gamma distribution
# ------------------------------------
# The mean claim amount or severity (`AvgClaimAmount`) can be empirically
# shown to follow approximately a Gamma distribution. We fit a GLM model for
# the severity with the same features as the frequency model.
#
# Note:
#
# - We filter out ``ClaimAmount == 0`` as the Gamma distribution has support
# on :math:`(0, \infty)`, not :math:`[0, \infty)`.
# - We use ``ClaimNb`` as `sample_weight` to account for policies that contain
# more than one claim.
from sklearn.linear_model import GammaRegressor
mask_train = df_train["ClaimAmount"] > 0
mask_test = df_test["ClaimAmount"] > 0
glm_sev = GammaRegressor(alpha=10.0, solver="newton-cholesky")
glm_sev.fit(
X_train[mask_train.values],
df_train.loc[mask_train, "AvgClaimAmount"],
sample_weight=df_train.loc[mask_train, "ClaimNb"],
)
scores = score_estimator(
glm_sev,
X_train[mask_train.values],
X_test[mask_test.values],
df_train[mask_train],
df_test[mask_test],
target="AvgClaimAmount",
weights="ClaimNb",
)
print("Evaluation of GammaRegressor on target AvgClaimAmount")
print(scores)
# %%
#
# Those values of the metrics are not necessarily easy to interpret. It can be
# insightful to compare them with a model that does not use any input
# features and always predicts a constant value, i.e. the average claim
# amount, in the same setting:
from sklearn.dummy import DummyRegressor
dummy_sev = DummyRegressor(strategy="mean")
dummy_sev.fit(
X_train[mask_train.values],
df_train.loc[mask_train, "AvgClaimAmount"],
sample_weight=df_train.loc[mask_train, "ClaimNb"],
)
scores = score_estimator(
dummy_sev,
X_train[mask_train.values],
X_test[mask_test.values],
df_train[mask_train],
df_test[mask_test],
target="AvgClaimAmount",
weights="ClaimNb",
)
print("Evaluation of a mean predictor on target AvgClaimAmount")
print(scores)
# %%
#
# We conclude that the claim amount is very challenging to predict. Still, the
# :class:`~sklearn.linear.GammaRegressor` is able to leverage some information
# from the input features to slighly improve upon the mean baseline in terms
# of D².
#
# Note that the resulting model is the average claim amount per claim. As such,
# it is conditional on having at least one claim, and cannot be used to predict
# the average claim amount per policy. For this, it needs to be combined with
# a claims frequency model.
print(
"Mean AvgClaim Amount per policy: %.2f "
% df_train["AvgClaimAmount"].mean()
)
print(
"Mean AvgClaim Amount | NbClaim > 0: %.2f"
% df_train["AvgClaimAmount"][df_train["AvgClaimAmount"] > 0].mean()
)
print(
"Predicted Mean AvgClaim Amount | NbClaim > 0: %.2f"
% glm_sev.predict(X_train).mean()
)
print(
"Predicted Mean AvgClaim Amount (dummy) | NbClaim > 0: %.2f"
% dummy_sev.predict(X_train).mean()
)
# %%
# We can visually compare observed and predicted values, aggregated for
# the drivers age (``DrivAge``).
fig, ax = plt.subplots(ncols=1, nrows=2, figsize=(16, 6))
plot_obs_pred(
df=df_train.loc[mask_train],
feature="DrivAge",
weight="Exposure",
observed="AvgClaimAmount",
predicted=glm_sev.predict(X_train[mask_train.values]),
y_label="Average Claim Severity",
title="train data",
ax=ax[0],
)
plot_obs_pred(
df=df_test.loc[mask_test],
feature="DrivAge",
weight="Exposure",
observed="AvgClaimAmount",
predicted=glm_sev.predict(X_test[mask_test.values]),
y_label="Average Claim Severity",
title="test data",
ax=ax[1],
fill_legend=True,
)
plt.tight_layout()
# %%
# Overall, the drivers age (``DrivAge``) has a weak impact on the claim
# severity, both in observed and predicted data.
#
# Pure Premium Modeling via a Product Model vs single TweedieRegressor
# --------------------------------------------------------------------
# As mentioned in the introduction, the total claim amount per unit of
# exposure can be modeled as the product of the prediction of the
# frequency model by the prediction of the severity model.
#
# Alternatively, one can directly model the total loss with a unique
# Compound Poisson Gamma generalized linear model (with a log link function).
# This model is a special case of the Tweedie GLM with a "power" parameter
# :math:`p \in (1, 2)`. Here, we fix apriori the `power` parameter of the
# Tweedie model to some arbitrary value (1.9) in the valid range. Ideally one
# would select this value via grid-search by minimizing the negative
# log-likelihood of the Tweedie model, but unfortunately the current
# implementation does not allow for this (yet).
#
# We will compare the performance of both approaches.
# To quantify the performance of both models, one can compute
# the mean deviance of the train and test data assuming a Compound
# Poisson-Gamma distribution of the total claim amount. This is equivalent to
# a Tweedie distribution with a `power` parameter between 1 and 2.
#
# The :func:`sklearn.metrics.mean_tweedie_deviance` depends on a `power`
# parameter. As we do not know the true value of the `power` parameter, we here
# compute the mean deviances for a grid of possible values, and compare the
# models side by side, i.e. we compare them at identical values of `power`.
# Ideally, we hope that one model will be consistently better than the other,
# regardless of `power`.
from sklearn.linear_model import TweedieRegressor
glm_pure_premium = TweedieRegressor(power=1.9, alpha=0.1, solver="newton-cholesky")
glm_pure_premium.fit(
X_train, df_train["PurePremium"], sample_weight=df_train["Exposure"]
)
tweedie_powers = [1.5, 1.7, 1.8, 1.9, 1.99, 1.999, 1.9999]
scores_product_model = score_estimator(
(glm_freq, glm_sev),
X_train,
X_test,
df_train,
df_test,
target="PurePremium",
weights="Exposure",
tweedie_powers=tweedie_powers,
)
scores_glm_pure_premium = score_estimator(
glm_pure_premium,
X_train,
X_test,
df_train,
df_test,
target="PurePremium",
weights="Exposure",
tweedie_powers=tweedie_powers,
)
scores = pd.concat(
[scores_product_model, scores_glm_pure_premium],
axis=1,
sort=True,
keys=("Product Model", "TweedieRegressor"),
)
print("Evaluation of the Product Model and the Tweedie Regressor on target PurePremium")
with pd.option_context("display.expand_frame_repr", False):
print(scores)
# %%
# In this example, both modeling approaches yield comparable performance
# metrics. For implementation reasons, the percentage of explained variance
# :math:`D^2` is not available for the product model.
#
# We can additionally validate these models by comparing observed and
# predicted total claim amount over the test and train subsets. We see that,
# on average, both model tend to underestimate the total claim (but this
# behavior depends on the amount of regularization).
res = []
for subset_label, X, df in [
("train", X_train, df_train),
("test", X_test, df_test),
]:
exposure = df["Exposure"].values
res.append(
{
"subset": subset_label,
"observed": df["ClaimAmount"].values.sum(),
"predicted, frequency*severity model": np.sum(
exposure * glm_freq.predict(X) * glm_sev.predict(X)
),
"predicted, tweedie, power=%.2f"
% glm_pure_premium.power: np.sum(exposure * glm_pure_premium.predict(X)),
}
)
print(pd.DataFrame(res).set_index("subset").T)
# %%
#
# Finally, we can compare the two models using a plot of cumulated claims: for
# each model, the policyholders are ranked from safest to riskiest based on the
# model predictions and the fraction of observed total cumulated claims is
# plotted on the y axis. This plot is often called the ordered Lorenz curve of
# the model.
#
# The Gini coefficient (based on the area between the curve and the diagonal)
# can be used as a model selection metric to quantify the ability of the model
# to rank policyholders. Note that this metric does not reflect the ability of
# the models to make accurate predictions in terms of absolute value of total
# claim amounts but only in terms of relative amounts as a ranking metric. The
# Gini coefficient is upper bounded by 1.0 but even an oracle model that ranks
# the policyholders by the observed claim amounts cannot reach a score of 1.0.
#
# We observe that both models are able to rank policyholders by risky-ness
# significantly better than chance although they are also both far from the
# oracle model due to the natural difficulty of the prediction problem from a
# few features: most accidents are not predictable and can be caused by
# environmental circumstances that are not described at all by the input
# features of the models.
#
# Note that the Gini index only characterizes the ranking performance of the
# model but not its calibration: any monotonic transformation of the predictions
# leaves the Gini index of the model unchanged.
#
# Finally one should highlight that the Compound Poisson Gamma model that is
# directly fit on the pure premium is operationally simpler to develop and
# maintain as it consists of a single scikit-learn estimator instead of a pair
# of models, each with its own set of hyperparameters.
from sklearn.metrics import auc
def lorenz_curve(y_true, y_pred, exposure):
y_true, y_pred = np.asarray(y_true), np.asarray(y_pred)
exposure = np.asarray(exposure)
# order samples by increasing predicted risk:
ranking = np.argsort(y_pred)
ranked_exposure = exposure[ranking]
ranked_pure_premium = y_true[ranking]
cumulated_claim_amount = np.cumsum(ranked_pure_premium * ranked_exposure)
cumulated_claim_amount /= cumulated_claim_amount[-1]
cumulated_samples = np.linspace(0, 1, len(cumulated_claim_amount))
return cumulated_samples, cumulated_claim_amount
fig, ax = plt.subplots(figsize=(8, 8))
y_pred_product = glm_freq.predict(X_test) * glm_sev.predict(X_test)
y_pred_total = glm_pure_premium.predict(X_test)
for label, y_pred in [
("Frequency * Severity model", y_pred_product),
("Compound Poisson Gamma", y_pred_total),
]:
ordered_samples, cum_claims = lorenz_curve(
df_test["PurePremium"], y_pred, df_test["Exposure"]
)
gini = 1 - 2 * auc(ordered_samples, cum_claims)
label += " (Gini index: {:.3f})".format(gini)
ax.plot(ordered_samples, cum_claims, linestyle="-", label=label)
# Oracle model: y_pred == y_test
ordered_samples, cum_claims = lorenz_curve(
df_test["PurePremium"], df_test["PurePremium"], df_test["Exposure"]
)
gini = 1 - 2 * auc(ordered_samples, cum_claims)
label = "Oracle (Gini index: {:.3f})".format(gini)
ax.plot(ordered_samples, cum_claims, linestyle="-.", color="gray", label=label)
# Random baseline
ax.plot([0, 1], [0, 1], linestyle="--", color="black", label="Random baseline")
ax.set(
title="Lorenz Curves",
xlabel="Fraction of policyholders\n(ordered by model from safest to riskiest)",
ylabel="Fraction of total claim amount",
)
ax.legend(loc="upper left")
plt.plot()
| bsd-3-clause | a1dcad238fab5a2ce44aef300415f303 | 33.027417 | 88 | 0.67724 | 3.442482 | false | true | false | false |
scikit-learn/scikit-learn | sklearn/neighbors/tests/test_quad_tree.py | 17 | 4856 | import pickle
import numpy as np
import pytest
from sklearn.neighbors._quad_tree import _QuadTree
from sklearn.utils import check_random_state
def test_quadtree_boundary_computation():
# Introduce a point into a quad tree with boundaries not easy to compute.
Xs = []
# check a random case
Xs.append(np.array([[-1, 1], [-4, -1]], dtype=np.float32))
# check the case where only 0 are inserted
Xs.append(np.array([[0, 0], [0, 0]], dtype=np.float32))
# check the case where only negative are inserted
Xs.append(np.array([[-1, -2], [-4, 0]], dtype=np.float32))
# check the case where only small numbers are inserted
Xs.append(np.array([[-1e-6, 1e-6], [-4e-6, -1e-6]], dtype=np.float32))
for X in Xs:
tree = _QuadTree(n_dimensions=2, verbose=0)
tree.build_tree(X)
tree._check_coherence()
def test_quadtree_similar_point():
# Introduce a point into a quad tree where a similar point already exists.
# Test will hang if it doesn't complete.
Xs = []
# check the case where points are actually different
Xs.append(np.array([[1, 2], [3, 4]], dtype=np.float32))
# check the case where points are the same on X axis
Xs.append(np.array([[1.0, 2.0], [1.0, 3.0]], dtype=np.float32))
# check the case where points are arbitrarily close on X axis
Xs.append(np.array([[1.00001, 2.0], [1.00002, 3.0]], dtype=np.float32))
# check the case where points are the same on Y axis
Xs.append(np.array([[1.0, 2.0], [3.0, 2.0]], dtype=np.float32))
# check the case where points are arbitrarily close on Y axis
Xs.append(np.array([[1.0, 2.00001], [3.0, 2.00002]], dtype=np.float32))
# check the case where points are arbitrarily close on both axes
Xs.append(np.array([[1.00001, 2.00001], [1.00002, 2.00002]], dtype=np.float32))
# check the case where points are arbitrarily close on both axes
# close to machine epsilon - x axis
Xs.append(np.array([[1, 0.0003817754041], [2, 0.0003817753750]], dtype=np.float32))
# check the case where points are arbitrarily close on both axes
# close to machine epsilon - y axis
Xs.append(
np.array([[0.0003817754041, 1.0], [0.0003817753750, 2.0]], dtype=np.float32)
)
for X in Xs:
tree = _QuadTree(n_dimensions=2, verbose=0)
tree.build_tree(X)
tree._check_coherence()
@pytest.mark.parametrize("n_dimensions", (2, 3))
@pytest.mark.parametrize("protocol", (0, 1, 2))
def test_quad_tree_pickle(n_dimensions, protocol):
rng = check_random_state(0)
X = rng.random_sample((10, n_dimensions))
tree = _QuadTree(n_dimensions=n_dimensions, verbose=0)
tree.build_tree(X)
s = pickle.dumps(tree, protocol=protocol)
bt2 = pickle.loads(s)
for x in X:
cell_x_tree = tree.get_cell(x)
cell_x_bt2 = bt2.get_cell(x)
assert cell_x_tree == cell_x_bt2
@pytest.mark.parametrize("n_dimensions", (2, 3))
def test_qt_insert_duplicate(n_dimensions):
rng = check_random_state(0)
X = rng.random_sample((10, n_dimensions))
Xd = np.r_[X, X[:5]]
tree = _QuadTree(n_dimensions=n_dimensions, verbose=0)
tree.build_tree(Xd)
cumulative_size = tree.cumulative_size
leafs = tree.leafs
# Assert that the first 5 are indeed duplicated and that the next
# ones are single point leaf
for i, x in enumerate(X):
cell_id = tree.get_cell(x)
assert leafs[cell_id]
assert cumulative_size[cell_id] == 1 + (i < 5)
def test_summarize():
# Simple check for quad tree's summarize
angle = 0.9
X = np.array(
[[-10.0, -10.0], [9.0, 10.0], [10.0, 9.0], [10.0, 10.0]], dtype=np.float32
)
query_pt = X[0, :]
n_dimensions = X.shape[1]
offset = n_dimensions + 2
qt = _QuadTree(n_dimensions, verbose=0)
qt.build_tree(X)
idx, summary = qt._py_summarize(query_pt, X, angle)
node_dist = summary[n_dimensions]
node_size = summary[n_dimensions + 1]
# Summary should contain only 1 node with size 3 and distance to
# X[1:] barycenter
barycenter = X[1:].mean(axis=0)
ds2c = ((X[0] - barycenter) ** 2).sum()
assert idx == offset
assert node_size == 3, "summary size = {}".format(node_size)
assert np.isclose(node_dist, ds2c)
# Summary should contain all 3 node with size 1 and distance to
# each point in X[1:] for ``angle=0``
idx, summary = qt._py_summarize(query_pt, X, 0.0)
barycenter = X[1:].mean(axis=0)
ds2c = ((X[0] - barycenter) ** 2).sum()
assert idx == 3 * (offset)
for i in range(3):
node_dist = summary[i * offset + n_dimensions]
node_size = summary[i * offset + n_dimensions + 1]
ds2c = ((X[0] - X[i + 1]) ** 2).sum()
assert node_size == 1, "summary size = {}".format(node_size)
assert np.isclose(node_dist, ds2c)
| bsd-3-clause | 51d51613380dd5e0bfcd4505263c8615 | 32.722222 | 87 | 0.62603 | 3.023661 | false | true | false | false |
scikit-learn/scikit-learn | asv_benchmarks/benchmarks/neighbors.py | 17 | 1140 | from sklearn.neighbors import KNeighborsClassifier
from .common import Benchmark, Estimator, Predictor
from .datasets import _20newsgroups_lowdim_dataset
from .utils import make_gen_classif_scorers
class KNeighborsClassifierBenchmark(Predictor, Estimator, Benchmark):
"""
Benchmarks for KNeighborsClassifier.
"""
param_names = ["algorithm", "dimension", "n_jobs"]
params = (["brute", "kd_tree", "ball_tree"], ["low", "high"], Benchmark.n_jobs_vals)
def setup_cache(self):
super().setup_cache()
def make_data(self, params):
algorithm, dimension, n_jobs = params
if Benchmark.data_size == "large":
n_components = 40 if dimension == "low" else 200
else:
n_components = 10 if dimension == "low" else 50
data = _20newsgroups_lowdim_dataset(n_components=n_components)
return data
def make_estimator(self, params):
algorithm, dimension, n_jobs = params
estimator = KNeighborsClassifier(algorithm=algorithm, n_jobs=n_jobs)
return estimator
def make_scorers(self):
make_gen_classif_scorers(self)
| bsd-3-clause | 79dd841d2bd67a9d451267d998b1542d | 28.230769 | 88 | 0.660526 | 3.931034 | false | false | false | false |
scikit-learn/scikit-learn | benchmarks/bench_plot_omp_lars.py | 12 | 4454 | """Benchmarks of orthogonal matching pursuit (:ref:`OMP`) versus least angle
regression (:ref:`least_angle_regression`)
The input data is mostly low rank but is a fat infinite tail.
"""
import gc
import sys
from time import time
import numpy as np
from sklearn.linear_model import lars_path, lars_path_gram, orthogonal_mp
from sklearn.datasets import make_sparse_coded_signal
def compute_bench(samples_range, features_range):
it = 0
results = dict()
lars = np.empty((len(features_range), len(samples_range)))
lars_gram = lars.copy()
omp = lars.copy()
omp_gram = lars.copy()
max_it = len(samples_range) * len(features_range)
for i_s, n_samples in enumerate(samples_range):
for i_f, n_features in enumerate(features_range):
it += 1
n_informative = n_features / 10
print("====================")
print("Iteration %03d of %03d" % (it, max_it))
print("====================")
# dataset_kwargs = {
# 'n_train_samples': n_samples,
# 'n_test_samples': 2,
# 'n_features': n_features,
# 'n_informative': n_informative,
# 'effective_rank': min(n_samples, n_features) / 10,
# #'effective_rank': None,
# 'bias': 0.0,
# }
dataset_kwargs = {
"n_samples": 1,
"n_components": n_features,
"n_features": n_samples,
"n_nonzero_coefs": n_informative,
"random_state": 0,
"data_transposed": True,
}
print("n_samples: %d" % n_samples)
print("n_features: %d" % n_features)
y, X, _ = make_sparse_coded_signal(**dataset_kwargs)
X = np.asfortranarray(X)
gc.collect()
print("benchmarking lars_path (with Gram):", end="")
sys.stdout.flush()
tstart = time()
G = np.dot(X.T, X) # precomputed Gram matrix
Xy = np.dot(X.T, y)
lars_path_gram(Xy=Xy, Gram=G, n_samples=y.size, max_iter=n_informative)
delta = time() - tstart
print("%0.3fs" % delta)
lars_gram[i_f, i_s] = delta
gc.collect()
print("benchmarking lars_path (without Gram):", end="")
sys.stdout.flush()
tstart = time()
lars_path(X, y, Gram=None, max_iter=n_informative)
delta = time() - tstart
print("%0.3fs" % delta)
lars[i_f, i_s] = delta
gc.collect()
print("benchmarking orthogonal_mp (with Gram):", end="")
sys.stdout.flush()
tstart = time()
orthogonal_mp(X, y, precompute=True, n_nonzero_coefs=n_informative)
delta = time() - tstart
print("%0.3fs" % delta)
omp_gram[i_f, i_s] = delta
gc.collect()
print("benchmarking orthogonal_mp (without Gram):", end="")
sys.stdout.flush()
tstart = time()
orthogonal_mp(X, y, precompute=False, n_nonzero_coefs=n_informative)
delta = time() - tstart
print("%0.3fs" % delta)
omp[i_f, i_s] = delta
results["time(LARS) / time(OMP)\n (w/ Gram)"] = lars_gram / omp_gram
results["time(LARS) / time(OMP)\n (w/o Gram)"] = lars / omp
return results
if __name__ == "__main__":
samples_range = np.linspace(1000, 5000, 5).astype(int)
features_range = np.linspace(1000, 5000, 5).astype(int)
results = compute_bench(samples_range, features_range)
max_time = max(np.max(t) for t in results.values())
import matplotlib.pyplot as plt
fig = plt.figure("scikit-learn OMP vs. LARS benchmark results")
for i, (label, timings) in enumerate(sorted(results.items())):
ax = fig.add_subplot(1, 2, i + 1)
vmax = max(1 - timings.min(), -1 + timings.max())
plt.matshow(timings, fignum=False, vmin=1 - vmax, vmax=1 + vmax)
ax.set_xticklabels([""] + [str(each) for each in samples_range])
ax.set_yticklabels([""] + [str(each) for each in features_range])
plt.xlabel("n_samples")
plt.ylabel("n_features")
plt.title(label)
plt.subplots_adjust(0.1, 0.08, 0.96, 0.98, 0.4, 0.63)
ax = plt.axes([0.1, 0.08, 0.8, 0.06])
plt.colorbar(cax=ax, orientation="horizontal")
plt.show()
| bsd-3-clause | a4e6d56f953f542a7b39345e548902c0 | 35.809917 | 83 | 0.534351 | 3.426154 | false | false | false | false |
scikit-learn/scikit-learn | examples/linear_model/plot_ard.py | 12 | 7094 | """
====================================
Comparing Linear Bayesian Regressors
====================================
This example compares two different bayesian regressors:
- a :ref:`automatic_relevance_determination`
- a :ref:`bayesian_ridge_regression`
In the first part, we use an :ref:`ordinary_least_squares` (OLS) model as a
baseline for comparing the models' coefficients with respect to the true
coefficients. Thereafter, we show that the estimation of such models is done by
iteratively maximizing the marginal log-likelihood of the observations.
In the last section we plot predictions and uncertainties for the ARD and the
Bayesian Ridge regressions using a polynomial feature expansion to fit a
non-linear relationship between `X` and `y`.
"""
# Author: Arturo Amor <david-arturo.amor-quiroz@inria.fr>
# %%
# Models robustness to recover the ground truth weights
# =====================================================
#
# Generate synthetic dataset
# --------------------------
#
# We generate a dataset where `X` and `y` are linearly linked: 10 of the
# features of `X` will be used to generate `y`. The other features are not
# useful at predicting `y`. In addition, we generate a dataset where `n_samples
# == n_features`. Such a setting is challenging for an OLS model and leads
# potentially to arbitrary large weights. Having a prior on the weights and a
# penalty alleviates the problem. Finally, gaussian noise is added.
from sklearn.datasets import make_regression
X, y, true_weights = make_regression(
n_samples=100,
n_features=100,
n_informative=10,
noise=8,
coef=True,
random_state=42,
)
# %%
# Fit the regressors
# ------------------
#
# We now fit both Bayesian models and the OLS to later compare the models'
# coefficients.
import pandas as pd
from sklearn.linear_model import ARDRegression, LinearRegression, BayesianRidge
olr = LinearRegression().fit(X, y)
brr = BayesianRidge(compute_score=True, n_iter=30).fit(X, y)
ard = ARDRegression(compute_score=True, n_iter=30).fit(X, y)
df = pd.DataFrame(
{
"Weights of true generative process": true_weights,
"ARDRegression": ard.coef_,
"BayesianRidge": brr.coef_,
"LinearRegression": olr.coef_,
}
)
# %%
# Plot the true and estimated coefficients
# ----------------------------------------
#
# Now we compare the coefficients of each model with the weights of
# the true generative model.
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.colors import SymLogNorm
plt.figure(figsize=(10, 6))
ax = sns.heatmap(
df.T,
norm=SymLogNorm(linthresh=10e-4, vmin=-80, vmax=80),
cbar_kws={"label": "coefficients' values"},
cmap="seismic_r",
)
plt.ylabel("linear model")
plt.xlabel("coefficients")
plt.tight_layout(rect=(0, 0, 1, 0.95))
_ = plt.title("Models' coefficients")
# %%
# Due to the added noise, none of the models recover the true weights. Indeed,
# all models always have more than 10 non-zero coefficients. Compared to the OLS
# estimator, the coefficients using a Bayesian Ridge regression are slightly
# shifted toward zero, which stabilises them. The ARD regression provides a
# sparser solution: some of the non-informative coefficients are set exactly to
# zero, while shifting others closer to zero. Some non-informative coefficients
# are still present and retain large values.
# %%
# Plot the marginal log-likelihood
# --------------------------------
import numpy as np
ard_scores = -np.array(ard.scores_)
brr_scores = -np.array(brr.scores_)
plt.plot(ard_scores, color="navy", label="ARD")
plt.plot(brr_scores, color="red", label="BayesianRidge")
plt.ylabel("Log-likelihood")
plt.xlabel("Iterations")
plt.xlim(1, 30)
plt.legend()
_ = plt.title("Models log-likelihood")
# %%
# Indeed, both models minimize the log-likelihood up to an arbitrary cutoff
# defined by the `n_iter` parameter.
#
# Bayesian regressions with polynomial feature expansion
# ======================================================
# Generate synthetic dataset
# --------------------------
# We create a target that is a non-linear function of the input feature.
# Noise following a standard uniform distribution is added.
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
rng = np.random.RandomState(0)
n_samples = 110
# sort the data to make plotting easier later
X = np.sort(-10 * rng.rand(n_samples) + 10)
noise = rng.normal(0, 1, n_samples) * 1.35
y = np.sqrt(X) * np.sin(X) + noise
full_data = pd.DataFrame({"input_feature": X, "target": y})
X = X.reshape((-1, 1))
# extrapolation
X_plot = np.linspace(10, 10.4, 10)
y_plot = np.sqrt(X_plot) * np.sin(X_plot)
X_plot = np.concatenate((X, X_plot.reshape((-1, 1))))
y_plot = np.concatenate((y - noise, y_plot))
# %%
# Fit the regressors
# ------------------
#
# Here we try a degree 10 polynomial to potentially overfit, though the bayesian
# linear models regularize the size of the polynomial coefficients. As
# `fit_intercept=True` by default for
# :class:`~sklearn.linear_model.ARDRegression` and
# :class:`~sklearn.linear_model.BayesianRidge`, then
# :class:`~sklearn.preprocessing.PolynomialFeatures` should not introduce an
# additional bias feature. By setting `return_std=True`, the bayesian regressors
# return the standard deviation of the posterior distribution for the model
# parameters.
ard_poly = make_pipeline(
PolynomialFeatures(degree=10, include_bias=False),
StandardScaler(),
ARDRegression(),
).fit(X, y)
brr_poly = make_pipeline(
PolynomialFeatures(degree=10, include_bias=False),
StandardScaler(),
BayesianRidge(),
).fit(X, y)
y_ard, y_ard_std = ard_poly.predict(X_plot, return_std=True)
y_brr, y_brr_std = brr_poly.predict(X_plot, return_std=True)
# %%
# Plotting polynomial regressions with std errors of the scores
# -------------------------------------------------------------
ax = sns.scatterplot(
data=full_data, x="input_feature", y="target", color="black", alpha=0.75
)
ax.plot(X_plot, y_plot, color="black", label="Ground Truth")
ax.plot(X_plot, y_brr, color="red", label="BayesianRidge with polynomial features")
ax.plot(X_plot, y_ard, color="navy", label="ARD with polynomial features")
ax.fill_between(
X_plot.ravel(),
y_ard - y_ard_std,
y_ard + y_ard_std,
color="navy",
alpha=0.3,
)
ax.fill_between(
X_plot.ravel(),
y_brr - y_brr_std,
y_brr + y_brr_std,
color="red",
alpha=0.3,
)
ax.legend()
_ = ax.set_title("Polynomial fit of a non-linear feature")
# %%
# The error bars represent one standard deviation of the predicted gaussian
# distribution of the query points. Notice that the ARD regression captures the
# ground truth the best when using the default parameters in both models, but
# further reducing the `lambda_init` hyperparameter of the Bayesian Ridge can
# reduce its bias (see example
# :ref:`sphx_glr_auto_examples_linear_model_plot_bayesian_ridge_curvefit.py`).
# Finally, due to the intrinsic limitations of a polynomial regression, both
# models fail when extrapolating.
| bsd-3-clause | 1854c39e6cec8bd5600d347c3a09af72 | 32.780952 | 83 | 0.685932 | 3.423745 | false | false | false | false |
diofant/diofant | diofant/ntheory/partitions_.py | 1 | 2833 | import math
from mpmath.libmp import (bitcount, fhalf, fone, from_int, from_man_exp,
from_rational, fzero, mpf_add, mpf_cos,
mpf_cosh_sinh, mpf_div, mpf_mul, mpf_pi, mpf_sqrt,
mpf_sub, pi_fixed, to_int)
__all__ = 'npartitions',
def _a(n, j, prec):
"""Compute the inner sum in the HRR formula."""
assert prec > 3
if j == 1:
return fone
s = fzero
pi = pi_fixed(prec)
for h in range(1, j):
if math.gcd(h, j) != 1:
continue
# & with mask to compute fractional part of fixed-point number
one = 1 << prec
onemask = one - 1
half = one >> 1
g = 0
if j >= 3:
for k in range(1, j):
t = h*k*one//j
frac = t & onemask
g += k*(frac - half)
g = ((g - 2*h*n*one)*pi//j) >> prec
s = mpf_add(s, mpf_cos(from_man_exp(g, -prec), prec), prec)
return s
def _d(n, j, prec, sq23pi, sqrt8):
"""Compute the sinh term in the outer sum of the HRR formula.
The constants sqrt(2/3*pi) and sqrt(8) must be precomputed.
"""
j = from_int(j)
pi = mpf_pi(prec)
a = mpf_div(sq23pi, j, prec)
b = mpf_sub(from_int(n), from_rational(1, 24, prec), prec)
c = mpf_sqrt(b, prec)
ch, sh = mpf_cosh_sinh(mpf_mul(a, c), prec)
D = mpf_div(mpf_sqrt(j, prec), mpf_mul(mpf_mul(sqrt8, b), pi), prec)
E = mpf_sub(mpf_mul(a, ch), mpf_div(sh, c, prec), prec)
return mpf_mul(D, E)
def npartitions(n):
"""Calculate the partition function P(n), i.e. the number of ways that
n can be written as a sum of positive integers.
P(n) is computed using the Hardy-Ramanujan-Rademacher formula.
The correctness of this implementation has been tested for 10**n
up to n = 8.
Examples
========
>>> npartitions(25)
1958
References
==========
* https://mathworld.wolfram.com/PartitionFunctionP.html
"""
n = int(n)
if n < 0:
return 0
if n <= 5:
return [1, 1, 2, 3, 5, 7][n]
# Estimate number of bits in p(n). This formula could be tidied
pbits = int((math.pi*(2*n/3.)**0.5 - math.log(4*n))/math.log(10) + 1) * \
math.log(10, 2)
prec = p = int(pbits*1.1 + 100)
s = fzero
M = max(6, int(0.24*n**0.5 + 4))
sq23pi = mpf_mul(mpf_sqrt(from_rational(2, 3, p), p), mpf_pi(p), p)
sqrt8 = mpf_sqrt(from_int(8), p)
for q in range(1, M):
a = _a(n, q, p)
d = _d(n, q, p, sq23pi, sqrt8)
s = mpf_add(s, mpf_mul(a, d), prec)
# On average, the terms decrease rapidly in magnitude. Dynamically
# reducing the precision greatly improves performance.
p = bitcount(abs(to_int(d))) + 50
return int(to_int(mpf_add(s, fhalf, prec)))
| bsd-3-clause | d8c21ae8853ef5f532d463e77d64ce8c | 28.821053 | 77 | 0.53371 | 2.941848 | false | false | false | false |
diofant/diofant | diofant/combinatorics/named_groups.py | 2 | 7374 | from .group_constructs import DirectProduct
from .perm_groups import PermutationGroup
from .permutations import Permutation
_af_new = Permutation._af_new
def AbelianGroup(*cyclic_orders):
"""
Returns the direct product of cyclic groups with the given orders.
According to the structure theorem for finite abelian groups ([1]),
every finite abelian group can be written as the direct product of
finitely many cyclic groups.
Examples
========
>>> Permutation.print_cyclic = True
>>> AbelianGroup(3, 4)
PermutationGroup([
Permutation(6)(0, 1, 2),
Permutation(3, 4, 5, 6)])
>>> _.is_group
True
See Also
========
diofant.combinatorics.group_constructs.DirectProduct
References
==========
* https://groupprops.subwiki.org/wiki/Structure_theorem_for_finitely_generated_abelian_groups
"""
groups = []
degree = 0
order = 1
for size in cyclic_orders:
degree += size
order *= size
groups.append(CyclicGroup(size))
G = DirectProduct(*groups)
G._is_abelian = True
G._degree = degree
G._order = order
return G
def AlternatingGroup(n):
"""
Generates the alternating group on ``n`` elements as a permutation group.
For ``n > 2``, the generators taken are ``(0 1 2), (0 1 2 ... n-1)`` for
``n`` odd
and ``(0 1 2), (1 2 ... n-1)`` for ``n`` even (See [1], p.31, ex.6.9.).
After the group is generated, some of its basic properties are set.
The cases ``n = 1, 2`` are handled separately.
Examples
========
>>> G = AlternatingGroup(4)
>>> G.is_group
True
>>> a = list(G.generate_dimino())
>>> len(a)
12
>>> all(perm.is_even for perm in a)
True
See Also
========
SymmetricGroup, CyclicGroup, DihedralGroup
References
==========
[1] Armstrong, M. "Groups and Symmetry"
"""
# small cases are special
if n in (1, 2):
return PermutationGroup([Permutation([0])])
a = list(range(n))
a[0], a[1], a[2] = a[1], a[2], a[0]
gen1 = a
if n % 2:
a = list(range(1, n))
a.append(0)
gen2 = a
else:
a = list(range(2, n))
a.append(1)
a.insert(0, 0)
gen2 = a
gens = [gen1, gen2]
if gen1 == gen2:
gens = gens[:1]
G = PermutationGroup([_af_new(a) for a in gens], dups=False)
if n < 4:
G._is_abelian = True
G._is_nilpotent = True
else:
G._is_abelian = False
G._is_nilpotent = False
if n < 5:
G._is_solvable = True
else:
G._is_solvable = False
G._degree = n
G._is_transitive = True
G._is_alt = True
return G
def CyclicGroup(n):
"""
Generates the cyclic group of order ``n`` as a permutation group.
The generator taken is the ``n``-cycle ``(0 1 2 ... n-1)``
(in cycle notation). After the group is generated, some of its basic
properties are set.
Examples
========
>>> G = CyclicGroup(6)
>>> G.is_group
True
>>> G.order()
6
>>> list(G.generate_schreier_sims(af=True))
[[0, 1, 2, 3, 4, 5], [1, 2, 3, 4, 5, 0], [2, 3, 4, 5, 0, 1],
[3, 4, 5, 0, 1, 2], [4, 5, 0, 1, 2, 3], [5, 0, 1, 2, 3, 4]]
See Also
========
SymmetricGroup, DihedralGroup, AlternatingGroup
"""
a = list(range(1, n))
a.append(0)
gen = _af_new(a)
G = PermutationGroup([gen])
G._is_abelian = True
G._is_nilpotent = True
G._is_solvable = True
G._degree = n
G._is_transitive = True
G._order = n
return G
def DihedralGroup(n):
r"""
Generates the dihedral group `D_n` as a permutation group.
The dihedral group `D_n` is the group of symmetries of the regular
``n``-gon. The generators taken are the ``n``-cycle ``a = (0 1 2 ... n-1)``
(a rotation of the ``n``-gon) and ``b = (0 n-1)(1 n-2)...``
(a reflection of the ``n``-gon) in cycle rotation. It is easy to see that
these satisfy ``a**n = b**2 = 1`` and ``bab = ~a`` so they indeed generate
`D_n` (See [1]). After the group is generated, some of its basic properties
are set.
Examples
========
>>> G = DihedralGroup(5)
>>> G.is_group
True
>>> a = list(G.generate_dimino())
>>> [perm.cyclic_form for perm in a]
[[], [[0, 1, 2, 3, 4]], [[0, 2, 4, 1, 3]],
[[0, 3, 1, 4, 2]], [[0, 4, 3, 2, 1]], [[0, 4], [1, 3]],
[[1, 4], [2, 3]], [[0, 1], [2, 4]], [[0, 2], [3, 4]],
[[0, 3], [1, 2]]]
See Also
========
SymmetricGroup, CyclicGroup, AlternatingGroup
References
==========
[1] https://en.wikipedia.org/wiki/Dihedral_group
"""
# small cases are special
if n == 1:
return PermutationGroup([Permutation([1, 0])])
if n == 2:
return PermutationGroup([Permutation([1, 0, 3, 2]),
Permutation([2, 3, 0, 1]), Permutation([3, 2, 1, 0])])
a = list(range(1, n))
a.append(0)
gen1 = _af_new(a)
a = list(range(n))
a.reverse()
gen2 = _af_new(a)
G = PermutationGroup([gen1, gen2])
# if n is a power of 2, group is nilpotent
if n & (n-1) == 0:
G._is_nilpotent = True
else:
G._is_nilpotent = False
G._is_abelian = False
G._is_solvable = True
G._degree = n
G._is_transitive = True
G._order = 2*n
return G
def SymmetricGroup(n):
"""
Generates the symmetric group on ``n`` elements as a permutation group.
The generators taken are the ``n``-cycle
``(0 1 2 ... n-1)`` and the transposition ``(0 1)`` (in cycle notation).
(See [1]). After the group is generated, some of its basic properties
are set.
Examples
========
>>> G = SymmetricGroup(4)
>>> G.is_group
True
>>> G.order()
24
>>> list(G.generate_schreier_sims(af=True))
[[0, 1, 2, 3], [1, 2, 3, 0], [2, 3, 0, 1], [3, 1, 2, 0], [0, 2, 3, 1],
[1, 3, 0, 2], [2, 0, 1, 3], [3, 2, 0, 1], [0, 3, 1, 2], [1, 0, 2, 3],
[2, 1, 3, 0], [3, 0, 1, 2], [0, 1, 3, 2], [1, 2, 0, 3], [2, 3, 1, 0],
[3, 1, 0, 2], [0, 2, 1, 3], [1, 3, 2, 0], [2, 0, 3, 1], [3, 2, 1, 0],
[0, 3, 2, 1], [1, 0, 3, 2], [2, 1, 0, 3], [3, 0, 2, 1]]
See Also
========
CyclicGroup, DihedralGroup, AlternatingGroup
References
==========
[1] https://en.wikipedia.org/wiki/Symmetric_group#Generators_and_relations
"""
if n == 1:
G = PermutationGroup([Permutation([0])])
elif n == 2:
G = PermutationGroup([Permutation([1, 0])])
else:
a = list(range(1, n))
a.append(0)
gen1 = _af_new(a)
a = list(range(n))
a[0], a[1] = a[1], a[0]
gen2 = _af_new(a)
G = PermutationGroup([gen1, gen2])
if n < 3:
G._is_abelian = True
G._is_nilpotent = True
else:
G._is_abelian = False
G._is_nilpotent = False
if n < 5:
G._is_solvable = True
else:
G._is_solvable = False
G._degree = n
G._is_transitive = True
G._is_sym = True
return G
def RubikGroup(n):
"""Return a group of Rubik's cube generators.
>>> RubikGroup(2).is_group
True
"""
from .generators import rubik
if n <= 1:
raise ValueError('Invalid cube . n has to be greater than 1')
return PermutationGroup(rubik(n))
| bsd-3-clause | 83bbb0871753ca25c2532b9c6c409b7e | 23.58 | 97 | 0.524546 | 3.066112 | false | false | false | false |
diofant/diofant | diofant/tests/simplify/test_combsimp.py | 1 | 5742 | from diofant import (FallingFactorial, Rational, RisingFactorial, Symbol,
binomial, combsimp, cos, exp, factorial, gamma, pi,
powsimp, rf, simplify, sin, sqrt, symbols)
from diofant.abc import k, n, x, y
__all__ = ()
def test_combsimp():
assert combsimp(factorial(n)) == factorial(n)
assert combsimp(binomial(n, k)) == binomial(n, k)
assert combsimp(factorial(n)/factorial(n - 3)) == n*(-1 + n)*(-2 + n)
assert combsimp(binomial(n + 1, k + 1)/binomial(n, k)) == (1 + n)/(1 + k)
assert combsimp(binomial(3*n + 4, n + 1)/binomial(3*n + 1, n)) == \
Rational(3, 2)*((3*n + 2)*(3*n + 4)/((n + 1)*(2*n + 3)))
assert combsimp(factorial(n)**2/factorial(n - 3)) == \
factorial(n)*n*(-1 + n)*(-2 + n)
assert combsimp(factorial(n)*binomial(n + 1, k + 1)/binomial(n, k)) == \
factorial(n + 1)/(1 + k)
assert combsimp(binomial(n - 1, k)) == -((-n + k)*binomial(n, k))/n
assert combsimp(binomial(n + 2, k + Rational(1, 2))) == 4*((n + 1)*(n + 2) *
binomial(n, k + Rational(1, 2)))/((2*k - 2*n - 1)*(2*k - 2*n - 3))
assert combsimp(binomial(n + 2, k + 2.0)) == \
-((1.0*n + 2.0)*binomial(n + 1.0, k + 2.0))/(k - n)
# coverage tests
assert combsimp(factorial(n*(1 + n) - n**2 - n)) == 1
assert combsimp(binomial(n + k - 2, n)) == \
k*(k - 1)*binomial(n + k, n)/((n + k)*(n + k - 1))
i = Symbol('i', integer=True)
e = gamma(i + 3)
assert combsimp(e) == e
e = gamma(exp(i))
assert combsimp(e) == e
e = gamma(n + Rational(1, 3))*gamma(n + Rational(2, 3))
assert combsimp(e) == e
assert combsimp(gamma(4*n + Rational(1, 2))/gamma(2*n - Rational(3, 4))) == \
2**(4*n - Rational(5, 2))*(8*n - 3)*gamma(2*n + Rational(3, 4))/sqrt(pi)
assert combsimp(6*FallingFactorial(-4, n)/factorial(n)) == \
(-1)**n*(n + 1)*(n + 2)*(n + 3)
assert combsimp(6*FallingFactorial(-4, n - 1)/factorial(n - 1)) == \
(-1)**(n - 1)*n*(n + 1)*(n + 2)
assert combsimp(6*FallingFactorial(-4, n - 3)/factorial(n - 3)) == \
(-1)**(n - 3)*n*(n - 1)*(n - 2)
assert combsimp(6*FallingFactorial(-4, -n - 1)/factorial(-n - 1)) == \
-(-1)**(-n - 1)*n*(n - 1)*(n - 2)
assert combsimp(6*RisingFactorial(4, n)/factorial(n)) == \
(n + 1)*(n + 2)*(n + 3)
assert combsimp(6*RisingFactorial(4, n - 1)/factorial(n - 1)) == \
n*(n + 1)*(n + 2)
assert combsimp(6*RisingFactorial(4, n - 3)/factorial(n - 3)) == \
n*(n - 1)*(n - 2)
assert combsimp(6*RisingFactorial(4, -n - 1)/factorial(-n - 1)) == \
-n*(n - 1)*(n - 2)
def test_combsimp_gamma():
R = Rational
assert combsimp(gamma(x)) == gamma(x)
assert combsimp(gamma(x + 1)/x) == gamma(x)
assert combsimp(gamma(x)/(x - 1)) == gamma(x - 1)
assert combsimp(x*gamma(x)) == gamma(x + 1)
assert combsimp((x + 1)*gamma(x + 1)) == gamma(x + 2)
assert combsimp(gamma(x + y)*(x + y)) == gamma(x + y + 1)
assert combsimp(x/gamma(x + 1)) == 1/gamma(x)
assert combsimp((x + 1)**2/gamma(x + 2)) == (x + 1)/gamma(x + 1)
assert combsimp(x*gamma(x) + gamma(x + 3)/(x + 2)) == \
(x + 2)*gamma(x + 1)
assert combsimp(gamma(2*x)*x) == gamma(2*x + 1)/2
assert combsimp(gamma(2*x)/(x - Rational(1, 2))) == 2*gamma(2*x - 1)
assert combsimp(gamma(x)*gamma(1 - x)) == pi/sin(pi*x)
assert combsimp(gamma(x)*gamma(-x)) == -pi/(x*sin(pi*x))
assert combsimp(1/gamma(x + 3)/gamma(1 - x)) == \
sin(pi*x)/(pi*x*(x + 1)*(x + 2))
assert powsimp(combsimp(
gamma(x)*gamma(x + Rational(1, 2))*gamma(y)/gamma(x + y))) == \
2**(-2*x + 1)*sqrt(pi)*gamma(2*x)*gamma(y)/gamma(x + y)
assert combsimp(1/gamma(x)/gamma(x - Rational(1, 3))/gamma(x + Rational(1, 3))) == \
3**(3*x - Rational(3, 2))/(2*pi*gamma(3*x - 1))
assert simplify(
gamma(Rational(1, 2) + x/2)*gamma(1 + x/2)/gamma(1 + x)/sqrt(pi)*2**x) == 1
assert combsimp(gamma(Rational(-1, 4))*gamma(Rational(-3, 4))) == 16*sqrt(2)*pi/3
assert powsimp(combsimp(gamma(2*x)/gamma(x))) == \
2**(2*x - 1)*gamma(x + Rational(1, 2))/sqrt(pi)
# issue sympy/sympy#6792
e = (-gamma(k)*gamma(k + 2) + gamma(k + 1)**2)/gamma(k)**2
assert combsimp(e) == -k
assert combsimp(1/e) == -1/k
e = (gamma(x) + gamma(x + 1))/gamma(x)
assert combsimp(e) == x + 1
assert combsimp(1/e) == 1/(x + 1)
e = (gamma(x) + gamma(x + 2))*(gamma(x - 1) + gamma(x))/gamma(x)
assert combsimp(e) == (x**2 + x + 1)*gamma(x + 1)/(x - 1)
e = (-gamma(k)*gamma(k + 2) + gamma(k + 1)**2)/gamma(k)**2
assert combsimp(e**2) == k**2
assert combsimp(e**2/gamma(k + 1)) == k/gamma(k)
a = R(1, 2) + R(1, 3)
b = a + R(1, 3)
assert combsimp(gamma(2*k)/gamma(k)*gamma(k + a)*gamma(k + b)) == \
3*2**(2*k + 1)*3**(-3*k - 2)*sqrt(pi)*gamma(3*k + R(3, 2))/2
A, B = symbols('A B', commutative=False)
assert combsimp(e*B*A) == combsimp(e)*B*A
# check iteration
assert combsimp(gamma(2*k)/gamma(k)*gamma(-k - R(1, 2))) == (
-2**(2*k + 1)*sqrt(pi)/(2*((2*k + 1)*cos(pi*k))))
assert combsimp(
gamma(k)*gamma(k + R(1, 3))*gamma(k + R(2, 3))/gamma(3*k/2)) == (
3*2**(3*k + 1)*3**(-3*k - Rational(1, 2))*sqrt(pi)*gamma(3*k/2 + Rational(1, 2))/2)
def test_sympyissue_9699():
n, k = symbols('n k', real=True)
assert combsimp((n + 1)*factorial(n)) == factorial(n + 1)
assert combsimp((x + 1)*factorial(x)/gamma(y)) == gamma(x + 2)/gamma(y)
assert combsimp(factorial(n)/n) == factorial(n - 1)
assert combsimp(rf(x + n, k)*binomial(n, k)) == binomial(n, k)*gamma(k + n + x)/gamma(n + x)
| bsd-3-clause | 45310ddef84fe96709c9a29f34cebadc | 42.5 | 129 | 0.512713 | 2.589986 | false | false | false | false |
diofant/diofant | diofant/tests/matrices/test_matadd.py | 2 | 1178 | import pytest
from diofant import (Basic, ImmutableMatrix, MatAdd, MatMul, MatPow,
MatrixSymbol, ShapeError, eye)
__all__ = ()
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
def test_sort_key():
assert MatAdd(Y, X).doit().args == (X, Y)
def test_matadd():
pytest.raises(ShapeError, lambda: X + eye(1))
MatAdd(X, eye(1), check=False) # not raises
def test_matadd_sympify():
assert isinstance(MatAdd(eye(1), eye(1)).args[0], Basic)
def test_matadd_of_matrices():
assert MatAdd(eye(2), 4*eye(2), eye(2)).doit() == ImmutableMatrix(6*eye(2))
def test_doit_args():
A = ImmutableMatrix([[1, 2], [3, 4]])
B = ImmutableMatrix([[2, 3], [4, 5]])
assert MatAdd(A, MatPow(B, 2)).doit() == A + B**2
assert MatAdd(A, MatMul(A, B)).doit() == A + A*B
assert MatAdd(A, A).doit(deep=False) == 2*A
assert (MatAdd(A, X, MatMul(A, B), Y, MatAdd(2*A, B)).doit() ==
MatAdd(X, Y, 3*A + A*B + B))
def test_is_commutative():
A = MatrixSymbol('A', 2, 2, commutative=True)
B = MatrixSymbol('B', 2, 2, commutative=True)
assert (A + B).is_commutative
assert (A + X).is_commutative is False
| bsd-3-clause | 73baa1315c230038a068c51ce7b41b6d | 25.772727 | 79 | 0.588285 | 2.745921 | false | true | false | false |
diofant/diofant | diofant/tensor/array/arrayop.py | 2 | 7985 | import collections
import itertools
from ...combinatorics import Permutation
from ...core import Integer, Tuple, diff
from ...matrices import MatrixBase
from .dense_ndim_array import ImmutableDenseNDimArray
from .ndim_array import NDimArray
def _arrayfy(a):
if isinstance(a, NDimArray):
return a
if isinstance(a, (MatrixBase, list, tuple, Tuple)):
return ImmutableDenseNDimArray(a)
return a
def tensorproduct(*args):
"""
Tensor product among scalars or array-like objects.
Examples
========
>>> A = Array([[1, 2], [3, 4]])
>>> B = Array([x, y])
>>> tensorproduct(A, B)
[[[x, y], [2*x, 2*y]], [[3*x, 3*y], [4*x, 4*y]]]
>>> tensorproduct(A, x)
[[x, 2*x], [3*x, 4*x]]
>>> tensorproduct(A, B, B)
[[[[x**2, x*y], [x*y, y**2]], [[2*x**2, 2*x*y], [2*x*y, 2*y**2]]],
[[[3*x**2, 3*x*y], [3*x*y, 3*y**2]], [[4*x**2, 4*x*y], [4*x*y, 4*y**2]]]]
Applying this function on two matrices will result in a rank 4 array.
>>> m = Matrix([[x, y], [z, t]])
>>> p = tensorproduct(eye(3), m)
>>> p
[[[[x, y], [z, t]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]],
[[[0, 0], [0, 0]], [[x, y], [z, t]], [[0, 0], [0, 0]]],
[[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[x, y], [z, t]]]]
"""
if len(args) == 0:
return Integer(1)
if len(args) == 1:
return _arrayfy(args[0])
if len(args) > 2:
return tensorproduct(tensorproduct(args[0], args[1]), *args[2:])
# length of args is 2:
a, b = map(_arrayfy, args)
if not isinstance(a, NDimArray) or not isinstance(b, NDimArray):
return a*b
al = list(a)
bl = list(b)
product_list = [i*j for i in al for j in bl]
return ImmutableDenseNDimArray(product_list, a.shape + b.shape)
def tensorcontraction(array, *contraction_axes):
"""
Contraction of an array-like object on the specified axes.
Examples
========
>>> tensorcontraction(eye(3), (0, 1))
3
>>> A = Array(range(18), (3, 2, 3))
>>> A
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]],
[[12, 13, 14], [15, 16, 17]]]
>>> tensorcontraction(A, (0, 2))
[21, 30]
Matrix multiplication may be emulated with a proper combination of
``tensorcontraction`` and ``tensorproduct``
>>> from diofant.abc import e, f, g, h
>>> m1 = Matrix([[a, b], [c, d]])
>>> m2 = Matrix([[e, f], [g, h]])
>>> p = tensorproduct(m1, m2)
>>> p
[[[[a*e, a*f], [a*g, a*h]], [[b*e, b*f], [b*g, b*h]]],
[[[c*e, c*f], [c*g, c*h]], [[d*e, d*f], [d*g, d*h]]]]
>>> tensorcontraction(p, (1, 2))
[[a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]]
>>> m1*m2
Matrix([
[a*e + b*g, a*f + b*h],
[c*e + d*g, c*f + d*h]])
"""
array = _arrayfy(array)
# Verify contraction_axes:
taken_dims = set()
for axes_group in contraction_axes:
if not isinstance(axes_group, collections.abc.Iterable):
raise ValueError('collections of contraction axes expected')
dim = array.shape[axes_group[0]]
for d in axes_group:
if d in taken_dims:
raise ValueError('dimension specified more than once')
if dim != array.shape[d]:
raise ValueError('cannot contract between axes of different dimension')
taken_dims.add(d)
rank = array.rank()
remaining_shape = [dim for i, dim in enumerate(array.shape) if i not in taken_dims]
cum_shape = [0]*rank
_cumul = 1
for i in range(rank):
cum_shape[rank - i - 1] = _cumul
_cumul *= int(array.shape[rank - i - 1])
# DEFINITION: by absolute position it is meant the position along the one
# dimensional array containing all the tensor components.
# Possible future work on this module: move computation of absolute
# positions to a class method.
# Determine absolute positions of the uncontracted indices:
remaining_indices = [[cum_shape[i]*j for j in range(array.shape[i])]
for i in range(rank) if i not in taken_dims]
# Determine absolute positions of the contracted indices:
summed_deltas = []
for axes_group in contraction_axes:
lidx = []
for js in range(array.shape[axes_group[0]]):
lidx.append(sum(cum_shape[ig] * js for ig in axes_group))
summed_deltas.append(lidx)
# Compute the contracted array:
#
# 1. external for loops on all uncontracted indices.
# Uncontracted indices are determined by the combinatorial product of
# the absolute positions of the remaining indices.
# 2. internal loop on all contracted indices.
# It sum the values of the absolute contracted index and the absolute
# uncontracted index for the external loop.
contracted_array = []
for icontrib in itertools.product(*remaining_indices):
index_base_position = sum(icontrib)
isum = Integer(0)
for sum_to_index in itertools.product(*summed_deltas):
isum += array[index_base_position + sum(sum_to_index)]
contracted_array.append(isum)
if len(remaining_indices) == 0:
assert len(contracted_array) == 1
return contracted_array[0]
return type(array)(contracted_array, remaining_shape)
def derive_by_array(expr, dx):
r"""
Derivative by arrays. Supports both arrays and scalars.
Given the array `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}`
this function will return a new array `B` defined by
`B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}`
Examples
========
>>> derive_by_array(cos(x*t), x)
-t*sin(t*x)
>>> derive_by_array(cos(x*t), [x, y, z, t])
[-t*sin(t*x), 0, 0, -x*sin(t*x)]
>>> derive_by_array([x, y**2*z], [[x, y], [z, t]])
[[[1, 0], [0, 2*y*z]], [[0, y**2], [0, 0]]]
"""
array_types = (collections.abc.Iterable, MatrixBase, NDimArray)
if isinstance(dx, array_types):
dx = ImmutableDenseNDimArray(dx)
for i in dx:
if not i._diff_wrt:
raise ValueError('cannot derive by this array')
if isinstance(expr, array_types):
expr = ImmutableDenseNDimArray(expr)
new_array = [[y.diff(x) for y in expr] for x in dx]
return type(expr)(new_array, dx.shape + expr.shape)
else:
if isinstance(dx, array_types):
return ImmutableDenseNDimArray([expr.diff(i) for i in dx], dx.shape)
else:
return diff(expr, dx)
def permutedims(expr, perm):
"""
Permutes the indices of an array.
Parameter specifies the permutation of the indices.
Examples
========
>>> a = Array([[x, y, z], [t, sin(x), 0]])
>>> a
[[x, y, z], [t, sin(x), 0]]
>>> permutedims(a, (1, 0))
[[x, t], [y, sin(x)], [z, 0]]
If the array is of second order, ``transpose`` can be used:
>>> transpose(a)
[[x, t], [y, sin(x)], [z, 0]]
Examples on higher dimensions:
>>> b = Array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
>>> permutedims(b, (2, 1, 0))
[[[1, 5], [3, 7]], [[2, 6], [4, 8]]]
>>> permutedims(b, (1, 2, 0))
[[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
``Permutation`` objects are also allowed:
>>> permutedims(b, Permutation([1, 2, 0]))
[[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
"""
if not isinstance(expr, NDimArray):
raise TypeError('expression has to be an N-dim array')
if not isinstance(perm, Permutation):
perm = Permutation(list(perm))
if perm.size != expr.rank():
raise ValueError('wrong permutation size')
# Get the inverse permutation:
iperm = ~perm
indices_span = perm([range(i) for i in expr.shape])
new_array = [None]*len(expr)
for i, idx in enumerate(itertools.product(*indices_span)):
t = iperm(idx)
new_array[i] = expr[t]
new_shape = perm(expr.shape)
return expr.func(new_array, new_shape)
| bsd-3-clause | 351b4bf2e04f6f517c184788665a1b4d | 29.477099 | 106 | 0.556418 | 3.102176 | false | false | false | false |
diofant/diofant | diofant/ntheory/residue_ntheory.py | 1 | 26568 | import collections
import math
import random
from ..core import Function, Integer
from ..core.compatibility import as_int
from ..core.numbers import igcdex, mod_inverse
from ..utilities.iterables import cantor_product
from .factor_ import factorint, multiplicity, totient, trailing
from .modular import crt, crt1, crt2
from .primetest import isprime
def n_order(a, n):
"""Returns the order of ``a`` modulo ``n``.
The order of ``a`` modulo ``n`` is the smallest integer
``k`` such that ``a**k`` leaves a remainder of 1 with ``n``.
Examples
========
>>> n_order(3, 7)
6
>>> n_order(4, 7)
3
"""
a, n = as_int(a), as_int(n)
if math.gcd(a, n) != 1:
raise ValueError('The two numbers should be relatively prime')
factors = collections.defaultdict(int)
f = factorint(n)
for px, kx in f.items():
if kx > 1:
factors[px] += kx - 1
fpx = factorint(px - 1)
for py, ky in fpx.items():
factors[py] += ky
group_order = 1
for px, kx in factors.items():
group_order *= px**kx
order = 1
if a > n:
a = a % n
for p, e in factors.items():
exponent = group_order
for f in range(e + 1):
if pow(a, exponent, n) != 1:
order *= p ** (e - f + 1)
break
exponent = exponent // p
return order
def _primitive_root_prime_iter(p):
"""Generates the primitive roots for a prime ``p``
References
==========
* W. Stein "Elementary Number Theory" (2011), page 44
Examples
========
>>> list(_primitive_root_prime_iter(19))
[2, 3, 10, 13, 14, 15]
"""
p = as_int(p)
v = [(p - 1) // i for i in factorint(p - 1)]
a = 2
while a < p:
for pw in v:
if pow(a, pw, p) == 1:
break
else:
yield a
a += 1
def primitive_root(p):
"""Returns the smallest primitive root or None.
References
==========
* W. Stein "Elementary Number Theory" (2011), page 44
* P. Hackman "Elementary Number Theory" (2009), Chapter C
Parameters
==========
p : positive integer
Examples
========
>>> primitive_root(19)
2
"""
p = as_int(p)
if p < 1:
raise ValueError('p is required to be positive')
if p <= 2:
return 1
f = factorint(p)
if len(f) > 2:
return
if len(f) == 2:
if 2 not in f or f[2] > 1:
return
# case p = 2*p1**k, p1 prime
for p1 in f: # pragma: no branch
if p1 != 2:
break
i = 1
while i < p: # pragma: no branch
i += 2
if i % p1 == 0:
continue
if is_primitive_root(i, p):
return i
else:
if 2 in f:
if p == 4:
return 3
return
p1, n = list(f.items())[0]
if n > 1:
# see Ref [2], page 81
g = primitive_root(p1)
if is_primitive_root(g, p1**2):
return g
else:
for i in range(2, g + p1 + 1): # pragma: no branch
if math.gcd(i, p) == 1 and is_primitive_root(i, p):
return i
return next(_primitive_root_prime_iter(p))
def is_primitive_root(a, p):
"""Returns True if ``a`` is a primitive root of ``p``
``a`` is said to be the primitive root of ``p`` if gcd(a, p) == 1 and
totient(p) is the smallest positive number s.t.::
a**totient(p) cong 1 mod(p)
Examples
========
>>> is_primitive_root(3, 10)
True
>>> is_primitive_root(9, 10)
False
>>> n_order(3, 10) == totient(10)
True
>>> n_order(9, 10) == totient(10)
False
"""
a, p = as_int(a), as_int(p)
if math.gcd(a, p) != 1:
raise ValueError('The two numbers should be relatively prime')
if a > p:
a = a % p
return n_order(a, p) == totient(p)
def _sqrt_mod_tonelli_shanks(a, p):
"""Returns the square root in the case of ``p`` prime with ``p == 1 (mod 8)``
References
==========
* R. Crandall and C. Pomerance "Prime Numbers", 2nt Ed., page 101
"""
s = trailing(p - 1)
t = p >> s
# find a non-quadratic residue
while 1:
d = random.randint(2, p - 1)
r = legendre_symbol(d, p)
if r == -1:
break
# assert legendre_symbol(d, p) == -1
A = pow(a, t, p)
D = pow(d, t, p)
m = 0
for i in range(s):
adm = A*pow(D, m, p) % p
adm = pow(adm, 2**(s - 1 - i), p)
if adm % p == p - 1:
m += 2**i
# assert A*pow(D, m, p) % p == 1
x = pow(a, (t + 1)//2, p)*pow(D, m//2, p) % p
return x
def sqrt_mod(a, p, all_roots=False):
"""Find a root of ``x**2 = a mod p``.
Parameters
==========
a : integer
p : positive integer
all_roots : if True the list of roots is returned or None
Notes
=====
If there is no root it is returned None; else the returned root
is less or equal to ``p // 2``; in general is not the smallest one.
It is returned ``p // 2`` only if it is the only root.
Use ``all_roots`` only when it is expected that all the roots fit
in memory; otherwise use ``sqrt_mod_iter``.
Examples
========
>>> sqrt_mod(11, 43)
21
>>> sqrt_mod(17, 32, True)
[7, 9, 23, 25]
"""
if all_roots:
return sorted(sqrt_mod_iter(a, p))
try:
p = abs(as_int(p))
it = sqrt_mod_iter(a, p)
r = next(it)
if r > p // 2:
return p - r
elif r < p // 2:
return r
else:
try:
r = next(it)
if r > p // 2:
return p - r
except StopIteration:
pass
return r
except StopIteration:
return
def sqrt_mod_iter(a, p, domain=int):
"""Iterate over solutions to ``x**2 = a mod p``.
Parameters
==========
a : integer
p : positive integer
domain : integer domain, ``int``, ``ZZ`` or ``Integer``
Examples
========
>>> list(sqrt_mod_iter(11, 43))
[21, 22]
"""
from ..domains import ZZ
a, p = as_int(a), abs(as_int(p))
if isprime(p):
a = a % p
if a == 0:
res = _sqrt_mod1(a, p, 1)
else:
res = _sqrt_mod_prime_power(a, p, 1)
if res:
if domain is ZZ:
for x in res:
yield x
else:
for x in res:
yield domain(x)
else:
f = factorint(p)
v = []
pv = []
for px, ex in f.items():
if a % px == 0:
rx = _sqrt_mod1(a, px, ex)
if not rx:
return
else:
rx = _sqrt_mod_prime_power(a, px, ex)
if not rx:
return
v.append(rx)
pv.append(px**ex)
mm, e, s = crt1(pv)
if domain is ZZ:
for vx in cantor_product(*v):
r = crt2(pv, vx, mm, e, s)[0]
yield r
else:
for vx in cantor_product(*v):
r = crt2(pv, vx, mm, e, s)[0]
yield domain(r)
def _sqrt_mod_prime_power(a, p, k):
"""Find the solutions to ``x**2 = a mod p**k`` when ``a % p != 0``.
Parameters
==========
a : integer
p : prime number
k : positive integer
References
==========
* P. Hackman "Elementary Number Theory" (2009), page 160
* http://www.numbertheory.org/php/squareroot.html
* :cite:`Gathen1999modern`
Examples
========
>>> _sqrt_mod_prime_power(11, 43, 1)
[21, 22]
"""
from ..domains import ZZ
assert k > 0
pk = p**k
a = a % pk
if k == 1:
if p == 2:
return [ZZ(a)]
if not is_quad_residue(a, p):
return
if p % 4 == 3:
res = pow(a, (p + 1) // 4, p)
elif p % 8 == 5:
sign = pow(a, (p - 1) // 4, p)
if sign == 1:
res = pow(a, (p + 3) // 8, p)
else:
b = pow(4*a, (p - 5) // 8, p)
x = (2*a*b) % p
assert pow(x, 2, p) == a
res = x
else:
res = _sqrt_mod_tonelli_shanks(a, p)
# ``_sqrt_mod_tonelli_shanks(a, p)`` is not deterministic;
# sort to get always the same result
return sorted([ZZ(res), ZZ(p - res)])
# see Ref.[2]
if p == 2:
if a % 8 != 1:
return
if k <= 3:
s = set()
for i in range(0, pk, 4):
s.add(1 + i)
s.add(-1 + i)
return list(s)
# according to Ref.[2] for k > 2 there are two solutions
# (mod 2**k-1), that is four solutions (mod 2**k), which can be
# obtained from the roots of x**2 = 0 (mod 8)
rv = [ZZ(1), ZZ(3), ZZ(5), ZZ(7)]
# hensel lift them to solutions of x**2 = 0 (mod 2**k)
# if r**2 - a = 0 mod 2**nx but not mod 2**(nx+1)
# then r + 2**(nx - 1) is a root mod 2**(nx+1)
n = 3
res = []
for r in rv:
nx = n
while nx < k:
r1 = (r**2 - a) >> nx
if r1 % 2:
r = r + (1 << (nx - 1))
assert (r**2 - a) % (1 << (nx + 1)) == 0
nx += 1
if r not in res:
res.append(r)
x = r + (1 << (k - 1))
assert (x**2 - a) % pk == 0
if x < (1 << nx) and x not in res:
res.append(x)
return res
rv = _sqrt_mod_prime_power(a, p, 1)
if not rv:
return
r = rv[0]
fr = r**2 - a
# hensel lifting with Newton iteration, see Ref.[3] chapter 9
# with f(x) = x**2 - a; one has f'(a) != 0 (mod p) for p != 2
n = 1
px = p
while 1:
n1 = n
n1 *= 2
if n1 > k:
break
n = n1
px = px**2
frinv = igcdex(2*r, px)[0]
r = (r - fr*frinv) % px
fr = r**2 - a
if n < k:
px = p**k
frinv = igcdex(2*r, px)[0]
r = (r - fr*frinv) % px
return [r, px - r]
def _sqrt_mod1(a, p, n):
"""Find solution to ``x**2 == a mod p**n`` when ``a % p == 0``
References
==========
* http://www.numbertheory.org/php/squareroot.html
"""
pn = p**n
a = a % pn
if a == 0:
# case gcd(a, p**k) = p**n
m = n // 2
if n % 2 == 1:
pm1 = p**(m + 1)
def _iter0a():
i = 0
while i < pn:
yield i
i += pm1
return _iter0a()
else:
pm = p**m
def _iter0b():
i = 0
while i < pn:
yield i
i += pm
return _iter0b()
# case gcd(a, p**k) = p**r, r < n
f = factorint(a)
r = f[p]
if r % 2 == 1:
return
m = r // 2
a1 = a >> r
if p == 2:
if n - r == 1:
pnm1 = 1 << (n - m + 1)
pm1 = 1 << (m + 1)
def _iter1():
k = 1 << (m + 2)
i = 1 << m
while i < pnm1:
j = i
while j < pn:
yield j
j += k
i += pm1
return _iter1()
if n - r == 2:
res = _sqrt_mod_prime_power(a1, p, n - r)
if res is None:
return
pnm = 1 << (n - m)
def _iter2():
s = set()
for r in res:
i = 0
while i < pn:
x = (r << m) + i
assert x not in s
s.add(x)
yield x
i += pnm
return _iter2()
else: # n - r > 2
res = _sqrt_mod_prime_power(a1, p, n - r)
if res is None:
return
pnm1 = 1 << (n - m - 1)
def _iter3():
s = set()
for r in res:
i = 0
while i < pn:
x = ((r << m) + i) % pn
if x not in s:
s.add(x)
yield x
i += pnm1
return _iter3()
else:
m = r // 2
a1 = a // p**r
res1 = _sqrt_mod_prime_power(a1, p, n - r)
if res1 is None:
return
pm = p**m
pnr = p**(n-r)
pnm = p**(n-m)
def _iter4():
s = set()
pm = p**m
for rx in res1:
i = 0
while i < pnm:
x = ((rx + i) % pn)
assert x not in s
s.add(x)
yield x*pm
i += pnr
return _iter4()
def is_quad_residue(a, p):
"""
Returns True if ``a`` (mod ``p``) is in the set of squares mod ``p``,
i.e a % p in {i**2 % p for i in range(p)}. If ``p`` is an odd
prime, an iterative method is used to make the determination:
>>> sorted({i**2 % 7 for i in range(7)})
[0, 1, 2, 4]
>>> [j for j in range(7) if is_quad_residue(j, 7)]
[0, 1, 2, 4]
See Also
========
legendre_symbol, jacobi_symbol
"""
a, p = as_int(a), as_int(p)
if p < 1:
raise ValueError('p must be > 0')
if a >= p or a < 0:
a = a % p
if a < 2 or p < 3:
return True
if not isprime(p):
if p % 2 and jacobi_symbol(a, p) == -1:
return False
r = sqrt_mod(a, p)
if r is None:
return False
else:
return True
return pow(a, (p - 1) // 2, p) == 1
def is_nthpow_residue(a, n, m):
"""Returns True if ``x**n == a (mod m)`` has solutions.
References
==========
* P. Hackman "Elementary Number Theory" (2009), page 76
"""
a, n, m = map(as_int, (a, n, m))
if m <= 0:
raise ValueError('m must be > 0')
if n < 0:
raise ValueError('n must be >= 0')
if a < 0:
raise ValueError('a must be >= 0')
if n == 0:
if m == 1:
return False
return a == 1
if n == 1:
return True
if n == 2:
return is_quad_residue(a, m)
return _is_nthpow_residue_bign(a, n, m)
def _is_nthpow_residue_bign(a, n, m):
"""Returns True if ``x**n == a (mod m)`` has solutions for n > 2."""
assert n > 2 and a >= 0 and m > 0
if primitive_root(m) is None:
assert m >= 8
for prime, power in factorint(m).items():
if not _is_nthpow_residue_bign_prime_power(a, n, prime, power):
return False
return True
f = totient(m)
k = f // math.gcd(f, n)
return pow(a, k, m) == 1
def _is_nthpow_residue_bign_prime_power(a, n, p, k):
"""Returns True/False if a solution for ``x**n == a (mod(p**k))``
does/doesn't exist.
"""
assert a >= 0 and n > 2 and isprime(p) and k > 0
if a % p:
if p != 2:
return _is_nthpow_residue_bign(a, n, pow(p, k))
if n & 1:
return True
c = trailing(n)
return a % pow(2, min(c + 2, k)) == 1
else:
a %= pow(p, k)
if not a:
return True
mu = multiplicity(p, a)
if mu % n:
return False
pm = pow(p, mu)
return _is_nthpow_residue_bign_prime_power(a//pm, n, p, k - mu)
def _nthroot_mod2(s, q, p):
f = factorint(q)
v = []
for b, e in f.items():
v.extend([b]*e)
for qx in v:
s = _nthroot_mod1(s, qx, p, False)
return s
def _nthroot_mod1(s, q, p, all_roots):
"""Root of ``x**q = s mod p``, ``p`` prime and ``q`` divides ``p - 1``.
References
==========
* A. M. Johnston "A Generalized qth Root Algorithm"
"""
g = primitive_root(p)
if not isprime(q):
r = _nthroot_mod2(s, q, p)
else:
f = p - 1
assert (p - 1) % q == 0
# determine k
k = 0
while f % q == 0:
k += 1
f = f // q
# find z, x, r1
f1 = igcdex(-f, q)[0] % q
z = f*f1
x = (1 + z) // q
r1 = pow(s, x, p)
s1 = pow(s, f, p)
h = pow(g, f*q, p)
t = discrete_log(p, s1, h)
g2 = pow(g, z*t, p)
g3 = igcdex(g2, p)[0]
r = r1*g3 % p
assert pow(r, q, p) == s
res = [r]
h = pow(g, (p - 1) // q, p)
assert pow(h, q, p) == 1
hx = r
for _ in range(q - 1):
hx = (hx*h) % p
res.append(hx)
if all_roots:
res.sort()
return res
return min(res)
def nthroot_mod(a, n, p, all_roots=False):
"""Find the solutions to ``x**n = a mod p``.
Parameters
==========
a : integer
n : positive integer
p : positive integer
all_roots : if False returns the smallest root, else the list of roots
Examples
========
>>> nthroot_mod(11, 4, 19)
8
>>> nthroot_mod(11, 4, 19, True)
[8, 11]
>>> nthroot_mod(68, 3, 109)
23
"""
if n == 2:
return sqrt_mod(a, p, all_roots)
# see Hackman "Elementary Number Theory" (2009), page 76
if not is_nthpow_residue(a, n, p):
return
if primitive_root(p) is None:
raise NotImplementedError('Not Implemented for m without primitive root')
if (p - 1) % n == 0:
return _nthroot_mod1(a, n, p, all_roots)
# The roots of ``x**n - a = 0 (mod p)`` are roots of
# ``gcd(x**n - a, x**(p - 1) - 1) = 0 (mod p)``
pa = n
pb = p - 1
b = 1
if pa < pb:
a, pa, b, pb = b, pb, a, pa
while pb:
# x**pa - a = 0; x**pb - b = 0
# x**pa - a = x**(q*pb + r) - a = (x**pb)**q * x**r - a =
# b**q * x**r - a; x**r - c = 0; c = b**-q * a mod p
q, r = divmod(pa, pb)
c = pow(b, q, p)
c = igcdex(c, p)[0]
c = (c * a) % p
pa, pb = pb, r
a, b = b, c
if pa == 1:
if all_roots:
res = [a]
else:
res = a
elif pa == 2:
return sqrt_mod(a, p, all_roots)
else:
res = _nthroot_mod1(a, pa, p, all_roots)
return res
def quadratic_residues(p):
"""Returns the list of quadratic residues.
Examples
========
>>> quadratic_residues(7)
[0, 1, 2, 4]
"""
r = set()
for i in range(p // 2 + 1):
r.add(pow(i, 2, p))
return sorted(r)
def legendre_symbol(a, p):
r"""Returns the Legendre symbol `(a / p)`.
For an integer ``a`` and an odd prime ``p``, the Legendre symbol is
defined as
.. math ::
\genfrac(){}{}{a}{p} = \begin{cases}
0 & \text{if } p \text{ divides } a\\
1 & \text{if } a \text{ is a quadratic residue modulo } p\\
-1 & \text{if } a \text{ is a quadratic nonresidue modulo } p
\end{cases}
Parameters
==========
a : integer
p : odd prime
Examples
========
>>> [legendre_symbol(i, 7) for i in range(7)]
[0, 1, 1, -1, 1, -1, -1]
>>> sorted({i**2 % 7 for i in range(7)})
[0, 1, 2, 4]
See Also
========
is_quad_residue, jacobi_symbol
References
==========
* https://en.wikipedia.org/wiki/Legendre_symbol
"""
a, p = as_int(a), as_int(p)
if not isprime(p) or p == 2:
raise ValueError('p should be an odd prime')
a = a % p
if not a:
return 0
if is_quad_residue(a, p):
return 1
return -1
def jacobi_symbol(m, n):
r"""
Returns the Jacobi symbol `(m / n)`.
For any integer ``m`` and any positive odd integer ``n`` the Jacobi symbol
is defined as the product of the Legendre symbols corresponding to the
prime factors of ``n``:
.. math ::
\genfrac(){}{}{m}{n} =
\genfrac(){}{}{m}{p^{1}}^{\alpha_1}
\genfrac(){}{}{m}{p^{2}}^{\alpha_2}
...
\genfrac(){}{}{m}{p^{k}}^{\alpha_k}
\text{ where } n =
p_1^{\alpha_1}
p_2^{\alpha_2}
...
p_k^{\alpha_k}
Like the Legendre symbol, if the Jacobi symbol `\genfrac(){}{}{m}{n} = -1`
then ``m`` is a quadratic nonresidue modulo ``n``.
But, unlike the Legendre symbol, if the Jacobi symbol
`\genfrac(){}{}{m}{n} = 1` then ``m`` may or may not be a quadratic residue
modulo ``n``.
Parameters
==========
m : integer
n : odd positive integer
Examples
========
>>> jacobi_symbol(45, 77)
-1
>>> jacobi_symbol(60, 121)
1
The relationship between the ``jacobi_symbol`` and ``legendre_symbol`` can
be demonstrated as follows:
>>> L = legendre_symbol
>>> Integer(45).factors()
{3: 2, 5: 1}
>>> jacobi_symbol(7, 45) == L(7, 3)**2 * L(7, 5)**1
True
See Also
========
is_quad_residue, legendre_symbol
"""
m, n = as_int(m), as_int(n)
if not n % 2:
raise ValueError('n should be an odd integer')
if m < 0 or m > n:
m = m % n
if not m:
return int(n == 1)
if n == 1 or m == 1:
return 1
if math.gcd(m, n) != 1:
return 0
j = 1
s = trailing(m)
m = m >> s
if s % 2 and n % 8 in [3, 5]:
j *= -1
while m != 1:
if m % 4 == 3 and n % 4 == 3:
j *= -1
m, n = n % m, m
s = trailing(m)
m = m >> s
if s % 2 and n % 8 in [3, 5]:
j *= -1
return j
class mobius(Function):
"""Möbius function maps natural number to {-1, 0, 1}
It is defined as follows:
1) `1` if `n = 1`.
2) `0` if `n` has a squared prime factor.
3) `(-1)^k` if `n` is a square-free positive integer with `k`
number of prime factors.
It is an important multiplicative function in number theory
and combinatorics. It has applications in mathematical series,
algebraic number theory and also physics (Fermion operator has very
concrete realization with Möbius Function model).
Parameters
==========
n : positive integer
Examples
========
>>> mobius(13*7)
1
>>> mobius(1)
1
>>> mobius(13*7*5)
-1
>>> mobius(13**2)
0
References
==========
* https://en.wikipedia.org/wiki/M%C3%B6bius_function
* Thomas Koshy "Elementary Number Theory with Applications"
"""
@classmethod
def eval(cls, n):
if n.is_integer:
if n.is_positive is not True:
raise ValueError('n should be a positive integer')
else:
raise TypeError('n should be an integer')
if n.is_prime:
return Integer(-1)
elif n == 1:
return Integer(1)
elif n.is_Integer:
a = factorint(n)
if any(i > 1 for i in a.values()):
return Integer(0)
return Integer(-1)**len(a)
def _discrete_log_trial_mul(n, a, b, order=None):
"""
Trial multiplication algorithm for computing the discrete logarithm of
``a`` to the base ``b`` modulo ``n``.
The algorithm finds the discrete logarithm using exhaustive search. This
naive method is used as fallback algorithm of ``discrete_log`` when the
group order is very small.
"""
a %= n
b %= n
if order is None:
order = n
x = 1
for i in range(order):
if x == a:
return i
x = x * b % n
raise ValueError('Log does not exist')
def _discrete_log_shanks_steps(n, a, b, order=None):
"""
Baby-step giant-step algorithm for computing the discrete logarithm of
``a`` to the base ``b`` modulo ``n``.
The algorithm is a time-memory trade-off of the method of exhaustive
search. It uses `O(sqrt(m))` memory, where `m` is the group order.
"""
a %= n
b %= n
if order is None:
order = n_order(b, n)
m = math.isqrt(order) + 1
T = {}
x = 1
for i in range(m):
T[x] = i
x = x * b % n
z = mod_inverse(b, n)
z = pow(z, m, n)
x = a
for i in range(m):
if x in T:
return i * m + T[x]
x = x * z % n
raise ValueError('Log does not exist')
def _discrete_log_pohlig_hellman(n, a, b, order=None):
"""
Pohlig-Hellman algorithm for computing the discrete logarithm of ``a`` to
the base ``b`` modulo ``n``.
In order to compute the discrete logarithm, the algorithm takes advantage
of the factorization of the group order. It is more efficient when the
group order factors into many small primes.
"""
a %= n
b %= n
if order is None:
order = n_order(b, n)
f = factorint(order)
l = [0] * len(f)
for i, (pi, ri) in enumerate(f.items()):
for j in range(ri):
gj = pow(b, l[i], n)
aj = pow(a * mod_inverse(gj, n), order // pi**(j + 1), n)
bj = pow(b, order // pi, n)
cj = discrete_log(n, aj, bj, pi, True)
l[i] += cj * pi**j
d, _ = crt([pi**ri for pi, ri in f.items()], l)
return d
def discrete_log(n, a, b, order=None, prime_order=None):
"""
Compute the discrete logarithm of ``a`` to the base ``b`` modulo ``n``.
This is a recursive function to reduce the discrete logarithm problem in
cyclic groups of composite order to the problem in cyclic groups of
prime order.
Notes
=====
It employs different algorithms depending on the problem (subgroup order
size, prime order or not):
* Trial multiplication
* Baby-step giant-step
* Pohlig-Hellman
References
==========
* https://mathworld.wolfram.com/DiscreteLogarithm.html
* :cite:`Menezes97`
Examples
========
>>> discrete_log(41, 15, 7)
3
"""
if order is None:
order = n_order(b, n)
if prime_order is None:
prime_order = isprime(order)
if order < 1000:
return _discrete_log_trial_mul(n, a, b, order)
elif prime_order:
return _discrete_log_shanks_steps(n, a, b, order)
return _discrete_log_pohlig_hellman(n, a, b, order)
| bsd-3-clause | b5c3d3a78eee21cea4be64a814f4ab68 | 23.305581 | 81 | 0.449974 | 3.274498 | false | false | false | false |
diofant/diofant | diofant/functions/special/spherical_harmonics.py | 1 | 8598 | from ...core import Dummy, Function, I, pi
from ...core.function import ArgumentIndexError
from ..combinatorial.factorials import factorial
from ..elementary.complexes import Abs
from ..elementary.exponential import exp
from ..elementary.miscellaneous import sqrt
from ..elementary.trigonometric import cos, cot, sin
from .polynomials import assoc_legendre
_x = Dummy('dummy_for_spherical_harmonics')
class Ynm(Function):
r"""
Spherical harmonics defined as
.. math::
Y_n^m(\theta, \varphi) := \sqrt{\frac{(2n+1)(n-m)!}{4\pi(n+m)!}}
\exp(i m \varphi)
\mathrm{P}_n^m\left(\cos(\theta)\right)
Ynm() gives the spherical harmonic function of order `n` and `m`
in `\theta` and `\varphi`, `Y_n^m(\theta, \varphi)`. The four
parameters are as follows: `n \geq 0` an integer and `m` an integer
such that `-n \leq m \leq n` holds. The two angles are real-valued
with `\theta \in [0, \pi]` and `\varphi \in [0, 2\pi]`.
Examples
========
>>> theta = Symbol('theta')
>>> phi = Symbol('phi')
>>> Ynm(n, m, theta, phi)
Ynm(n, m, theta, phi)
Several symmetries are known, for the order
>>> theta = Symbol('theta')
>>> phi = Symbol('phi')
>>> Ynm(n, -m, theta, phi)
(-1)**m*E**(-2*I*m*phi)*Ynm(n, m, theta, phi)
as well as for the angles
>>> theta = Symbol('theta')
>>> phi = Symbol('phi')
>>> Ynm(n, m, -theta, phi)
Ynm(n, m, theta, phi)
>>> Ynm(n, m, theta, -phi)
E**(-2*I*m*phi)*Ynm(n, m, theta, phi)
For specific integers n and m we can evaluate the harmonics
to more useful expressions
>>> simplify(Ynm(0, 0, theta, phi).expand(func=True))
1/(2*sqrt(pi))
>>> simplify(Ynm(1, -1, theta, phi).expand(func=True))
sqrt(6)*E**(-I*phi)*sin(theta)/(4*sqrt(pi))
>>> simplify(Ynm(1, 0, theta, phi).expand(func=True))
sqrt(3)*cos(theta)/(2*sqrt(pi))
>>> simplify(Ynm(1, 1, theta, phi).expand(func=True))
-sqrt(6)*E**(I*phi)*sin(theta)/(4*sqrt(pi))
>>> simplify(Ynm(2, -2, theta, phi).expand(func=True))
sqrt(30)*E**(-2*I*phi)*sin(theta)**2/(8*sqrt(pi))
>>> simplify(Ynm(2, -1, theta, phi).expand(func=True))
sqrt(30)*E**(-I*phi)*sin(2*theta)/(8*sqrt(pi))
>>> simplify(Ynm(2, 0, theta, phi).expand(func=True))
sqrt(5)*(3*cos(theta)**2 - 1)/(4*sqrt(pi))
>>> simplify(Ynm(2, 1, theta, phi).expand(func=True))
-sqrt(30)*E**(I*phi)*sin(2*theta)/(8*sqrt(pi))
>>> simplify(Ynm(2, 2, theta, phi).expand(func=True))
sqrt(30)*E**(2*I*phi)*sin(theta)**2/(8*sqrt(pi))
We can differentiate the functions with respect
to both angles
>>> theta = Symbol('theta')
>>> phi = Symbol('phi')
>>> diff(Ynm(n, m, theta, phi), theta)
m*cot(theta)*Ynm(n, m, theta, phi) + E**(-I*phi)*sqrt((-m + n)*(m + n + 1))*Ynm(n, m + 1, theta, phi)
>>> diff(Ynm(n, m, theta, phi), phi)
I*m*Ynm(n, m, theta, phi)
Further we can compute the complex conjugation
>>> theta = Symbol('theta')
>>> phi = Symbol('phi')
>>> m = Symbol('m')
>>> conjugate(Ynm(n, m, theta, phi))
(-1)**(2*m)*E**(-2*I*m*phi)*Ynm(n, m, theta, phi)
To get back the well known expressions in spherical
coordinates we use full expansion
>>> theta = Symbol('theta')
>>> phi = Symbol('phi')
>>> expand_func(Ynm(n, m, theta, phi))
E**(I*m*phi)*sqrt((2*n + 1)*factorial(-m + n)/factorial(m + n))*assoc_legendre(n, m, cos(theta))/(2*sqrt(pi))
See Also
========
diofant.functions.special.spherical_harmonics.Ynm_c
diofant.functions.special.spherical_harmonics.Znm
References
==========
* https://en.wikipedia.org/wiki/Spherical_harmonics
* https://mathworld.wolfram.com/SphericalHarmonic.html
* http://functions.wolfram.com/Polynomials/SphericalHarmonicY/
* https://dlmf.nist.gov/14.30
"""
@classmethod
def eval(cls, n, m, theta, phi):
# Handle negative index m and arguments theta, phi
if m.could_extract_minus_sign():
m = -m
return (-1)**m * exp(-2*I*m*phi) * Ynm(n, m, theta, phi)
if theta.could_extract_minus_sign():
theta = -theta
return Ynm(n, m, theta, phi)
if phi.could_extract_minus_sign():
phi = -phi
return exp(-2*I*m*phi) * Ynm(n, m, theta, phi)
# TODO Add more simplififcation here
def _eval_expand_func(self, **hints):
n, m, theta, phi = self.args
rv = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) *
exp(I*m*phi) * assoc_legendre(n, m, cos(theta)))
# We can do this because of the range of theta
return rv.subs({sqrt(-cos(theta)**2 + 1): sin(theta)})
def fdiff(self, argindex=4):
if argindex == 3:
# Diff wrt theta
n, m, theta, phi = self.args
return (m * cot(theta) * Ynm(n, m, theta, phi) +
sqrt((n - m)*(n + m + 1)) * exp(-I*phi) * Ynm(n, m + 1, theta, phi))
elif argindex == 4:
# Diff wrt phi
n, m, theta, phi = self.args
return I * m * Ynm(n, m, theta, phi)
else: # diff wrt n, m, etc
raise ArgumentIndexError(self, argindex)
def _eval_rewrite_as_sin(self, n, m, theta, phi):
return self.rewrite(cos)
def _eval_rewrite_as_cos(self, n, m, theta, phi):
# This method can be expensive due to extensive use of simplification!
from ...simplify import simplify, trigsimp
# TODO: Make sure n \in N
# TODO: Assert |m| <= n ortherwise we should return 0
term = simplify(self.expand(func=True))
# We can do this because of the range of theta
term = term.xreplace({Abs(sin(theta)): sin(theta)})
return simplify(trigsimp(term))
def _eval_conjugate(self):
# TODO: Make sure theta \in R and phi \in R
n, m, theta, phi = self.args
return (-1)**m * self.func(n, -m, theta, phi)
def as_real_imag(self, deep=True, **hints):
# TODO: Handle deep and hints
n, m, theta, phi = self.args
re = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) *
cos(m*phi) * assoc_legendre(n, m, cos(theta)))
im = (sqrt((2*n + 1)/(4*pi) * factorial(n - m)/factorial(n + m)) *
sin(m*phi) * assoc_legendre(n, m, cos(theta)))
return re, im
def Ynm_c(n, m, theta, phi):
r"""Conjugate spherical harmonics defined as
.. math::
\overline{Y_n^m(\theta, \varphi)} := (-1)^m Y_n^{-m}(\theta, \varphi)
See Also
========
diofant.functions.special.spherical_harmonics.Ynm
diofant.functions.special.spherical_harmonics.Znm
References
==========
* https://en.wikipedia.org/wiki/Spherical_harmonics
* https://mathworld.wolfram.com/SphericalHarmonic.html
* http://functions.wolfram.com/Polynomials/SphericalHarmonicY/
"""
from .. import conjugate
return conjugate(Ynm(n, m, theta, phi))
class Znm(Function):
r"""
Real spherical harmonics defined as
.. math::
Z_n^m(\theta, \varphi) :=
\begin{cases}
\frac{Y_n^m(\theta, \varphi) + \overline{Y_n^m(\theta, \varphi)}}{\sqrt{2}} &\quad m > 0 \\
Y_n^m(\theta, \varphi) &\quad m = 0 \\
\frac{Y_n^m(\theta, \varphi) - \overline{Y_n^m(\theta, \varphi)}}{i \sqrt{2}} &\quad m < 0 \\
\end{cases}
which gives in simplified form
.. math::
Z_n^m(\theta, \varphi) =
\begin{cases}
\frac{Y_n^m(\theta, \varphi) + (-1)^m Y_n^{-m}(\theta, \varphi)}{\sqrt{2}} &\quad m > 0 \\
Y_n^m(\theta, \varphi) &\quad m = 0 \\
\frac{Y_n^m(\theta, \varphi) - (-1)^m Y_n^{-m}(\theta, \varphi)}{i \sqrt{2}} &\quad m < 0 \\
\end{cases}
See Also
========
diofant.functions.special.spherical_harmonics.Ynm
diofant.functions.special.spherical_harmonics.Ynm_c
References
==========
* https://en.wikipedia.org/wiki/Spherical_harmonics
* https://mathworld.wolfram.com/SphericalHarmonic.html
* http://functions.wolfram.com/Polynomials/SphericalHarmonicY/
"""
@classmethod
def eval(cls, n, m, theta, phi):
if m.is_positive:
zz = (Ynm(n, m, theta, phi) + Ynm_c(n, m, theta, phi))/sqrt(2)
return zz
elif m.is_zero:
return Ynm(n, m, theta, phi)
elif m.is_negative:
zz = (Ynm(n, m, theta, phi) - Ynm_c(n, m, theta, phi))/(sqrt(2)*I)
return zz
| bsd-3-clause | b047f4cee8074f5a5182f8430382b095 | 30.962825 | 113 | 0.558618 | 3.003144 | false | false | false | false |
diofant/diofant | diofant/polys/sqfreetools.py | 1 | 5542 | """Square-free decomposition algorithms and related tools."""
from .polyerrors import DomainError
class _SQF:
"""Mixin class to compute square-free decomposition of polynomials."""
def sqf_list(self, f):
"""
Return square-free decomposition of a polynomial in ``K[X]``.
Examples
========
>>> R, x, y = ring('x y', ZZ)
>>> R.sqf_list(x**5 + 2*x**4*y + x**3*y**2)
(1, [(x + y, 2), (x, 3)])
>>> R, x, y = ring('x y', FF(5))
>>> f = x**5*y**5 + 1
Note that e.g.:
>>> f.diff(x)
0
This phenomenon doesn't happen in characteristic zero. However we can
still compute square-free decomposition of ``f``:
>>> R.sqf_list(f)
(1, [(x*y + 1, 5)])
"""
domain = self.domain
if domain.is_Field:
coeff, f = f.LC, f.monic()
else:
coeff, f = f.primitive()
if domain.is_FiniteField:
return coeff, self._gf_sqf_list(f)
else:
return coeff, self._rr_yun0_sqf_list(f)
def _gf_sqf_list(self, f):
"""
Compute square-free decomposition of the monic ``f`` in ``GF(q)[X]``.
Notes
=====
Uses a modified version of Musser's algorithm for square-free
decomposition of univariate polynomials over finite fields.
References
==========
* :cite:`Geddes1992algorithms`, algorithm 8.3
* :cite:`Musser1971factor`, p.54, algorithm V (modified)
"""
domain = self.domain
n, factors, p = 1, [], int(domain.characteristic)
m = int(domain.order // p)
while not f.is_ground:
df = [f.diff(x) for x in self.gens]
if any(_ for _ in df):
g = f
for q in df:
g = self.gcd(g, q)
h, f, i = f // g, g, 1
while h != 1:
g = self.gcd(f, h)
h //= g
if not h.is_ground:
factors.append((h, i*n))
f //= g
h = g
i += 1
n *= p
g = self.zero
for monom, coeff in f.items():
g[(_ // p for _ in monom)] = coeff**m
f = g
return factors
def _rr_yun0_sqf_list(self, f):
"""Compute square-free decomposition of ``f`` in zero-characteristic ring ``K[X]``.
References
==========
* :cite:`Geddes1992algorithms`, algorithm 8.2
* :cite:`LeeM2013factor`, algorithm 3.1
"""
if f.is_ground:
return []
result, count = [], 1
qs = [f.diff(x) for x in self.gens]
g = f
for q in qs:
g = self.gcd(g, q)
while f != 1:
qs = [q // g for q in qs]
f //= g
qs = [q - f.diff(x) for x, q in zip(self.gens, qs)]
g = f
for q in qs:
g = self.gcd(g, q)
if g != 1:
result.append((g, count))
count += 1
return result
def is_squarefree(self, f):
"""
Return ``True`` if ``f`` is a square-free polynomial in ``K[X]``.
Examples
========
>>> _, x, y = ring('x y', ZZ)
>>> ((x + y)**2).is_squarefree
False
>>> (x**2 + y**2).is_squarefree
True
"""
if f.is_ground:
return True
else:
g = f
for x in self.gens:
g = self.gcd(g, f.diff(x))
if g.is_ground:
return True
return False
def sqf_part(self, f):
"""
Returns square-free part of a polynomial in ``K[X]``.
Examples
========
>>> R, x, y = ring('x y', ZZ)
>>> R.sqf_part(x**3 + 2*x**2*y + x*y**2)
x**2 + x*y
"""
domain = self.domain
if domain.is_FiniteField:
g = self.one
for f, _ in self.sqf_list(f)[1]:
g *= f
return g
if not f:
return f
gcd = f
for x in self.gens:
gcd = self.gcd(gcd, f.diff(x))
sqf = f // gcd
if domain.is_Field:
return sqf.monic()
else:
return sqf.primitive()[1]
def sqf_norm(self, f):
"""
Square-free norm of ``f`` in ``K[X]``, useful over algebraic domains.
Returns ``s``, ``f``, ``r``, such that ``g(x) = f(x-sa)`` and ``r(x) = Norm(g(x))``
is a square-free polynomial over K, where ``a`` is the algebraic extension of ``K``.
Examples
========
>>> _, x, y = ring('x y', QQ.algebraic_field(I))
>>> (x*y + y**2).sqf_norm()
(1, x*y - I*x + y**2 - 3*I*y - 2,
x**2*y**2 + x**2 + 2*x*y**3 + 2*x*y + y**4 + 5*y**2 + 4)
"""
domain = self.domain
if not domain.is_AlgebraicField:
raise DomainError(f'ground domain must be algebraic, got {domain}')
new_ring = self.to_ground().inject(*domain.symbols, front=True)
g = domain.mod.set_ring(new_ring)
s = 0
while True:
h = f.inject(front=True)
r = g.resultant(h)
if r.is_squarefree:
return s, f, r
else:
f = f.compose({x: x - domain.unit for x in self.gens})
s += 1
| bsd-3-clause | 36006d4f0090764c117ab3c28f2c6d05 | 23.200873 | 92 | 0.428726 | 3.559409 | false | false | false | false |
diofant/diofant | diofant/vector/orienters.py | 1 | 11432 | from ..core import Basic, Symbol, cacheit, sympify
from ..functions import cos, sin
from ..matrices import ImmutableMatrix, eye, rot_axis1, rot_axis2, rot_axis3
class Orienter(Basic):
"""Super-class for all orienter classes."""
def rotation_matrix(self):
"""
The rotation matrix corresponding to this orienter
instance.
"""
return self._parent_orient
class AxisOrienter(Orienter):
"""Class to denote an axis orienter."""
def __new__(cls, angle, axis):
from .vector import Vector
if not isinstance(axis, Vector):
raise TypeError('axis should be a Vector')
angle = sympify(angle)
obj = super().__new__(cls, angle, axis)
obj._angle = angle
obj._axis = axis
return obj
def __init__(self, angle, axis):
"""
Axis rotation is a rotation about an arbitrary axis by
some angle. The angle is supplied as a Diofant expr scalar, and
the axis is supplied as a Vector.
Parameters
==========
angle : Expr
The angle by which the new system is to be rotated
axis : Vector
The axis around which the rotation has to be performed
Examples
========
>>> from diofant.vector import CoordSysCartesian
>>> q1 = symbols('q1')
>>> N = CoordSysCartesian('N')
>>> orienter = AxisOrienter(q1, N.i + 2 * N.j)
>>> B = N.orient_new('B', [orienter])
"""
# Dummy initializer for docstrings
@cacheit
def rotation_matrix(self, system):
"""
The rotation matrix corresponding to this orienter
instance.
Parameters
==========
system : CoordSysCartesian
The coordinate system wrt which the rotation matrix
is to be computed
"""
from .functions import express
axis = express(self.axis, system).normalize()
axis = axis.to_matrix(system)
theta = self.angle
parent_orient = ((eye(3) - axis * axis.T) * cos(theta) +
ImmutableMatrix([[0, -axis[2], axis[1]],
[axis[2], 0, -axis[0]],
[-axis[1], axis[0], 0]]) *
sin(theta) + axis * axis.T)
parent_orient = parent_orient.T
return parent_orient
@property
def angle(self):
return self._angle
@property
def axis(self):
return self._axis
class ThreeAngleOrienter(Orienter):
"""Super-class for Body and Space orienters."""
def __new__(cls, angle1, angle2, angle3, rot_order):
approved_orders = ('123', '231', '312', '132', '213',
'321', '121', '131', '212', '232',
'313', '323', '')
original_rot_order = rot_order
rot_order = str(rot_order).upper()
if len(rot_order) != 3:
raise TypeError('rot_order should be a str of length 3')
rot_order = [i.replace('X', '1') for i in rot_order]
rot_order = [i.replace('Y', '2') for i in rot_order]
rot_order = [i.replace('Z', '3') for i in rot_order]
rot_order = ''.join(rot_order)
if rot_order not in approved_orders:
raise TypeError('Invalid rot_type parameter')
a1 = int(rot_order[0])
a2 = int(rot_order[1])
a3 = int(rot_order[2])
angle1 = sympify(angle1)
angle2 = sympify(angle2)
angle3 = sympify(angle3)
if cls._in_order:
parent_orient = (_rot(a1, angle1) *
_rot(a2, angle2) *
_rot(a3, angle3))
else:
parent_orient = (_rot(a3, angle3) *
_rot(a2, angle2) *
_rot(a1, angle1))
parent_orient = parent_orient.T
if not isinstance(original_rot_order, Symbol):
original_rot_order = Symbol(original_rot_order)
obj = super().__new__(cls, angle1, angle2, angle3, original_rot_order)
obj._angle1 = angle1
obj._angle2 = angle2
obj._angle3 = angle3
obj._rot_order = str(original_rot_order)
obj._parent_orient = parent_orient
return obj
@property
def angle1(self):
return self._angle1
@property
def angle2(self):
return self._angle2
@property
def angle3(self):
return self._angle3
@property
def rot_order(self):
return self._rot_order
class BodyOrienter(ThreeAngleOrienter):
"""Class to denote a body-orienter."""
_in_order = True
def __new__(cls, angle1, angle2, angle3, rot_order):
obj = ThreeAngleOrienter.__new__(cls, angle1, angle2, angle3,
rot_order)
return obj
def __init__(self, angle1, angle2, angle3, rot_order):
"""
Body orientation takes this coordinate system through three
successive simple rotations.
Body fixed rotations include both Euler Angles and
Tait-Bryan Angles, see https://en.wikipedia.org/wiki/Euler_angles.
Parameters
==========
angle1, angle2, angle3 : Expr
Three successive angles to rotate the coordinate system by
rotation_order : string
String defining the order of axes for rotation
Examples
========
>>> from diofant.vector import CoordSysCartesian
>>> q1, q2, q3 = symbols('q1 q2 q3')
>>> N = CoordSysCartesian('N')
A 'Body' fixed rotation is described by three angles and
three body-fixed rotation axes. To orient a coordinate system D
with respect to N, each sequential rotation is always about
the orthogonal unit vectors fixed to D. For example, a '123'
rotation will specify rotations about N.i, then D.j, then
D.k. (Initially, D.i is same as N.i)
Therefore,
>>> body_orienter = BodyOrienter(q1, q2, q3, '123')
>>> D = N.orient_new('D', [body_orienter])
is same as
>>> axis_orienter1 = AxisOrienter(q1, N.i)
>>> D = N.orient_new('D', [axis_orienter1])
>>> axis_orienter2 = AxisOrienter(q2, D.j)
>>> D = D.orient_new('D', [axis_orienter2])
>>> axis_orienter3 = AxisOrienter(q3, D.k)
>>> D = D.orient_new('D', [axis_orienter3])
Acceptable rotation orders are of length 3, expressed in XYZ or
123, and cannot have a rotation about about an axis twice in a row.
>>> body_orienter1 = BodyOrienter(q1, q2, q3, '123')
>>> body_orienter2 = BodyOrienter(q1, q2, 0, 'ZXZ')
>>> body_orienter3 = BodyOrienter(0, 0, 0, 'XYX')
"""
# Dummy initializer for docstrings
class SpaceOrienter(ThreeAngleOrienter):
"""Class to denote a space-orienter."""
_in_order = False
def __new__(cls, angle1, angle2, angle3, rot_order):
obj = ThreeAngleOrienter.__new__(cls, angle1, angle2, angle3,
rot_order)
return obj
def __init__(self, angle1, angle2, angle3, rot_order):
"""
Space rotation is similar to Body rotation, but the rotations
are applied in the opposite order.
Parameters
==========
angle1, angle2, angle3 : Expr
Three successive angles to rotate the coordinate system by
rotation_order : string
String defining the order of axes for rotation
See Also
========
BodyOrienter : Orienter to orient systems wrt Euler angles.
Examples
========
>>> from diofant.vector import CoordSysCartesian
>>> q1, q2, q3 = symbols('q1 q2 q3')
>>> N = CoordSysCartesian('N')
To orient a coordinate system D with respect to N, each
sequential rotation is always about N's orthogonal unit vectors.
For example, a '123' rotation will specify rotations about
N.i, then N.j, then N.k.
Therefore,
>>> space_orienter = SpaceOrienter(q1, q2, q3, '312')
>>> D = N.orient_new('D', [space_orienter])
is same as
>>> axis_orienter1 = AxisOrienter(q1, N.i)
>>> B = N.orient_new('B', [axis_orienter1])
>>> axis_orienter2 = AxisOrienter(q2, N.j)
>>> C = B.orient_new('C', [axis_orienter2])
>>> axis_orienter3 = AxisOrienter(q3, N.k)
>>> D = C.orient_new('C', [axis_orienter3])
"""
# Dummy initializer for docstrings
class QuaternionOrienter(Orienter):
"""Class to denote a quaternion-orienter."""
def __new__(cls, q0, q1, q2, q3):
q0 = sympify(q0)
q1 = sympify(q1)
q2 = sympify(q2)
q3 = sympify(q3)
parent_orient = (ImmutableMatrix([[q0 ** 2 + q1 ** 2 - q2 ** 2 -
q3 ** 2,
2 * (q1 * q2 - q0 * q3),
2 * (q0 * q2 + q1 * q3)],
[2 * (q1 * q2 + q0 * q3),
q0 ** 2 - q1 ** 2 +
q2 ** 2 - q3 ** 2,
2 * (q2 * q3 - q0 * q1)],
[2 * (q1 * q3 - q0 * q2),
2 * (q0 * q1 + q2 * q3),
q0 ** 2 - q1 ** 2 -
q2 ** 2 + q3 ** 2]]))
parent_orient = parent_orient.T
obj = super().__new__(cls, q0, q1, q2, q3)
obj._q0 = q0
obj._q1 = q1
obj._q2 = q2
obj._q3 = q3
obj._parent_orient = parent_orient
return obj
def __init__(self, angle1, angle2, angle3, rot_order):
"""
Quaternion orientation orients the new CoordSysCartesian with
Quaternions, defined as a finite rotation about lambda, a unit
vector, by some amount theta.
This orientation is described by four parameters:
q0 = cos(theta/2)
q1 = lambda_x sin(theta/2)
q2 = lambda_y sin(theta/2)
q3 = lambda_z sin(theta/2)
Quaternion does not take in a rotation order.
Parameters
==========
q0, q1, q2, q3 : Expr
The quaternions to rotate the coordinate system by
Examples
========
>>> from diofant.vector import CoordSysCartesian
>>> q0, q1, q2, q3 = symbols('q0 q1 q2 q3')
>>> N = CoordSysCartesian('N')
>>> q_orienter = QuaternionOrienter(q0, q1, q2, q3)
>>> B = N.orient_new('B', [q_orienter])
"""
# Dummy initializer for docstrings
@property
def q0(self):
return self._q0
@property
def q1(self):
return self._q1
@property
def q2(self):
return self._q2
@property
def q3(self):
return self._q3
def _rot(axis, angle):
"""DCM for simple axis 1, 2 or 3 rotations."""
if axis == 1:
return ImmutableMatrix(rot_axis1(angle).T)
elif axis == 2:
return ImmutableMatrix(rot_axis2(angle).T)
elif axis == 3:
return ImmutableMatrix(rot_axis3(angle).T)
else:
raise NotImplementedError
| bsd-3-clause | a4d62864aa5dec2bdf4e0a8b2ad05d88 | 29.648794 | 78 | 0.523443 | 3.860858 | false | false | false | false |
diofant/diofant | diofant/tests/polys/test_polyroots.py | 1 | 26424 | """Tests for algorithms for computing symbolic roots of polynomials."""
import itertools
import mpmath
import pytest
from diofant import (EX, QQ, ZZ, I, Integer, Interval, Piecewise,
PolynomialError, Rational, RootOf, Symbol, Wild, acos,
cbrt, cos, cyclotomic_poly, exp, im, legendre_poly,
nroots, pi, powsimp, re, root, roots, sin, sqrt, symbols)
from diofant.abc import a, b, c, d, e, q, x, y, z
from diofant.polys.polyroots import (preprocess_roots, root_factors,
roots_binomial, roots_cubic,
roots_cyclotomic, roots_linear,
roots_quadratic, roots_quartic,
roots_quintic)
from diofant.polys.polyutils import _nsort
from diofant.utilities.randtest import verify_numerically
__all__ = ()
def test_roots_linear():
assert roots_linear((2*x + 1).as_poly()) == [-Rational(1, 2)]
def test_roots_quadratic():
assert roots_quadratic((2*x**2).as_poly()) == [0, 0]
assert roots_quadratic((2*x**2 + 3*x).as_poly()) == [-Rational(3, 2), 0]
assert roots_quadratic((2*x**2 + 3).as_poly()) == [-I*sqrt(6)/2, I*sqrt(6)/2]
assert roots_quadratic((2*x**2 + 4*x + 3).as_poly()) == [-1 - I*sqrt(2)/2, -1 + I*sqrt(2)/2]
f = x**2 + (2*a*e + 2*c*e)/(a - c)*x + (d - b + a*e**2 - c*e**2)/(a - c)
assert (roots_quadratic(f.as_poly(x)) ==
[-e*(a + c)/(a - c) - sqrt((a*b + 4*a*c*e**2 -
a*d - b*c + c*d)/(a - c)**2),
-e*(a + c)/(a - c) + sqrt((a*b + 4*a*c*e**2 -
a*d - b*c + c*d)/(a - c)**2)])
# check for simplification
f = (y*x**2 - 2*x - 2*y).as_poly(x)
assert roots_quadratic(f) == [-sqrt((2*y**2 + 1)/y**2) + 1/y,
sqrt((2*y**2 + 1)/y**2) + 1/y]
f = (x**2 + (-y**2 - 2)*x + y**2 + 1).as_poly(x)
assert roots_quadratic(f) == [y**2/2 - sqrt(y**4)/2 + 1,
y**2/2 + sqrt(y**4)/2 + 1]
f = (sqrt(2)*x**2 - 1).as_poly(x)
r = roots_quadratic(f)
assert r == _nsort(r)
# issue sympy/sympy#8255
f = (-24*x**2 - 180*x + 264).as_poly()
assert [w.evalf(2) for w in f.all_roots(radicals=True)] == \
[w.evalf(2) for w in f.all_roots(radicals=False)]
for _a, _b, _c in itertools.product((-2, 2), (-2, 2), (0, -1)):
f = (_a*x**2 + _b*x + _c).as_poly()
roots = roots_quadratic(f)
assert roots == _nsort(roots)
def test_sympyissue_8285():
roots = ((4*x**8 - 1).as_poly()*(x**2 + 1).as_poly()).all_roots()
assert roots == _nsort(roots)
f = (x**4 + 5*x**2 + 6).as_poly()
ro = [RootOf(f, i) for i in range(4)]
roots = (x**4 + 5*x**2 + 6).as_poly().all_roots()
assert roots == ro
assert roots == _nsort(roots)
# more than 2 complex roots from which to identify the
# imaginary ones
roots = (2*x**8 - 1).as_poly().all_roots()
assert roots == _nsort(roots)
assert len((2*x**10 - 1).as_poly().all_roots()) == 10 # doesn't fail
def test_sympyissue_8289():
roots = ((x**2 + 2).as_poly()*(x**4 + 2).as_poly()).all_roots()
assert roots == _nsort(roots)
roots = (x**6 + 3*x**3 + 2).as_poly().all_roots()
assert roots == _nsort(roots)
roots = (x**6 - x + 1).as_poly().all_roots()
assert roots == _nsort(roots)
# all imaginary roots
roots = (x**4 + 4*x**2 + 4).as_poly().all_roots()
assert roots == _nsort(roots)
def test_sympyissue_14293():
roots = (x**8 + 2*x**6 + 37*x**4 - 36*x**2 + 324).as_poly().all_roots()
assert roots == _nsort(roots)
def test_roots_cubic():
assert roots_cubic((2*x**3).as_poly()) == [0, 0, 0]
assert roots_cubic((x**3 - 3*x**2 + 3*x - 1).as_poly()) == [1, 1, 1]
assert roots_cubic((x**3 + 1).as_poly()) == \
[-1, Rational(1, 2) - I*sqrt(3)/2, Rational(1, 2) + I*sqrt(3)/2]
assert roots_cubic((2*x**3 - 3*x**2 - 3*x - 1).as_poly())[0] == \
Rational(1, 2) + cbrt(3)/2 + 3**Rational(2, 3)/2
eq = -x**3 + 2*x**2 + 3*x - 2
assert roots(eq, trig=True, multiple=True) == \
roots_cubic(eq.as_poly(), trig=True) == [
Rational(2, 3) + 2*sqrt(13)*cos(acos(8*sqrt(13)/169)/3)/3,
-2*sqrt(13)*sin(-acos(8*sqrt(13)/169)/3 + pi/6)/3 + Rational(2, 3),
-2*sqrt(13)*cos(-acos(8*sqrt(13)/169)/3 + pi/3)/3 + Rational(2, 3),
]
res = roots_cubic((x**3 + 2*a/27).as_poly(x))
assert res == [-root(2, 3)*root(a, 3)/3,
-root(2, 3)*root(a, 3)*(-Rational(1, 2) + sqrt(3)*I/2)/3,
-root(2, 3)*root(a, 3)*(-Rational(1, 2) - sqrt(3)*I/2)/3]
res = roots_cubic((x**3 - 2*a/27).as_poly(x))
assert res == [root(2, 3)*root(a, 3)/3,
root(2, 3)*root(a, 3)*(-Rational(1, 2) + sqrt(3)*I/2)/3,
root(2, 3)*root(a, 3)*(-Rational(1, 2) - sqrt(3)*I/2)/3]
# issue sympy/sympy#8438
p = -3*x**3 - 2*x**2 + x*y + 1
croots = roots_cubic(p.as_poly(x), x)
z = -Rational(3, 2) - 7*I/2 # this will fail in code given in commit msg
post = [r.subs({y: z}) for r in croots]
assert set(post) == set(roots_cubic(p.subs({y: z}).as_poly(x)))
# /!\ if p is not made an expression, this is *very* slow
assert all(p.subs({y: z, x: i}).evalf(2, chop=True) == 0 for i in post)
def test_roots_quartic():
assert roots_quartic((x**4).as_poly()) == [0, 0, 0, 0]
assert roots_quartic((x**4 + x**3).as_poly()) in [
[-1, 0, 0, 0],
[0, -1, 0, 0],
[0, 0, -1, 0],
[0, 0, 0, -1]
]
assert roots_quartic((x**4 - x**3).as_poly()) in [
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
]
lhs = roots_quartic((x**4 + x).as_poly())
rhs = [Rational(1, 2) + I*sqrt(3)/2, Rational(1, 2) - I*sqrt(3)/2, 0, -1]
assert sorted(lhs, key=hash) == sorted(rhs, key=hash)
# test of all branches of roots quartic
for i, (a, b, c, d) in enumerate([(1, 2, 3, 0),
(3, -7, -9, 9),
(1, 2, 3, 4),
(1, 2, 3, 4),
(-7, -3, 3, -6),
(-3, 5, -6, -4),
(6, -5, -10, -3)]):
if i == 2:
c = -a*(a**2/Integer(8) - b/Integer(2))
elif i == 3:
d = a*(a*(3*a**2/Integer(256) - b/Integer(16)) + c/Integer(4))
eq = x**4 + a*x**3 + b*x**2 + c*x + d
ans = roots_quartic(eq.as_poly())
assert all(eq.subs({x: ai}).evalf(chop=True) == 0 for ai in ans)
# not all symbolic quartics are unresolvable
eq = (q*x + q/4 + x**4 + x**3 + 2*x**2 - Rational(1, 3)).as_poly(x)
sol = roots_quartic(eq)
assert all(verify_numerically(eq.subs({x: i}), 0) for i in sol)
z = symbols('z', negative=True)
eq = x**4 + 2*x**3 + 3*x**2 + x*(z + 11) + 5
zans = roots_quartic(eq.as_poly(x))
assert all(verify_numerically(eq.subs({x: i, z: -1}), 0) for i in zans)
# but some are (see also issue sympy/sympy#4989)
# it's ok if the solution is not Piecewise, but the tests below should pass
eq = (y*x**4 + x**3 - x + z).as_poly(x)
ans = roots_quartic(eq)
assert all(type(i) == Piecewise for i in ans)
reps = ({y: -Rational(1, 3), z: -Rational(1, 4)}, # 4 real
{y: -Rational(1, 3), z: -Rational(1, 2)}, # 2 real
{y: -Rational(1, 3), z: -2}) # 0 real
for rep in reps:
sol = roots_quartic(eq.subs(rep).as_poly(x))
assert all(verify_numerically(w.subs(rep) - s, 0) for w, s in zip(ans, sol))
def test_roots_quintic():
assert not roots_quintic((x**5 + x**4 + 1).as_poly())
assert not roots_quintic((x**5 - 6*x + 3).as_poly())
assert not roots_quintic((6*x**5 + 9*x**3 - 10*x**2 - 9*x).as_poly())
def test_roots_cyclotomic():
assert roots_cyclotomic(cyclotomic_poly(1, x, polys=True)) == [1]
assert roots_cyclotomic(cyclotomic_poly(2, x, polys=True)) == [-1]
assert roots_cyclotomic(cyclotomic_poly(
3, x, polys=True)) == [-Rational(1, 2) - I*sqrt(3)/2, -Rational(1, 2) + I*sqrt(3)/2]
assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True)) == [-I, I]
assert roots_cyclotomic(cyclotomic_poly(
6, x, polys=True)) == [Rational(1, 2) - I*sqrt(3)/2, Rational(1, 2) + I*sqrt(3)/2]
assert roots_cyclotomic(cyclotomic_poly(7, x, polys=True)) == [
-cos(pi/7) - I*sin(pi/7),
-cos(pi/7) + I*sin(pi/7),
-cos(3*pi/7) - I*sin(3*pi/7),
-cos(3*pi/7) + I*sin(3*pi/7),
cos(2*pi/7) - I*sin(2*pi/7),
cos(2*pi/7) + I*sin(2*pi/7),
]
assert roots_cyclotomic(cyclotomic_poly(8, x, polys=True)) == [
-sqrt(2)/2 - I*sqrt(2)/2,
-sqrt(2)/2 + I*sqrt(2)/2,
sqrt(2)/2 - I*sqrt(2)/2,
sqrt(2)/2 + I*sqrt(2)/2,
]
assert roots_cyclotomic(cyclotomic_poly(12, x, polys=True)) == [
-sqrt(3)/2 - I/2,
-sqrt(3)/2 + I/2,
sqrt(3)/2 - I/2,
sqrt(3)/2 + I/2,
]
assert roots_cyclotomic(
cyclotomic_poly(1, x, polys=True), factor=True) == [1]
assert roots_cyclotomic(
cyclotomic_poly(2, x, polys=True), factor=True) == [-1]
assert roots_cyclotomic(cyclotomic_poly(3, x, polys=True), factor=True) == \
[-root(-1, 3), -1 + root(-1, 3)]
assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True), factor=True) == \
[-I, I]
assert roots_cyclotomic(cyclotomic_poly(5, x, polys=True), factor=True) == \
[-root(-1, 5), -root(-1, 5)**3, root(-1, 5)**2, -1 - root(-1, 5)**2 + root(-1, 5) + root(-1, 5)**3]
assert roots_cyclotomic(cyclotomic_poly(6, x, polys=True), factor=True) == \
[1 - root(-1, 3), root(-1, 3)]
def test_roots_binomial():
assert roots_binomial((5*x).as_poly()) == [0]
assert roots_binomial((5*x**4).as_poly()) == [0, 0, 0, 0]
assert roots_binomial((5*x + 2).as_poly()) == [-Rational(2, 5)]
A = 10**Rational(3, 4)/10
assert roots_binomial((5*x**4 + 2).as_poly()) == \
[-A - A*I, -A + A*I, A - A*I, A + A*I]
a1 = Symbol('a1', nonnegative=True)
b1 = Symbol('b1', nonnegative=True)
r0 = roots_quadratic((a1*x**2 + b1).as_poly(x))
r1 = roots_binomial((a1*x**2 + b1).as_poly(x))
assert powsimp(r0[0]) == powsimp(r1[0])
assert powsimp(r0[1]) == powsimp(r1[1])
for a, b, s, n in itertools.product((1, 2), (1, 2), (-1, 1), (2, 3, 4, 5)):
if a == b and a != 1: # a == b == 1 is sufficient
continue
p = (a*x**n + s*b).as_poly()
ans = roots_binomial(p)
assert ans == _nsort(ans)
# issue sympy/sympy#8813
assert roots((2*x**3 - 16*y**3).as_poly(x)) == {
2*y*(-Rational(1, 2) - sqrt(3)*I/2): 1,
2*y: 1,
2*y*(-Rational(1, 2) + sqrt(3)*I/2): 1}
p = (exp(I*x/3)**4 + exp(I*x/3)).as_poly(exp(I*x/3))
assert roots(p) == roots(x**4 + x)
def test_roots_preprocessing():
f = a*y*x**2 + y - b
coeff, poly = preprocess_roots(f.as_poly(x))
assert coeff == 1
assert poly == (a*y*x**2 + y - b).as_poly(x)
f = c**3*x**3 + c**2*x**2 + c*x + a
coeff, poly = preprocess_roots(f.as_poly(x))
assert coeff == 1/c
assert poly == (x**3 + x**2 + x + a).as_poly(x)
f = c**3*x**3 + c**2*x**2 + a
coeff, poly = preprocess_roots(f.as_poly(x))
assert coeff == 1/c
assert poly == (x**3 + x**2 + a).as_poly(x)
f = c**3*x**3 + c*x + a
coeff, poly = preprocess_roots(f.as_poly(x))
assert coeff == 1/c
assert poly == (x**3 + x + a).as_poly(x)
f = c**3*x**3 + a
coeff, poly = preprocess_roots(f.as_poly(x))
assert coeff == 1/c
assert poly == (x**3 + a).as_poly(x)
E, F, J, L = symbols('E,F,J,L')
f = -21601054687500000000*E**8*J**8/L**16 + \
508232812500000000*F*x*E**7*J**7/L**14 - \
4269543750000000*E**6*F**2*J**6*x**2/L**12 + \
16194716250000*E**5*F**3*J**5*x**3/L**10 - \
27633173750*E**4*F**4*J**4*x**4/L**8 + \
14840215*E**3*F**5*J**3*x**5/L**6 + \
54794*E**2*F**6*J**2*x**6/(5*L**4) - \
1153*E*J*F**7*x**7/(80*L**2) + \
633*F**8*x**8/160000
coeff, poly = preprocess_roots(f.as_poly(x))
assert coeff == 20*E*J/(F*L**2)
assert poly == 633*x**8 - 115300*x**7 + 4383520*x**6 + 296804300*x**5 - 27633173750*x**4 + \
809735812500*x**3 - 10673859375000*x**2 + 63529101562500*x - 135006591796875
f = J**8 + 7*E*x**2*L**16 + 5*F*x*E**5*J**7*L**2
coeff, poly = preprocess_roots(f.as_poly(x))
assert coeff == 1
assert poly == f.as_poly(x)
f = (-y**2 + x**2*exp(x)).as_poly(y, domain=ZZ.inject(x, exp(x)))
g = (y**2 - exp(x)).as_poly(y, domain=ZZ.inject(exp(x)))
assert preprocess_roots(f) == (x, g)
def test_roots0():
assert roots(1, x) == {}
assert roots(x, x) == {0: 1}
assert roots(x**9, x) == {0: 9}
assert roots(((x - 2)*(x + 3)*(x - 4)).expand(), x) == {-3: 1, 2: 1, 4: 1}
assert roots(x**2 - 2*x + 1, x, auto=False) == {1: 2}
assert roots(2*x + 1, x) == {Rational(-1, 2): 1}
assert roots((2*x + 1)**2, x) == {Rational(-1, 2): 2}
assert roots((2*x + 1)**5, x) == {Rational(-1, 2): 5}
assert roots((2*x + 1)**10, x) == {Rational(-1, 2): 10}
assert roots(x**4 - 1, x) == {I: 1, 1: 1, -1: 1, -I: 1}
assert roots((x**4 - 1)**2, x) == {I: 2, 1: 2, -1: 2, -I: 2}
assert roots(((2*x - 3)**2).expand(), x) == {+Rational(3, 2): 2}
assert roots(((2*x + 3)**2).expand(), x) == {-Rational(3, 2): 2}
assert roots(((2*x - 3)**3).expand(), x) == {+Rational(3, 2): 3}
assert roots(((2*x + 3)**3).expand(), x) == {-Rational(3, 2): 3}
assert roots(((2*x - 3)**5).expand(), x) == {+Rational(3, 2): 5}
assert roots(((2*x + 3)**5).expand(), x) == {-Rational(3, 2): 5}
assert roots(((a*x - b)**5).expand(), x) == {+b/a: 5}
assert roots(((a*x + b)**5).expand(), x) == {-b/a: 5}
assert roots(x**2 + (-a - 1)*x + a, x) == {a: 1, 1: 1}
assert roots(x**4 - 2*x**2 + 1, x) == {1: 2, -1: 2}
assert roots(x**6 - 4*x**4 + 4*x**3 - x**2, x) == \
{1: 2, -1 - sqrt(2): 1, 0: 2, -1 + sqrt(2): 1}
assert roots(x**8 - 1, x) == {
sqrt(2)/2 + I*sqrt(2)/2: 1,
sqrt(2)/2 - I*sqrt(2)/2: 1,
-sqrt(2)/2 + I*sqrt(2)/2: 1,
-sqrt(2)/2 - I*sqrt(2)/2: 1,
1: 1, -1: 1, I: 1, -I: 1
}
f = -2016*x**2 - 5616*x**3 - 2056*x**4 + 3324*x**5 + 2176*x**6 - \
224*x**7 - 384*x**8 - 64*x**9
assert roots(f) == {0: 2, -2: 2, 2: 1, -Rational(7, 2): 1, -Rational(3, 2): 1, -Rational(1, 2): 1, Rational(3, 2): 1}
assert roots((a + b + c)*x - (a + b + c + d), x) == {(a + b + c + d)/(a + b + c): 1}
assert roots(x**3 + x**2 - x + 1, x, cubics=False) == {}
assert roots(((x - 2)*(
x + 3)*(x - 4)).expand(), x, cubics=False) == {-3: 1, 2: 1, 4: 1}
assert roots(((x - 2)*(x + 3)*(x - 4)*(x - 5)).expand(), x, cubics=False) == \
{-3: 1, 2: 1, 4: 1, 5: 1}
assert roots(x**3 + 2*x**2 + 4*x + 8, x) == {-2: 1, -2*I: 1, 2*I: 1}
assert roots(x**3 + 2*x**2 + 4*x + 8, x, cubics=True) == \
{-2*I: 1, 2*I: 1, -2: 1}
assert roots((x**2 - x)*(x**3 + 2*x**2 + 4*x + 8), x) == \
{1: 1, 0: 1, -2: 1, -2*I: 1, 2*I: 1}
r1_2, r1_3 = Rational(1, 2), Rational(1, 3)
x0 = (3*sqrt(33) + 19)**r1_3
x1 = 4/x0/3
x2 = x0/3
x3 = sqrt(3)*I/2
x4 = x3 - r1_2
x5 = -x3 - r1_2
assert roots(x**3 + x**2 - x + 1, x, cubics=True) == {
-x1 - x2 - r1_3: 1,
-x1/x4 - x2*x4 - r1_3: 1,
-x1/x5 - x2*x5 - r1_3: 1,
}
f = (x**2 + 2*x + 3).subs({x: 2*x**2 + 3*x}).subs({x: 5*x - 4})
r13_20, r1_20 = (Rational(*r) for r in ((13, 20), (1, 20)))
s2 = sqrt(2)
assert roots(f, x) == {
r13_20 + r1_20*sqrt(1 - 8*I*s2): 1,
r13_20 - r1_20*sqrt(1 - 8*I*s2): 1,
r13_20 + r1_20*sqrt(1 + 8*I*s2): 1,
r13_20 - r1_20*sqrt(1 + 8*I*s2): 1,
}
f = x**4 + x**3 + x**2 + x + 1
r1_4, r1_8, r5_8 = (Rational(*r) for r in ((1, 4), (1, 8), (5, 8)))
assert roots(f, x) == {
-r1_4 + r1_4*5**r1_2 + I*(r5_8 + r1_8*5**r1_2)**r1_2: 1,
-r1_4 + r1_4*5**r1_2 - I*(r5_8 + r1_8*5**r1_2)**r1_2: 1,
-r1_4 - r1_4*5**r1_2 + I*(r5_8 - r1_8*5**r1_2)**r1_2: 1,
-r1_4 - r1_4*5**r1_2 - I*(r5_8 - r1_8*5**r1_2)**r1_2: 1,
}
f = z**3 + (-2 - y)*z**2 + (1 + 2*y - 2*x**2)*z - y + 2*x**2
assert roots(f, z) == {
1: 1,
Rational(1, 2) + y/2 + sqrt(1 - 2*y + y**2 + 8*x**2)/2: 1,
Rational(1, 2) + y/2 - sqrt(1 - 2*y + y**2 + 8*x**2)/2: 1,
}
assert roots(a*b*c*x**3 + 2*x**2 + 4*x + 8, x, cubics=False) == {}
assert roots(a*b*c*x**3 + 2*x**2 + 4*x + 8, x, cubics=True) != {}
assert roots(x**4 - 1, x, filter='Z') == {1: 1, -1: 1}
assert roots(x**4 - 1, x, filter='R') == {1: 1, -1: 1}
assert roots(x**4 - 1, x, filter='I') == {I: 1, -I: 1}
pytest.raises(ValueError, lambda: roots(x**4 - 1, x, filter='spam'))
assert roots((x - 1)*(x + 1), x) == {1: 1, -1: 1}
assert roots(
(x - 1)*(x + 1), x, predicate=lambda r: r.is_positive) == {1: 1}
assert roots(x**4 - 1, x, filter='Z', multiple=True) == [-1, 1]
assert roots(x**4 - 1, x, filter='I', multiple=True) == [I, -I]
assert roots(x**3, x, multiple=True) == [0, 0, 0]
assert roots(1234, x, multiple=True) == []
f = x**6 - x**5 + x**4 - x**3 + x**2 - x + 1
assert roots(f) == {
-I*sin(pi/7) + cos(pi/7): 1,
-I*sin(2*pi/7) - cos(2*pi/7): 1,
-I*sin(3*pi/7) + cos(3*pi/7): 1,
I*sin(pi/7) + cos(pi/7): 1,
I*sin(2*pi/7) - cos(2*pi/7): 1,
I*sin(3*pi/7) + cos(3*pi/7): 1,
}
g = ((x**2 + 1)*f**2).expand()
assert roots(g) == {
-I*sin(pi/7) + cos(pi/7): 2,
-I*sin(2*pi/7) - cos(2*pi/7): 2,
-I*sin(3*pi/7) + cos(3*pi/7): 2,
I*sin(pi/7) + cos(pi/7): 2,
I*sin(2*pi/7) - cos(2*pi/7): 2,
I*sin(3*pi/7) + cos(3*pi/7): 2,
-I: 1, I: 1,
}
r = roots(x**3 + 40*x + 64)
real_root = [rx for rx in r if rx.is_extended_real][0]
cr = 108 + 6*sqrt(1074)
assert real_root == -2*root(cr, 3)/3 + 20/root(cr, 3)
eq = ((7 + 5*sqrt(2))*x**3 + (-6 - 4*sqrt(2))*x**2 + (-sqrt(2) - 1)*x + 2).as_poly(x, domain=EX)
assert roots(eq) == {-1 + sqrt(2): 1, -2 + 2*sqrt(2): 1, -sqrt(2) + 1: 1}
eq = (41*x**5 + 29*sqrt(2)*x**5 - 153*x**4 - 108*sqrt(2)*x**4 +
175*x**3 + 125*sqrt(2)*x**3 - 45*x**2 - 30*sqrt(2)*x**2 - 26*sqrt(2)*x -
26*x + 24).as_poly(x, domain=EX)
assert roots(eq) == {-sqrt(2) + 1: 1, -2 + 2*sqrt(2): 1, -1 + sqrt(2): 1,
-4 + 4*sqrt(2): 1, -3 + 3*sqrt(2): 1}
eq = (x**3 - 2*x**2 + 6*sqrt(2)*x**2 - 8*sqrt(2)*x + 23*x - 14 +
14*sqrt(2)).as_poly(x, domain=EX)
assert roots(eq) == {-2*sqrt(2) + 2: 1, -2*sqrt(2) + 1: 1, -2*sqrt(2) - 1: 1}
assert roots(((x + sqrt(2))**3 - 7).as_poly(x, domain=EX)) == \
{-sqrt(2) - root(7, 3)/2 - sqrt(3)*root(7, 3)*I/2: 1,
-sqrt(2) - root(7, 3)/2 + sqrt(3)*root(7, 3)*I/2: 1,
-sqrt(2) + root(7, 3): 1}
pytest.raises(PolynomialError, lambda: roots(x*y, x, y))
def test_roots1():
assert roots(1) == {}
assert roots(1, multiple=True) == []
q = Symbol('q', real=True)
assert roots(x**3 - q, x) == {cbrt(q): 1,
-cbrt(q)/2 - sqrt(3)*I*cbrt(q)/2: 1,
-cbrt(q)/2 + sqrt(3)*I*cbrt(q)/2: 1}
assert roots_cubic((x**3 - 1).as_poly()) == [1, Rational(-1, 2) + sqrt(3)*I/2,
Rational(-1, 2) - sqrt(3)*I/2]
assert roots([1, x, y]) == {-x/2 - sqrt(x**2 - 4*y)/2: 1,
-x/2 + sqrt(x**2 - 4*y)/2: 1}
pytest.raises(ValueError, lambda: roots([1, x, y], z))
def test_roots_slow():
"""Just test that calculating these roots does not hang."""
a, b, c, d, x = symbols('a,b,c,d,x')
f1 = x**2*c + (a/b) + x*c*d - a
f2 = x**2*(a + b*(c - d)*a) + x*a*b*c/(b*d - d) + (a*d - c/d)
assert list(roots(f1, x).values()) == [1, 1]
assert list(roots(f2, x).values()) == [1, 1]
zz, yy, xx, zy, zx, yx, k = symbols('zz,yy,xx,zy,zx,yx,k')
e1 = (zz - k)*(yy - k)*(xx - k) + zy*yx*zx + zx - zy - yx
e2 = (zz - k)*yx*yx + zx*(yy - k)*zx + zy*zy*(xx - k)
assert list(roots(e1 - e2, k).values()) == [1, 1, 1]
f = x**3 + 2*x**2 + 8
R = list(roots(f))
assert not any(i for i in [f.subs({x: ri}).evalf(chop=True) for ri in R])
def test_roots_inexact():
R1 = roots(x**2 + x + 1, x, multiple=True)
R2 = roots(x**2 + x + 1.0, x, multiple=True)
for r1, r2 in zip(R1, R2):
assert abs(r1 - r2) < 1e-12
f = x**4 + 3.0*sqrt(2.0)*x**3 - (78.0 + 24.0*sqrt(3.0))*x**2 \
+ 144.0*(2*sqrt(3.0) + 9.0)
R1 = roots(f, multiple=True)
R2 = (-12.7530479110482, -3.85012393732929,
4.89897948556636, 7.46155167569183)
for r1, r2 in zip(R1, R2):
assert abs(r1 - r2) < 1e-10
def test_roots_preprocessed():
E, F, J, L = symbols('E,F,J,L')
f = -21601054687500000000*E**8*J**8/L**16 + \
508232812500000000*F*x*E**7*J**7/L**14 - \
4269543750000000*E**6*F**2*J**6*x**2/L**12 + \
16194716250000*E**5*F**3*J**5*x**3/L**10 - \
27633173750*E**4*F**4*J**4*x**4/L**8 + \
14840215*E**3*F**5*J**3*x**5/L**6 + \
54794*E**2*F**6*J**2*x**6/(5*L**4) - \
1153*E*J*F**7*x**7/(80*L**2) + \
633*F**8*x**8/160000
assert roots(f, x) == {}
R1 = roots(f.evalf(strict=False), x, multiple=True)
R2 = [-1304.88375606366, 97.1168816800648, 186.946430171876, 245.526792947065,
503.441004174773, 791.549343830097, 1273.16678129348, 1850.10650616851]
w = Wild('w')
p = w*E*J/(F*L**2)
assert len(R1) == len(R2)
for r1, r2 in zip(R1, R2):
match = r1.match(p)
assert match is not None and abs(match[w] - r2) < 1e-10
def test_roots_mixed():
f = -1936 - 5056*x - 7592*x**2 + 2704*x**3 - 49*x**4
_re, _im = [], []
p = f.as_poly()
for r in p.all_roots():
c, (r,) = r.as_coeff_mul()
if r.is_real:
r = r.interval
_re.append((c*QQ.to_expr(r.a), c*QQ.to_expr(r.b)))
else:
r = r.interval
_im.append((c*QQ.to_expr(r.ax) + c*I*QQ.to_expr(r.ay),
c*QQ.to_expr(r.bx) + c*I*QQ.to_expr(r.by)))
_nroots = nroots(f)
_sroots = roots(f, multiple=True)
_re = [Interval(a, b) for (a, b) in _re]
_im = [Interval(re(a), re(b))*Interval(im(a), im(b)) for (a, b) in _im]
_intervals = _re + _im
_sroots = [r.evalf() for r in _sroots]
_nroots = sorted(_nroots, key=lambda x: x.sort_key())
_sroots = sorted(_sroots, key=lambda x: x.sort_key())
for _roots in (_nroots, _sroots):
for i, r in zip(_intervals, _roots):
if r.is_extended_real:
assert r in i
else:
assert (re(r), im(r)) in i
def test_root_factors():
assert root_factors(Integer(1).as_poly(x)) == [Integer(1).as_poly(x)]
assert root_factors(x.as_poly()) == [x.as_poly()]
assert root_factors(x**2 - 1, x) == [x + 1, x - 1]
assert root_factors(x**2 - y, x) == [x - sqrt(y), x + sqrt(y)]
assert root_factors((x**4 - 1)**2) == \
[x + 1, x + 1, x - 1, x - 1, x - I, x - I, x + I, x + I]
assert root_factors((x**4 - 1).as_poly(), filter='Z') == \
[(x + 1).as_poly(), (x - 1).as_poly(), (x**2 + 1).as_poly()]
assert root_factors(8*x**2 + 12*x**4 + 6*x**6 + x**8, x, filter='Q') == \
[x, x, x**6 + 6*x**4 + 12*x**2 + 8]
pytest.raises(ValueError, lambda: root_factors((x*y).as_poly()))
def test_nroots1():
n = 64
p = legendre_poly(n, x, polys=True)
pytest.raises(mpmath.mp.NoConvergence, lambda: p.nroots(n=3, maxsteps=5))
roots = p.nroots(n=3)
# The order of roots matters. They are ordered from smallest to the
# largest.
assert [str(r) for r in roots] == \
['-0.999', '-0.996', '-0.991', '-0.983', '-0.973', '-0.961',
'-0.946', '-0.930', '-0.911', '-0.889', '-0.866', '-0.841',
'-0.813', '-0.784', '-0.753', '-0.720', '-0.685', '-0.649',
'-0.611', '-0.572', '-0.531', '-0.489', '-0.446', '-0.402',
'-0.357', '-0.311', '-0.265', '-0.217', '-0.170', '-0.121',
'-0.0730', '-0.0243', '0.0243', '0.0730', '0.121', '0.170',
'0.217', '0.265', '0.311', '0.357', '0.402', '0.446', '0.489',
'0.531', '0.572', '0.611', '0.649', '0.685', '0.720', '0.753',
'0.784', '0.813', '0.841', '0.866', '0.889', '0.911', '0.930',
'0.946', '0.961', '0.973', '0.983', '0.991', '0.996', '0.999']
def test_nroots2():
p = (x**5 + 3*x + 1).as_poly()
roots = p.nroots(n=3)
# The order of roots matters. The roots are ordered by their real
# components (if they agree, then by their imaginary components),
# with real roots appearing first.
assert [str(r) for r in roots] == \
['-0.332', '-0.839 - 0.944*I', '-0.839 + 0.944*I',
'1.01 - 0.937*I', '1.01 + 0.937*I']
roots = p.nroots(n=5)
assert [str(r) for r in roots] == \
['-0.33199', '-0.83907 - 0.94385*I', '-0.83907 + 0.94385*I',
'1.0051 - 0.93726*I', '1.0051 + 0.93726*I']
def test_roots_composite():
assert len(roots((y**3 + y**2*sqrt(x) + y + x).as_poly(y, composite=True))) == 3
def test_sympyissue_7724():
e = x**4*I + x**2 + I
r1, r2 = roots(e, x), e.as_poly(x).all_roots()
assert len(r1) == 4
assert {_.evalf() for _ in r1} == {_.evalf() for _ in r2}
def test_sympyissue_14291():
p = (((x - 1)**2 + 1)*((x - 1)**2 + 2)*(x - 1)).as_poly()
assert set(p.all_roots()) == {1, 1 - I, 1 + I, 1 - I*sqrt(2), 1 + sqrt(2)*I}
def test_sympyissue_16589():
e = x**4 - 8*sqrt(2)*x**3 + 4*x**3 - 64*sqrt(2)*x**2 + 1024*x
rs = roots(e, x)
assert 0 in rs
assert all(not e.evalf(chop=True, subs={x: r}) for r in rs)
def test_sympyissue_21263():
e = x**3 + 3*x**2 + 3*x + y + 1
r = roots(e, x)
assert r == {-root(y, 3) - 1: 1,
-root(y, 3)*(-Rational(1, 2) - sqrt(3)*I/2) - 1: 1,
-root(y, 3)*(-Rational(1, 2) + sqrt(3)*I/2) - 1: 1}
| bsd-3-clause | a1fd4fc56b59f0377c6169fb29d7f420 | 35.7 | 121 | 0.475098 | 2.368166 | false | false | false | false |
diofant/diofant | diofant/functions/special/elliptic_integrals.py | 1 | 11441 | """Elliptic integrals."""
from ...core import Function, I, Integer, Rational, oo, pi, zoo
from ...core.function import ArgumentIndexError
from ..elementary.complexes import sign
from ..elementary.hyperbolic import atanh
from ..elementary.miscellaneous import sqrt
from ..elementary.trigonometric import sin, tan
from .gamma_functions import gamma
from .hyper import hyper, meijerg
class elliptic_k(Function):
r"""
The complete elliptic integral of the first kind, defined by
.. math:: K(m) = F\left(\tfrac{\pi}{2}\middle| m\right)
where `F\left(z\middle| m\right)` is the Legendre incomplete
elliptic integral of the first kind.
The function `K(m)` is a single-valued function on the complex
plane with branch cut along the interval `(1, \infty)`.
Examples
========
>>> elliptic_k(0)
pi/2
>>> elliptic_k(1.0 + I)
1.50923695405127 + 0.625146415202697*I
>>> elliptic_k(m).series(m, n=3)
pi/2 + pi*m/8 + 9*pi*m**2/128 + O(m**3)
References
==========
* https://en.wikipedia.org/wiki/Elliptic_integrals
* http://functions.wolfram.com/EllipticIntegrals/EllipticK
See Also
========
elliptic_f
"""
@classmethod
def eval(cls, m):
if m == 0:
return pi/2
elif m == Rational(1, 2):
return 8*pi**Rational(3, 2)/gamma(-Rational(1, 4))**2
elif m == 1:
return zoo
elif m == -1:
return gamma(Rational(1, 4))**2/(4*sqrt(2*pi))
elif m in (oo, -oo, I*oo, I*-oo, zoo):
return Integer(0)
def fdiff(self, argindex=1):
m = self.args[0]
if argindex == 1:
return (elliptic_e(m) - (1 - m)*elliptic_k(m))/(2*m*(1 - m))
else:
raise ArgumentIndexError(self, argindex)
def _eval_conjugate(self):
m = self.args[0]
if (m.is_extended_real and (m - 1).is_positive) is False:
return self.func(m.conjugate())
def _eval_nseries(self, x, n, logx):
from ...simplify import hyperexpand
return hyperexpand(self.rewrite(hyper)._eval_nseries(x, n=n, logx=logx))
def _eval_rewrite_as_hyper(self, m):
return (pi/2)*hyper((Rational(1, 2), Rational(1, 2)), (1,), m)
def _eval_rewrite_as_meijerg(self, m):
return meijerg(((Rational(1, 2), Rational(1, 2)), []), ((0,), (0,)), -m)/2
class elliptic_f(Function):
r"""
The Legendre incomplete elliptic integral of the first
kind, defined by
.. math:: F\left(z\middle| m\right) =
\int_0^z \frac{dt}{\sqrt{1 - m \sin^2 t}}
This function reduces to a complete elliptic integral of
the first kind, `K(m)`, when `z = \pi/2`.
Examples
========
>>> elliptic_f(z, m).series(z)
z + z**5*(3*m**2/40 - m/30) + m*z**3/6 + O(z**6)
>>> elliptic_f(3.0 + I/2, 1.0 + I)
2.909449841483 + 1.74720545502474*I
References
==========
* https://en.wikipedia.org/wiki/Elliptic_integrals
* http://functions.wolfram.com/EllipticIntegrals/EllipticF
See Also
========
elliptic_k
"""
@classmethod
def eval(cls, z, m):
k = 2*z/pi
if m.is_zero:
return z
elif z.is_zero:
return Integer(0)
elif k.is_integer:
return k*elliptic_k(m)
elif m in (oo, -oo):
return Integer(0)
elif z.could_extract_minus_sign():
return -elliptic_f(-z, m)
def fdiff(self, argindex=1):
z, m = self.args
fm = sqrt(1 - m*sin(z)**2)
if argindex == 1:
return 1/fm
elif argindex == 2:
return (elliptic_e(z, m)/(2*m*(1 - m)) - elliptic_f(z, m)/(2*m) -
sin(2*z)/(4*(1 - m)*fm))
else:
raise ArgumentIndexError(self, argindex)
def _eval_conjugate(self):
z, m = self.args
if (m.is_extended_real and (m - 1).is_positive) is False:
return self.func(z.conjugate(), m.conjugate())
class elliptic_e(Function):
r"""
Called with two arguments `z` and `m`, evaluates the
incomplete elliptic integral of the second kind, defined by
.. math:: E\left(z\middle| m\right) = \int_0^z \sqrt{1 - m \sin^2 t} dt
Called with a single argument `m`, evaluates the Legendre complete
elliptic integral of the second kind
.. math:: E(m) = E\left(\tfrac{\pi}{2}\middle| m\right)
The function `E(m)` is a single-valued function on the complex
plane with branch cut along the interval `(1, \infty)`.
Examples
========
>>> elliptic_e(z, m).series(z)
z + z**5*(-m**2/40 + m/30) - m*z**3/6 + O(z**6)
>>> elliptic_e(m).series(m, n=4)
pi/2 - pi*m/8 - 3*pi*m**2/128 - 5*pi*m**3/512 + O(m**4)
>>> elliptic_e(1 + I, 2 - I/2).evalf()
1.55203744279187 + 0.290764986058437*I
>>> elliptic_e(0)
pi/2
>>> elliptic_e(2.0 - I)
0.991052601328069 + 0.81879421395609*I
References
==========
* https://en.wikipedia.org/wiki/Elliptic_integrals
* http://functions.wolfram.com/EllipticIntegrals/EllipticE2
* http://functions.wolfram.com/EllipticIntegrals/EllipticE
"""
@classmethod
def eval(cls, z, m=None):
if m is not None:
k = 2*z/pi
if m.is_zero:
return z
if z.is_zero:
return Integer(0)
elif k.is_integer:
return k*elliptic_e(m)
elif m in (oo, -oo):
return zoo
elif z.could_extract_minus_sign():
return -elliptic_e(-z, m)
else:
m = z
if m.is_zero:
return pi/2
elif m == 1:
return Integer(1)
elif m is oo:
return I*oo
elif m == -oo:
return oo
elif m is zoo:
return zoo
def fdiff(self, argindex=1):
if len(self.args) == 2:
z, m = self.args
if argindex == 1:
return sqrt(1 - m*sin(z)**2)
elif argindex == 2:
return (elliptic_e(z, m) - elliptic_f(z, m))/(2*m)
else:
raise ArgumentIndexError(self, argindex)
else:
m = self.args[0]
if argindex == 1:
return (elliptic_e(m) - elliptic_k(m))/(2*m)
else:
raise ArgumentIndexError(self, argindex)
def _eval_conjugate(self):
if len(self.args) == 2:
z, m = self.args
if (m.is_extended_real and (m - 1).is_positive) is False:
return self.func(z.conjugate(), m.conjugate())
else:
m = self.args[0]
if (m.is_extended_real and (m - 1).is_positive) is False:
return self.func(m.conjugate())
def _eval_nseries(self, x, n, logx):
from ...simplify import hyperexpand
if len(self.args) == 1:
return hyperexpand(self.rewrite(hyper)._eval_nseries(x, n=n, logx=logx))
return super()._eval_nseries(x, n=n, logx=logx)
def _eval_rewrite_as_hyper(self, *args):
if len(args) == 1:
m = args[0]
return (pi/2)*hyper((-Rational(1, 2), Rational(1, 2)), (1,), m)
def _eval_rewrite_as_meijerg(self, *args):
if len(args) == 1:
m = args[0]
return -meijerg(((Rational(1, 2), Rational(3, 2)), []),
((0,), (0,)), -m)/4
class elliptic_pi(Function):
r"""
Called with three arguments `n`, `z` and `m`, evaluates the
Legendre incomplete elliptic integral of the third kind, defined by
.. math:: \Pi\left(n; z\middle| m\right) = \int_0^z \frac{dt}
{\left(1 - n \sin^2 t\right) \sqrt{1 - m \sin^2 t}}
Called with two arguments `n` and `m`, evaluates the complete
elliptic integral of the third kind:
.. math:: \Pi\left(n\middle| m\right) =
\Pi\left(n; \tfrac{\pi}{2}\middle| m\right)
Examples
========
>>> elliptic_pi(n, z, m).series(z, n=4)
z + z**3*(m/6 + n/3) + O(z**4)
>>> elliptic_pi(0.5 + I, 1.0 - I, 1.2)
2.50232379629182 - 0.760939574180767*I
>>> elliptic_pi(0, 0)
pi/2
>>> elliptic_pi(1.0 - I/3, 2.0 + I)
3.29136443417283 + 0.32555634906645*I
References
==========
* https://en.wikipedia.org/wiki/Elliptic_integrals
* http://functions.wolfram.com/EllipticIntegrals/EllipticPi3
* http://functions.wolfram.com/EllipticIntegrals/EllipticPi
"""
@classmethod
def eval(cls, n, m, z=None):
if z is not None:
z, m = m, z
k = 2*z/pi
if n == 0:
return elliptic_f(z, m)
elif n == 1:
return (elliptic_f(z, m) +
(sqrt(1 - m*sin(z)**2)*tan(z) -
elliptic_e(z, m))/(1 - m))
elif k.is_integer:
return k*elliptic_pi(n, m)
elif m == 0:
return atanh(sqrt(n - 1)*tan(z))/sqrt(n - 1)
elif n == m:
return (elliptic_f(z, n) - elliptic_pi(1, z, n) +
tan(z)/sqrt(1 - n*sin(z)**2))
elif n in (oo, -oo):
return Integer(0)
elif m in (oo, -oo):
return Integer(0)
elif z.could_extract_minus_sign():
return -elliptic_pi(n, -z, m)
else:
if n == 0:
return elliptic_k(m)
elif n == 1:
return zoo
elif m == 0:
return pi/(2*sqrt(1 - n))
elif m == 1:
return -oo/sign(n - 1)
elif n == m:
return elliptic_e(n)/(1 - n)
elif n in (oo, -oo):
return Integer(0)
elif m in (oo, -oo):
return Integer(0)
def _eval_conjugate(self):
if len(self.args) == 3:
n, z, m = self.args
if (n.is_extended_real and (n - 1).is_positive) is False and \
(m.is_extended_real and (m - 1).is_positive) is False:
return self.func(n.conjugate(), z.conjugate(), m.conjugate())
else:
n, m = self.args
return self.func(n.conjugate(), m.conjugate())
def fdiff(self, argindex=1):
if len(self.args) == 3:
n, z, m = self.args
fm, fn = sqrt(1 - m*sin(z)**2), 1 - n*sin(z)**2
if argindex == 1:
return (elliptic_e(z, m) + (m - n)*elliptic_f(z, m)/n +
(n**2 - m)*elliptic_pi(n, z, m)/n -
n*fm*sin(2*z)/(2*fn))/(2*(m - n)*(n - 1))
elif argindex == 2:
return 1/(fm*fn)
elif argindex == 3:
return (elliptic_e(z, m)/(m - 1) +
elliptic_pi(n, z, m) -
m*sin(2*z)/(2*(m - 1)*fm))/(2*(n - m))
else:
raise ArgumentIndexError(self, argindex)
else:
n, m = self.args
if argindex == 1:
return (elliptic_e(m) + (m - n)*elliptic_k(m)/n +
(n**2 - m)*elliptic_pi(n, m)/n)/(2*(m - n)*(n - 1))
elif argindex == 2:
return (elliptic_e(m)/(m - 1) + elliptic_pi(n, m))/(2*(n - m))
else:
raise ArgumentIndexError(self, argindex)
| bsd-3-clause | 864603a3eca439b55a7da6e0cc4d7829 | 30.345205 | 84 | 0.498995 | 3.19581 | false | false | false | false |
diofant/diofant | diofant/tests/polys/test_rationaltools.py | 2 | 2195 | """Tests for tools for manipulation of rational expressions."""
from diofant import Eq, Integral, Mul, Rational, exp, sin, symbols, together
from diofant.abc import x, y, z
__all__ = ()
A, B = symbols('A,B', commutative=False)
def test_together():
assert together(0) == 0
assert together(1) == 1
assert together(x*y*z) == x*y*z
assert together(x + y) == x + y
assert together(1/x) == 1/x
assert together(1/x + 1) == (x + 1)/x
assert together(1/x + 3) == (3*x + 1)/x
assert together(1/x + x) == (x**2 + 1)/x
assert together((1/x + 1, 1/x + 3)) == ((x + 1)/x, (3*x + 1)/x)
assert together(1/x + Rational(1, 2)) == (x + 2)/(2*x)
assert together(Rational(1, 2) + x/2) == Mul(Rational(1, 2), x + 1, evaluate=False)
assert together(1/x + 2/y) == (2*x + y)/(y*x)
assert together(1/(1 + 1/x)) == x/(1 + x)
assert together(x/(1 + 1/x)) == x**2/(1 + x)
assert together(1/x + 1/y + 1/z) == (x*y + x*z + y*z)/(x*y*z)
assert together(1/(1 + x + 1/y + 1/z)) == y*z/(y + z + y*z + x*y*z)
assert together(1/(x*y) + 1/(x*y)**2) == y**(-2)*x**(-2)*(1 + x*y)
assert together(1/(x*y) + 1/(x*y)**4) == y**(-4)*x**(-4)*(1 + x**3*y**3)
assert together(1/(x**7*y) + 1/(x*y)**4) == y**(-4)*x**(-7)*(x**3 + y**3)
assert together(5/(2 + 6/(3 + 7/(4 + 8/(5 + 9/x))))) == \
Rational(5, 2)*((171 + 119*x)/(279 + 203*x))
assert together(1 + 1/(x + 1)**2) == (1 + (x + 1)**2)/(x + 1)**2
assert together(1 + 1/(x*(1 + x))) == (1 + x*(1 + x))/(x*(1 + x))
assert together(
1/(x*(x + 1)) + 1/(x*(x + 2))) == (3 + 2*x)/(x*(1 + x)*(2 + x))
assert together(1 + 1/(2*x + 2)**2) == (4*(x + 1)**2 + 1)/(4*(x + 1)**2)
assert together(sin(1/x + 1/y)) == sin(1/x + 1/y)
assert together(sin(1/x + 1/y), deep=True) == sin((x + y)/(x*y))
assert together(1/exp(x) + 1/(x*exp(x))) == (1 + x)/(x*exp(x))
assert together(1/exp(2*x) + 1/(x*exp(3*x))) == (1 + exp(x)*x)/(x*exp(3*x))
assert together(Integral(1/x + 1/y, x)) == Integral((x + y)/(x*y), x)
assert together(Eq(1/x + 1/y, 1 + 1/z)) == Eq((x + y)/(x*y), (z + 1)/z)
assert together((A*B)**-1 + (B*A)**-1) == (A*B)**-1 + (B*A)**-1
| bsd-3-clause | d35bfbe09a12e761c388a35e0f4fc5a1 | 36.20339 | 87 | 0.474715 | 2.345085 | false | false | false | false |
diofant/diofant | diofant/tests/matrices/test_adjoint.py | 2 | 1203 | from diofant import (Adjoint, Integer, Matrix, MatrixSymbol, Transpose,
adjoint, conjugate, eye, symbols, trace, transpose)
__all__ = ()
n, m, l, k, p = symbols('n m l k p', integer=True)
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', m, l)
C = MatrixSymbol('C', n, n)
D = MatrixSymbol('D', n, n)
def test_adjoint():
Sq = MatrixSymbol('Sq', n, n)
assert Adjoint(A).shape == (m, n)
assert Adjoint(A*B).shape == (l, n)
assert adjoint(Adjoint(A)) == A
assert isinstance(Adjoint(Adjoint(A)), Adjoint)
assert conjugate(Adjoint(A)) == Transpose(A) == Adjoint(A).conjugate()
assert transpose(Adjoint(A)) == Adjoint(Transpose(A)) == Transpose(A).adjoint()
assert Adjoint(eye(3)).doit() == Adjoint(eye(3)).doit(deep=False) == eye(3)
assert Adjoint(Integer(5)).doit() == Integer(5)
assert Adjoint(Matrix([[1, 2], [3, 4]])).doit() == Matrix([[1, 3], [2, 4]])
assert adjoint(trace(Sq)) == conjugate(trace(Sq))
assert trace(adjoint(Sq)) == conjugate(trace(Sq))
assert Adjoint(Sq)[0, 1] == conjugate(Sq[1, 0])
assert Adjoint(A*B).doit() == Adjoint(B) * Adjoint(A)
assert Adjoint(C + D).doit() == Adjoint(C) + Adjoint(D)
| bsd-3-clause | 1a41321d88d48b5dfadcd65df57f3d3b | 31.513514 | 83 | 0.603491 | 2.934146 | false | false | false | false |
diofant/diofant | diofant/polys/rationaltools.py | 1 | 2478 | """Tools for manipulation of rational expressions."""
from ..core import Add, gcd_terms
from ..core.sympify import sympify
def together(expr, deep=False):
"""
Denest and combine rational expressions using symbolic methods.
This function takes an expression or a container of expressions
and puts it (them) together by denesting and combining rational
subexpressions. No heroic measures are taken to minimize degree
of the resulting numerator and denominator. To obtain completely
reduced expression use :func:`~diofant.polys.polytools.cancel`. However, :func:`together`
can preserve as much as possible of the structure of the input
expression in the output (no expansion is performed).
A wide variety of objects can be put together including lists,
tuples, sets, relational objects, integrals and others. It is
also possible to transform interior of function applications,
by setting ``deep`` flag to ``True``.
By definition, :func:`together` is a complement to :func:`~diofant.polys.partfrac.apart`,
so ``apart(together(expr))`` should return expr unchanged. Note
however, that :func:`together` uses only symbolic methods, so
it might be necessary to use :func:`~diofant.polys.polytools.cancel` to perform algebraic
simplification and minimise degree of the numerator and denominator.
Examples
========
>>> together(1/x + 1/y)
(x + y)/(x*y)
>>> together(1/x + 1/y + 1/z)
(x*y + x*z + y*z)/(x*y*z)
>>> together(1/(x*y) + 1/y**2)
(x + y)/(x*y**2)
>>> together(1/(1 + 1/x) + 1/(1 + 1/y))
(x*(y + 1) + y*(x + 1))/((x + 1)*(y + 1))
>>> together(exp(1/x + 1/y))
E**(1/y + 1/x)
>>> together(exp(1/x + 1/y), deep=True)
E**((x + y)/(x*y))
>>> together(1/exp(x) + 1/(x*exp(x)))
E**(-x)*(x + 1)/x
>>> together(1/exp(2*x) + 1/(x*exp(3*x)))
E**(-3*x)*(E**x*x + 1)/x
"""
def _together(expr):
if expr.is_Atom or (expr.is_Function and not deep):
return expr
elif expr.is_Add:
return gcd_terms(list(map(_together, Add.make_args(expr))))
elif expr.is_Pow:
base = _together(expr.base)
if deep:
exp = _together(expr.exp)
else:
exp = expr.exp
return expr.__class__(base, exp)
else:
return expr.__class__(*[_together(arg) for arg in expr.args])
return _together(sympify(expr))
| bsd-3-clause | 258579af55b4120d470efc72c78ca3d7 | 32.945205 | 93 | 0.605327 | 3.509915 | false | false | false | false |
diofant/diofant | diofant/interactive/printing.py | 1 | 3322 | import builtins
import fractions
import os
import sys
from ..printing import latex, pretty, sstrrepr
from ..printing.printer import Printer
def _init_python_printing(stringify_func):
"""Setup printing in Python interactive session."""
def _displayhook(arg):
"""Python's pretty-printer display hook.
This function was adapted from PEP 217.
"""
if arg is not None:
builtins._ = None
if isinstance(arg, str):
print(repr(arg))
else:
print(stringify_func(arg))
builtins._ = arg
sys.displayhook = _displayhook
def _init_ipython_printing(ip, stringify_func):
"""Setup printing in IPython interactive session."""
def _print_plain_text(arg, p, cycle):
p.text(stringify_func(arg))
def _print_latex_text(o):
return latex(o, mode='equation*')
printable_types = [float, tuple, list, set, frozenset, dict,
int, fractions.Fraction]
plaintext_formatter = ip.display_formatter.formatters['text/plain']
latex_formatter = ip.display_formatter.formatters['text/latex']
for cls in printable_types:
plaintext_formatter.for_type(cls, _print_plain_text)
for cls in printable_types:
latex_formatter.for_type(cls, _print_latex_text)
def init_printing(no_global=False, pretty_print=None, **settings):
r"""Initializes pretty-printer depending on the environment.
Parameters
==========
no_global : boolean
If True, the settings become system wide;
if False, use just for this console/session.
pretty_print : boolean or None
Enable pretty printer (turned on by default for IPython, but
disabled for plain Python console).
\*\*settings : dict
A dictionary of default settings for printers.
Notes
=====
This function runs automatically for wildcard imports (e.g.
for ``from diofant import *``) in interactive sessions.
Examples
========
>>> from diofant.abc import theta
>>> sqrt(5)
sqrt(5)
>>> init_printing(pretty_print=True, no_global=True)
>>> sqrt(5)
___
╲╱ 5
>>> theta
θ
>>> init_printing(pretty_print=True, use_unicode=False, no_global=True)
>>> theta
theta
>>> init_printing(pretty_print=True, order='grevlex', no_global=True)
>>> y + x + y**2 + x**2
2 2
x + y + x + y
"""
try:
ip = get_ipython()
except NameError:
ip = None
# guess unicode support
unicode_term = False
TERM = os.environ.get('TERM', '')
if TERM != '' and not TERM.endswith('linux'):
unicode_term = True
if settings.get('use_unicode') is None:
settings['use_unicode'] = bool(unicode_term)
if ip:
stringify_func = pretty if pretty_print is not False else sstrrepr
else:
stringify_func = sstrrepr if not pretty_print else pretty
if no_global:
_stringify_func = stringify_func
def stringify_func(expr): # pylint: disable=function-redefined
return _stringify_func(expr, **settings)
else:
Printer.set_global_settings(**settings)
if ip:
_init_ipython_printing(ip, stringify_func)
else:
_init_python_printing(stringify_func)
| bsd-3-clause | 96f7cbc54356f4d5a5372f1e1ad37bdd | 25.96748 | 75 | 0.615014 | 3.920804 | false | false | false | false |
diofant/diofant | diofant/core/evalf.py | 1 | 44144 | """
Adaptive numerical evaluation of Diofant expressions, using mpmath
for mathematical functions.
An mpf value tuple is a tuple of integers (sign, man, exp, bc)
representing a floating-point number: [1, -1][sign]*man*2**exp where
sign is 0 or 1 and bc should correspond to the number of bits used to
represent the mantissa (man) in binary notation, e.g.
>>> sign, man, exp, bc = 0, 5, 1, 3
>>> n = [1, -1][sign]*man*2**exp
>>> n, bitcount(man)
(10, 3)
A temporary result is a tuple (re, im, re_acc, im_acc) where
re and im are nonzero mpf value tuples representing approximate
numbers, or None to denote exact zeros.
re_acc, im_acc are integers denoting log2(e) where e is the estimated
relative accuracy of the respective complex part, but may be anything
if the corresponding complex part is None.
"""
import math
import numbers
from mpmath import inf as mpmath_inf
from mpmath import (libmp, make_mpc, make_mpf, mp, mpc, mpf, nsum, quadosc,
quadts, workprec)
from mpmath.libmp import bitcount as mpmath_bitcount
from mpmath.libmp import (fhalf, fnan, fnone, fone, from_int, from_man_exp,
from_rational, fzero, mpf_abs, mpf_add, mpf_atan,
mpf_atan2, mpf_cmp, mpf_cos, mpf_e, mpf_exp, mpf_log,
mpf_lt, mpf_mul, mpf_neg, mpf_pi, mpf_pow,
mpf_pow_int, mpf_shift, mpf_sin, mpf_sqrt, normalize,
round_nearest)
from mpmath.libmp.backend import MPZ
from mpmath.libmp.gammazeta import mpf_bernoulli
from mpmath.libmp.libmpc import _infs_nan
from mpmath.libmp.libmpf import dps_to_prec, prec_to_dps
from .compatibility import is_sequence
from .sympify import sympify
LG10 = math.log(10, 2)
rnd = round_nearest
def bitcount(n):
return mpmath_bitcount(int(n))
# Used in a few places as placeholder values to denote exponents and
# precision levels, e.g. of exact numbers. Must be careful to avoid
# passing these to mpmath functions or returning them in final results.
INF = float(mpmath_inf)
MINUS_INF = float(-mpmath_inf)
# ~= 100 digits. Real men set this to INF.
DEFAULT_MAXPREC = int(110*LG10) # keep in sync with maxn kwarg of evalf
class PrecisionExhausted(ArithmeticError):
"""Raised when precision is exhausted."""
############################################################################
# #
# Helper functions for arithmetic and complex parts #
# #
############################################################################
def fastlog(x):
"""Fast approximation of log2(x) for an mpf value tuple x.
Notes: Calculated as exponent + width of mantissa. This is an
approximation for two reasons: 1) it gives the ceil(log2(abs(x)))
value and 2) it is too high by 1 in the case that x is an exact
power of 2. Although this is easy to remedy by testing to see if
the odd mpf mantissa is 1 (indicating that one was dealing with
an exact power of 2) that would decrease the speed and is not
necessary as this is only being used as an approximation for the
number of bits in x. The correct return value could be written as
"x[2] + (x[3] if x[1] != 1 else 0)".
Since mpf tuples always have an odd mantissa, no check is done
to see if the mantissa is a multiple of 2 (in which case the
result would be too large by 1).
Examples
========
>>> s, m, e = 0, 5, 1
>>> bc = bitcount(m)
>>> n = [1, -1][s]*m*2**e
>>> n, (log(n)/log(2)).evalf(2), fastlog((s, m, e, bc))
(10, 3.3, 4)
"""
if not x or x == fzero:
return MINUS_INF
return x[2] + x[3]
def pure_complex(v):
"""Return a and b if v matches a + I*b where b is not zero and
a and b are Numbers, else None.
>>> a, b = Tuple(2, 3)
>>> pure_complex(a)
>>> pure_complex(a + b*I)
(2, 3)
>>> pure_complex(I)
(0, 1)
"""
from .numbers import I
h, t = v.as_coeff_Add()
c, i = t.as_coeff_Mul()
if i is I:
return h, c
def scaled_zero(mag, sign=1):
"""Return an mpf representing a power of two with magnitude ``mag``
and -1 for precision. Or, if ``mag`` is a scaled_zero tuple, then just
remove the sign from within the list that it was initially wrapped
in.
Examples
========
>>> z, p = scaled_zero(100)
>>> z, p
(([0], 1, 100, 1), -1)
>>> ok = scaled_zero(z)
>>> ok
(0, 1, 100, 1)
>>> Float(ok)
1.26765060022823e+30
>>> Float(ok, p)
0.e+30
>>> ok, p = scaled_zero(100, -1)
>>> Float(scaled_zero(ok), p)
-0.e+30
"""
if type(mag) is tuple and len(mag) == 4 and iszero(mag, scaled=True):
return (mag[0][0],) + mag[1:]
elif isinstance(mag, numbers.Integral):
if sign not in [-1, 1]:
raise ValueError('sign must be +/-1')
rv, p = mpf_shift(fone, mag), -1
s = 0 if sign == 1 else 1
rv = ([s],) + rv[1:]
return rv, p
else:
raise ValueError('scaled zero expects int or scaled_zero tuple.')
def iszero(mpf, scaled=False):
if not scaled:
return not mpf or not mpf[1] and not mpf[-1]
return mpf and type(mpf[0]) is list and mpf[1] == mpf[-1] == 1
def complex_accuracy(result):
"""
Returns relative accuracy of a complex number with given accuracies
for the real and imaginary parts. The relative accuracy is defined
in the complex norm sense as ||z|+|error|| / |z| where error
is equal to (real absolute error) + (imag absolute error)*i.
The full expression for the (logarithmic) error can be approximated
easily by using the max norm to approximate the complex norm.
In the worst case (re and im equal), this is wrong by a factor
sqrt(2), or by log2(sqrt(2)) = 0.5 bit.
"""
re, im, re_acc, im_acc = result
if not im:
if not re:
return INF
return re_acc
if not re:
return im_acc
re_size = fastlog(re)
im_size = fastlog(im)
absolute_error = max(re_size - re_acc, im_size - im_acc)
relative_error = absolute_error - max(re_size, im_size)
return -relative_error
def get_abs(expr, prec, options):
re, im, re_acc, im_acc = evalf(expr, prec + 2, options)
if not re:
re, re_acc, im, im_acc = im, im_acc, re, re_acc
if im:
return libmp.mpc_abs((re, im), prec), None, re_acc, None
elif re:
return mpf_abs(re), None, re_acc, None
else:
return None, None, None, None
def get_complex_part(expr, no, prec, options):
"""Selector no = 0 for real part, no = 1 for imaginary part."""
workprec = prec
i = 0
while 1:
res = evalf(expr, workprec, options)
value, accuracy = res[no::2]
if (not value) or accuracy >= prec or expr.is_Float:
return value, None, accuracy, None
workprec += max(30, 2**i)
i += 1
def evalf_abs(expr, prec, options):
return get_abs(expr.args[0], prec, options)
def evalf_re(expr, prec, options):
return get_complex_part(expr.args[0], 0, prec, options)
def evalf_im(expr, prec, options):
return get_complex_part(expr.args[0], 1, prec, options)
def finalize_complex(re, im, prec):
assert re != fzero or im != fzero
if re == fzero:
return None, im, None, prec
elif im == fzero:
return re, None, prec, None
size_re = fastlog(re)
size_im = fastlog(im)
if size_re > size_im:
re_acc = prec
im_acc = prec + min(-(size_re - size_im), 0)
else:
im_acc = prec
re_acc = prec + min(-(size_im - size_re), 0)
return re, im, re_acc, im_acc
def chop_parts(value, prec):
"""Chop off tiny real or complex parts."""
re, im, re_acc, im_acc = value
# chop based on absolute value
if re and re not in _infs_nan and (fastlog(re) < -prec + 4):
re, re_acc = None, None
if im and im not in _infs_nan and (fastlog(im) < -prec + 4):
im, im_acc = None, None
return re, im, re_acc, im_acc
def check_target(expr, result, prec):
a = complex_accuracy(result)
if a < prec:
raise PrecisionExhausted('Failed to distinguish the expression: '
f'\n\n{expr}\n\nfrom zero. Try simplifying '
'the input, using chop=True, or providing '
'a higher maxn for evalf')
############################################################################
# #
# Arithmetic operations #
# #
############################################################################
def add_terms(terms, prec, target_prec):
"""
Helper for evalf_add. Adds a list of (mpfval, accuracy) terms.
Returns
=======
- None, None if there are no non-zero terms;
- terms[0] if there is only 1 term;
- scaled_zero if the sum of the terms produces a zero by cancellation
e.g. mpfs representing 1 and -1 would produce a scaled zero which need
special handling since they are not actually zero and they are purposely
malformed to ensure that they can't be used in anything but accuracy
calculations;
- a tuple that is scaled to target_prec that corresponds to the
sum of the terms.
The returned mpf tuple will be normalized to target_prec; the input
prec is used to define the working precision.
XXX explain why this is needed and why one can't just loop using mpf_add
"""
terms = [t for t in terms if not iszero(t)]
if not terms:
return None, None
elif len(terms) == 1:
return terms[0]
# see if any argument is NaN or oo and thus warrants a special return
special = []
from .numbers import Float, nan
for t in terms:
arg = Float._new(t[0], 1)
if arg is nan or arg.is_infinite:
special.append(arg)
if special:
from .add import Add
rv = evalf(Add(*special), prec + 4, {})
return rv[0], rv[2]
working_prec = 2*prec
sum_man, sum_exp, absolute_error = 0, 0, MINUS_INF
for x, accuracy in terms:
sign, man, exp, bc = x
if sign:
man = -man
absolute_error = max(absolute_error, bc + exp - accuracy)
delta = exp - sum_exp
if exp >= sum_exp:
# x much larger than existing sum?
# first: quick test
if ((delta > working_prec) and
((not sum_man) or
delta - bitcount(abs(sum_man)) > working_prec)):
sum_man = man
sum_exp = exp
else:
sum_man += (man << delta)
else:
delta = -delta
# x much smaller than existing sum?
if delta - bc > working_prec:
if not sum_man:
sum_man, sum_exp = man, exp
else:
sum_man = (sum_man << delta) + man
sum_exp = exp
if not sum_man:
return scaled_zero(absolute_error)
if sum_man < 0:
sum_sign = 1
sum_man = -sum_man
else:
sum_sign = 0
sum_bc = bitcount(sum_man)
sum_accuracy = sum_exp + sum_bc - absolute_error
r = normalize(sum_sign, sum_man, sum_exp, sum_bc, target_prec,
rnd), sum_accuracy
return r
def evalf_add(v, prec, options):
res = pure_complex(v)
if res:
h, c = res
re, _, re_acc, _ = evalf(h, prec, options)
im, _, im_acc, _ = evalf(c, prec, options)
return re, im, re_acc, im_acc
oldmaxprec = options['maxprec']
i = 0
target_prec = prec
while 1:
options['maxprec'] = min(oldmaxprec, 2*prec)
terms = [evalf(arg, prec + 10, options) for arg in v.args]
re, re_acc = add_terms(
[a[0::2] for a in terms if a[0]], prec, target_prec)
im, im_acc = add_terms(
[a[1::2] for a in terms if a[1]], prec, target_prec)
acc = complex_accuracy((re, im, re_acc, im_acc))
if acc >= target_prec:
break
if (prec - target_prec) > options['maxprec']:
break
prec = prec + max(10 + 2**i, target_prec - acc)
i += 1
options['maxprec'] = oldmaxprec
if iszero(re, scaled=True):
re = scaled_zero(re)
if iszero(im, scaled=True):
im = scaled_zero(im)
return re, im, re_acc, im_acc
def evalf_mul(v, prec, options):
res = pure_complex(v)
if res:
# the only pure complex that is a mul is h*I
_, h = res
im, _, im_acc, _ = evalf(h, prec, options)
return None, im, None, im_acc
args = list(v.args)
# see if any argument is NaN or oo and thus warrants a special return
special, other = [], []
from .numbers import Float, Integer, nan
for arg in args:
arg = evalf(arg, prec, options)
if arg[0] is None:
continue
arg = Float._new(arg[0], 1)
if arg is nan or arg.is_infinite:
special.append(arg)
else:
other.append(arg)
if special:
from .mul import Mul
other = Mul(*other)
special = Mul(*special)
return evalf(special*other, prec + 4, {})
# With guard digits, multiplication in the real case does not destroy
# accuracy. This is also true in the complex case when considering the
# total accuracy; however accuracy for the real or imaginary parts
# separately may be lower.
acc = prec
# XXX: big overestimate
working_prec = prec + len(args) + 5
# Empty product is 1
start = man, exp, bc = MPZ(1), 0, 1
# First, we multiply all pure real or pure imaginary numbers.
# direction tells us that the result should be multiplied by
# I**direction; all other numbers get put into complex_factors
# to be multiplied out after the first phase.
last = len(args)
direction = 0
args.append(Integer(1))
complex_factors = []
for i, arg in enumerate(args):
if i != last and pure_complex(arg):
args[-1] = (args[-1]*arg).expand()
continue
if i == last and arg is Integer(1):
continue
re, im, re_acc, im_acc = evalf(arg, working_prec, options)
if re and im:
complex_factors.append((re, im, re_acc, im_acc))
continue
if re:
(s, m, e, b), w_acc = re, re_acc
elif im:
(s, m, e, b), w_acc = im, im_acc
direction += 1
else:
return None, None, None, None
direction += 2*s
man *= m
exp += e
bc += b
if bc > 3*working_prec:
man >>= working_prec
exp += working_prec
acc = min(acc, w_acc)
sign = (direction & 2) >> 1
if not complex_factors:
v = normalize(sign, man, exp, bitcount(man), prec, rnd)
# multiply by i
if direction & 1:
return None, v, None, acc
else:
return v, None, acc, None
else:
# initialize with the first term
if (man, exp, bc) != start:
# there was a real part; give it an imaginary part
re, im = (sign, man, exp, bitcount(man)), (0, MPZ(0), 0, 0)
i0 = 0
else:
# there is no real part to start (other than the starting 1)
wre, wim, wre_acc, wim_acc = complex_factors[0]
acc = min(acc,
complex_accuracy((wre, wim, wre_acc, wim_acc)))
re = wre
im = wim
i0 = 1
for wre, wim, wre_acc, wim_acc in complex_factors[i0:]:
# acc is the overall accuracy of the product; we aren't
# computing exact accuracies of the product.
acc = min(acc,
complex_accuracy((wre, wim, wre_acc, wim_acc)))
use_prec = working_prec
A = mpf_mul(re, wre, use_prec)
B = mpf_mul(mpf_neg(im), wim, use_prec)
C = mpf_mul(re, wim, use_prec)
D = mpf_mul(im, wre, use_prec)
re = mpf_add(A, B, use_prec)
im = mpf_add(C, D, use_prec)
# multiply by I
if direction & 1:
re, im = mpf_neg(im), re
return re, im, acc, acc
def evalf_pow(v, prec, options):
from .numbers import E, Rational
target_prec = prec
base, exp = v.args
# We handle x**n separately. This has two purposes: 1) it is much
# faster, because we avoid calling evalf on the exponent, and 2) it
# allows better handling of real/imaginary parts that are exactly zero
if exp.is_Integer:
p = exp.numerator
# Exact
if not p:
return fone, None, prec, None
# Exponentiation by p magnifies relative error by |p|, so the
# base must be evaluated with increased precision if p is large
prec += int(math.log(abs(p), 2))
re, im, *_ = evalf(base, prec + 5, options)
# Real to integer power
if re and not im:
return mpf_pow_int(re, p, target_prec), None, target_prec, None
# (x*I)**n = I**n * x**n
if im and not re:
z = mpf_pow_int(im, p, target_prec)
case = p % 4
if case == 0:
return z, None, target_prec, None
elif case == 1:
return None, z, None, target_prec
elif case == 2:
return mpf_neg(z), None, target_prec, None
else:
return None, mpf_neg(z), None, target_prec
# Zero raised to an integer power
if not re:
return None, None, None, None
# General complex number to arbitrary integer power
re, im = libmp.mpc_pow_int((re, im), p, prec)
# Assumes full accuracy in input
return finalize_complex(re, im, target_prec)
# Pure square root
if exp is Rational(1, 2):
xre, xim, _, _ = evalf(base, prec + 5, options)
# General complex square root
if xim:
re, im = libmp.mpc_sqrt((xre or fzero, xim), prec)
return finalize_complex(re, im, prec)
if not xre:
return None, None, None, None
# Square root of a negative real number
if mpf_lt(xre, fzero):
return None, mpf_sqrt(mpf_neg(xre), prec), None, prec
# Positive square root
return mpf_sqrt(xre, prec), None, prec, None
# We first evaluate the exponent to find its magnitude
# This determines the working precision that must be used
prec += 10
yre, yim, _, _ = evalf(exp, prec, options)
# Special cases: x**0
if not (yre or yim):
return fone, None, prec, None
ysize = fastlog(yre)
# Restart if too big
# XXX: prec + ysize might exceed maxprec
if ysize > 5:
prec += ysize
yre, yim, _, _ = evalf(exp, prec, options)
# Pure exponential function; no need to evalf the base
if base is E:
if yim:
re, im = libmp.mpc_exp((yre or fzero, yim), prec)
return finalize_complex(re, im, target_prec)
return mpf_exp(yre, target_prec), None, target_prec, None
xre, xim, _, _ = evalf(base, prec + 5, options)
# 0**y
if not (xre or xim):
return None, None, None, None
# (real ** complex) or (complex ** complex)
if yim:
re, im = libmp.mpc_pow(
(xre or fzero, xim or fzero), (yre or fzero, yim),
target_prec)
return finalize_complex(re, im, target_prec)
# complex ** real
if xim:
re, im = libmp.mpc_pow_mpf((xre or fzero, xim), yre, target_prec)
return finalize_complex(re, im, target_prec)
# negative ** real
elif mpf_lt(xre, fzero):
re, im = libmp.mpc_pow_mpf((xre, fzero), yre, target_prec)
return finalize_complex(re, im, target_prec)
# positive ** real
else:
return mpf_pow(xre, yre, target_prec), None, target_prec, None
############################################################################
# #
# Special functions #
# #
############################################################################
def evalf_trig(v, prec, options):
"""
This function handles sin and cos of complex arguments.
TODO: should also handle tan of complex arguments.
"""
from ..functions import cos, sin
if isinstance(v, cos):
func = mpf_cos
elif isinstance(v, sin):
func = mpf_sin
else:
raise NotImplementedError
arg = v.args[0]
# 20 extra bits is possibly overkill. It does make the need
# to restart very unlikely
xprec = prec + 20
re, im, *_ = evalf(arg, xprec, options)
if im:
if 'subs' in options:
v = v.subs(options['subs'])
return evalf(v._eval_evalf(prec), prec, options)
if not re:
if isinstance(v, cos):
return fone, None, prec, None
elif isinstance(v, sin):
return None, None, None, None
else:
raise NotImplementedError
# For trigonometric functions, we are interested in the
# fixed-point (absolute) accuracy of the argument.
xsize = fastlog(re)
# Magnitude <= 1.0. OK to compute directly, because there is no
# danger of hitting the first root of cos (with sin, magnitude
# <= 2.0 would actually be ok)
if xsize < 1:
return func(re, prec, rnd), None, prec, None
# Very large
if xsize >= 10:
xprec = prec + xsize
re, im, *_ = evalf(arg, xprec, options)
# Need to repeat in case the argument is very close to a
# multiple of pi (or pi/2), hitting close to a root
while 1:
y = func(re, prec, rnd)
ysize = fastlog(y)
gap = -ysize
accuracy = (xprec - xsize) - gap
if accuracy < prec:
if xprec > options['maxprec']:
return y, None, accuracy, None
xprec += gap
re, im, *_ = evalf(arg, xprec, options)
continue
return y, None, prec, None
def evalf_log(expr, prec, options):
from ..functions import Abs, log
from .add import Add
if len(expr.args) > 1:
expr = expr.doit()
return evalf(expr, prec, options)
arg = expr.args[0]
workprec = prec + 10
xre, xim, *_ = evalf(arg, workprec, options)
if xim:
# XXX: use get_abs etc instead
re = evalf_log(
log(Abs(arg, evaluate=False), evaluate=False), prec, options)
im = mpf_atan2(xim, xre or fzero, prec)
return re[0], im, re[2], prec
imaginary_term = (mpf_cmp(xre, fzero) < 0)
re = mpf_log(mpf_abs(xre), prec, rnd)
size = fastlog(re)
if prec - size > workprec:
# We actually need to compute 1+x accurately, not x
arg = Add(-1, arg, evaluate=False)
xre, xim, _, _ = evalf_add(arg, prec, options)
prec2 = workprec - fastlog(xre)
# xre is now x - 1 so we add 1 back here to calculate x
re = mpf_log(mpf_abs(mpf_add(xre, fone, prec2)), prec, rnd)
re_acc = prec
if imaginary_term:
return re, mpf_pi(prec), re_acc, prec
else:
return re, None, re_acc, None
def evalf_atan(v, prec, options):
arg = v.args[0]
xre, xim, *_ = evalf(arg, prec + 5, options)
if xre is xim is None:
return (None,)*4
if xim:
raise NotImplementedError
return mpf_atan(xre, prec, rnd), None, prec, None
def evalf_subs(prec, subs):
"""Change all Float entries in `subs` to have precision prec."""
newsubs = {}
for a, b in subs.items():
b = sympify(b)
if b.is_Float:
b = b._eval_evalf(prec)
newsubs[a] = b
return newsubs
def evalf_piecewise(expr, prec, options):
if 'subs' in options:
expr = expr.subs(evalf_subs(prec, options['subs']))
newopts = options.copy()
del newopts['subs']
return evalf(expr, prec, newopts)
# We still have undefined symbols
raise NotImplementedError
def evalf_bernoulli(expr, prec, options):
arg = expr.args[0]
if not arg.is_Integer:
raise ValueError('Bernoulli number index must be an integer')
n = int(arg)
b = mpf_bernoulli(n, prec, rnd)
if b == fzero:
return None, None, None, None
return b, None, prec, None
############################################################################
# #
# High-level operations #
# #
############################################################################
def as_mpmath(x, prec, options):
from .numbers import oo
x = sympify(x)
if x == 0:
return mpf(0)
if x == oo:
return mpf('inf')
if x == -oo:
return mpf('-inf')
# XXX
re, im, _, _ = evalf(x, prec, options)
if im:
return mpc(re or fzero, im)
return mpf(re)
def do_integral(expr, prec, options):
func = expr.args[0]
x, xlow, xhigh = expr.args[1]
if xlow == xhigh:
xlow = xhigh = 0
elif x not in func.free_symbols:
# only the difference in limits matters in this case
# so if there is a symbol in common that will cancel
# out when taking the difference, then use that
# difference
if xhigh.free_symbols & xlow.free_symbols:
diff = xhigh - xlow
if not diff.free_symbols:
xlow, xhigh = 0, diff
oldmaxprec = options['maxprec']
options['maxprec'] = min(oldmaxprec, 2*prec)
with workprec(prec + 5):
xlow = as_mpmath(xlow, prec + 15, options)
xhigh = as_mpmath(xhigh, prec + 15, options)
# Integration is like summation, and we can phone home from
# the integrand function to update accuracy summation style
# Note that this accuracy is inaccurate, since it fails
# to account for the variable quadrature weights,
# but it is better than nothing
from ..functions import cos, sin
from .numbers import pi
from .symbol import Wild
have_part = [False, False]
max_real_term = [MINUS_INF]
max_imag_term = [MINUS_INF]
def f(t):
re, im, *_ = evalf(func, mp.prec, {'subs': {x: t}, 'maxprec': DEFAULT_MAXPREC})
have_part[0] = re or have_part[0]
have_part[1] = im or have_part[1]
max_real_term[0] = max(max_real_term[0], fastlog(re))
max_imag_term[0] = max(max_imag_term[0], fastlog(im))
if im:
return mpc(re or fzero, im)
return mpf(re or fzero)
if options.get('quad') == 'osc':
A = Wild('A', exclude=[x])
B = Wild('B', exclude=[x])
D = Wild('D')
m = func.match(cos(A*x + B)*D)
if not m:
m = func.match(sin(A*x + B)*D)
if not m:
raise ValueError('An integrand of the form sin(A*x+B)*f(x) '
'or cos(A*x+B)*f(x) is required for oscillatory quadrature')
period = as_mpmath(2*pi/m[A], prec + 15, options)
result = quadosc(f, [xlow, xhigh], period=period)
# XXX: quadosc does not do error detection yet
quadrature_error = MINUS_INF
else:
result, quadrature_error = quadts(f, [xlow, xhigh], error=1)
quadrature_error = fastlog(quadrature_error._mpf_)
options['maxprec'] = oldmaxprec
if have_part[0]:
re = result.real._mpf_
if re == fzero:
re, re_acc = scaled_zero(
min(-prec, -max_real_term[0], -quadrature_error))
re = scaled_zero(re) # handled ok in evalf_integral
else:
re_acc = -max(max_real_term[0] - fastlog(re) -
prec, quadrature_error)
else:
re, re_acc = None, None
if have_part[1]:
im = result.imag._mpf_
if im == fzero:
im, im_acc = scaled_zero(
min(-prec, -max_imag_term[0], -quadrature_error))
im = scaled_zero(im) # handled ok in evalf_integral
else:
im_acc = -max(max_imag_term[0] - fastlog(im) -
prec, quadrature_error)
else:
im, im_acc = None, None
result = re, im, re_acc, im_acc
return result
def evalf_integral(expr, prec, options):
limits = expr.limits
if len(limits) != 1 or len(limits[0]) != 3:
raise NotImplementedError
workprec = prec
i = 0
maxprec = options.get('maxprec', INF)
while 1:
result = do_integral(expr, workprec, options)
accuracy = complex_accuracy(result)
if accuracy >= prec: # achieved desired precision
break
if workprec >= maxprec: # can't increase accuracy any more
break
if accuracy == -1:
# maybe the answer really is zero and maybe we just haven't increased
# the precision enough. So increase by doubling to not take too long
# to get to maxprec.
workprec *= 2
else:
workprec += max(prec, 2**i)
workprec = min(workprec, maxprec)
i += 1
return result
def check_convergence(numer, denom, n):
"""
Returns (h, g, p) where
-- h is:
> 0 for convergence of rate 1/factorial(n)**h
< 0 for divergence of rate factorial(n)**(-h)
= 0 for geometric or polynomial convergence or divergence
-- abs(g) is:
> 1 for geometric convergence of rate 1/h**n
< 1 for geometric divergence of rate h**n
= 1 for polynomial convergence or divergence
(g < 0 indicates an alternating series)
-- p is:
> 1 for polynomial convergence of rate 1/n**h
<= 1 for polynomial divergence of rate n**(-h)
"""
npol = numer.as_poly(n)
dpol = denom.as_poly(n)
p = npol.degree()
q = dpol.degree()
rate = q - p
if rate:
return rate, None, None
constant = dpol.LC() / npol.LC()
if abs(constant) != 1:
return rate, constant, None
if npol.degree() == dpol.degree() == 0:
return rate, constant, 0
pc = npol.all_coeffs()[-2]
qc = dpol.all_coeffs()[-2]
return rate, constant, (qc - pc)/dpol.LC()
def hypsum(expr, n, start, prec):
"""
Sum a rapidly convergent infinite hypergeometric series with
given general term, e.g. e = hypsum(1/factorial(n), n). The
quotient between successive terms must be a quotient of integer
polynomials.
"""
from ..simplify import hypersimp
from ..utilities import lambdify
from .numbers import Float
if prec == float('inf'):
raise NotImplementedError('does not support inf prec')
if start:
expr = expr.subs({n: n + start})
hs = hypersimp(expr, n)
if hs is None:
raise NotImplementedError('a hypergeometric series is required')
num, den = hs.as_numer_denom()
func1 = lambdify(n, num)
func2 = lambdify(n, den)
h, g, p = check_convergence(num, den, n)
if h < 0:
raise ValueError(f'Sum diverges like (n!)^{int(-h)}')
term = expr.subs({n: 0})
if not term.is_Rational:
raise NotImplementedError('Non rational term functionality is not implemented.')
# Direct summation if geometric or faster
if h > 0 or (h == 0 and abs(g) > 1):
term = (MPZ(term.numerator) << prec) // term.denominator
s = term
k = 1
while abs(term) > 5:
term *= MPZ(func1(k - 1))
term //= MPZ(func2(k - 1))
s += term
k += 1
return from_man_exp(s, -prec)
else:
alt = g < 0
if abs(g) < 1:
raise ValueError(f'Sum diverges like ({int(abs(1/g))})^n')
if p < 1 or (p == 1 and not alt):
raise ValueError(f'Sum diverges like n^{int(-p)}')
# We have polynomial convergence: use Richardson extrapolation
vold = None
ndig = prec_to_dps(prec)
while True:
# Need to use at least quad precision because a lot of cancellation
# might occur in the extrapolation process; we check the answer to
# make sure that the desired precision has been reached, too.
prec2 = 4*prec
term0 = (MPZ(term.numerator) << prec2) // term.denominator
def summand(k, _term=[term0]):
if k:
k = int(k)
_term[0] *= MPZ(func1(k - 1))
_term[0] //= MPZ(func2(k - 1))
return make_mpf(from_man_exp(_term[0], -prec2))
with workprec(prec):
v = nsum(summand, [0, mpmath_inf], method='richardson')
vf = Float(v, ndig)
if vold is not None and vold == vf:
break
prec += prec # double precision each time
vold = vf
return v._mpf_
def evalf_prod(expr, prec, options):
from ..concrete import Sum
if all((l[1] - l[2]).is_Integer for l in expr.limits):
re, im, re_acc, im_acc = evalf(expr.doit(), prec=prec, options=options)
else:
re, im, re_acc, im_acc = evalf(expr.rewrite(Sum), prec=prec, options=options)
return re, im, re_acc, im_acc
def evalf_sum(expr, prec, options):
from .numbers import Float, Integer, oo
if 'subs' in options:
expr = expr.subs(options['subs'])
func = expr.function
limits = expr.limits
if len(limits) != 1 or len(limits[0]) != 3:
raise NotImplementedError
if func is Integer(0):
return mpf(0), None, None, None
prec2 = prec + 10
try:
n, a, b = limits[0]
if b != oo or a != int(a):
raise NotImplementedError
# Use fast hypergeometric summation if possible
v = hypsum(func, n, int(a), prec2)
delta = prec - fastlog(v)
if fastlog(v) < -10:
v = hypsum(func, n, int(a), delta)
return v, None, min(prec, delta), None
except NotImplementedError:
# Euler-Maclaurin summation for general series
m, err, eps = prec, oo, Float(2.0)**(-prec)
while err > eps:
m <<= 1
s, err = expr.euler_maclaurin(m=m, n=m, eps=eps,
eval_integral=False)
err = err.evalf(strict=False)
err = fastlog(evalf(abs(err), 20, options)[0])
re, im, re_acc, im_acc = evalf(s, prec2, options)
if re_acc is None:
re_acc = -err
if im_acc is None:
im_acc = -err
return re, im, re_acc, im_acc
############################################################################
# #
# Symbolic interface #
# #
############################################################################
def evalf_symbol(x, prec, options):
val = options['subs'][x]
if isinstance(val, mpf):
if not val:
return None, None, None, None
return val._mpf_, None, prec, None
else:
if '_cache' not in options:
options['_cache'] = {}
cache = options['_cache']
cached, cached_prec = cache.get(x, (None, MINUS_INF))
if cached_prec >= prec:
return cached
v = evalf(sympify(val), prec, options)
cache[x] = (v, prec)
return v
evalf_table = None
def _create_evalf_table():
global evalf_table
from ..concrete.products import Product
from ..concrete.summations import Sum
from ..functions.combinatorial.numbers import bernoulli
from ..functions.elementary.complexes import Abs, im, re
from ..functions.elementary.exponential import log
from ..functions.elementary.piecewise import Piecewise
from ..functions.elementary.trigonometric import atan, cos, sin
from ..integrals.integrals import Integral
from .add import Add
from .mul import Mul
from .numbers import (Exp1, Float, Half, ImaginaryUnit, Integer, NaN,
NegativeOne, One, Pi, Rational, Zero)
from .power import Pow
from .symbol import Dummy, Symbol
evalf_table = {
Symbol: evalf_symbol,
Dummy: evalf_symbol,
Float: lambda x, prec, options: (x._mpf_, None, prec if prec <= x._prec else x._prec, None),
Rational: lambda x, prec, options: (from_rational(x.numerator, x.denominator, prec),
None, prec, None),
Integer: lambda x, prec, options: (from_int(x.numerator, prec),
None, prec, None),
Zero: lambda x, prec, options: (None, None, prec, None),
One: lambda x, prec, options: (fone, None, prec, None),
Half: lambda x, prec, options: (fhalf, None, prec, None),
Pi: lambda x, prec, options: (mpf_pi(prec), None, prec, None),
Exp1: lambda x, prec, options: (mpf_e(prec), None, prec, None),
ImaginaryUnit: lambda x, prec, options: (None, fone, None, prec),
NegativeOne: lambda x, prec, options: (fnone, None, prec, None),
NaN: lambda x, prec, options: (fnan, None, prec, None),
cos: evalf_trig,
sin: evalf_trig,
Add: evalf_add,
Mul: evalf_mul,
Pow: evalf_pow,
log: evalf_log,
atan: evalf_atan,
Abs: evalf_abs,
re: evalf_re,
im: evalf_im,
Integral: evalf_integral,
Sum: evalf_sum,
Product: evalf_prod,
Piecewise: evalf_piecewise,
bernoulli: evalf_bernoulli,
}
def evalf(x, prec, options):
from ..functions import im as im_
from ..functions import re as re_
try:
rf = evalf_table[x.func]
r = rf(x, prec, options)
except KeyError as exc:
try:
# Fall back to ordinary evalf if possible
if 'subs' in options:
x = x.subs(evalf_subs(prec, options['subs']))
re, im = x._eval_evalf(prec).as_real_imag()
if re.has(re_) or im.has(im_):
raise NotImplementedError from exc
if re == 0:
re = None
reprec = None
else:
re = re._to_mpmath(prec)._mpf_
reprec = prec
if im == 0:
im = None
imprec = None
else:
im = im._to_mpmath(prec)._mpf_
imprec = prec
r = re, im, reprec, imprec
except AttributeError as exc:
raise NotImplementedError from exc
chop = options.get('chop', False)
if chop:
if chop is True:
chop_prec = prec
else:
# convert (approximately) from given tolerance;
# the formula here will will make 1e-i rounds to 0 for
# i in the range +/-27 while 2e-i will not be chopped
chop_prec = round(-3.321*math.log10(chop) + 2.5)
r = chop_parts(r, chop_prec)
if options.get('strict'):
check_target(x, r, prec)
return r
class EvalfMixin:
"""Mixin class adding evalf capability."""
def evalf(self, dps=15, subs=None, maxn=110, chop=False, strict=True, quad=None):
"""
Evaluate the given formula to an accuracy of dps decimal digits.
Optional keyword arguments:
subs=<dict>
Substitute numerical values for symbols, e.g.
subs={x:3, y:1+pi}. The substitutions must be given as a
dictionary.
maxn=<integer>
Allow a maximum temporary working precision of maxn digits
(default=110)
chop=<bool>
Replace tiny real or imaginary parts in subresults
by exact zeros (default=False)
strict=<bool>
Raise PrecisionExhausted if any subresult fails to evaluate
to full accuracy, given the available maxprec
(default=True)
quad=<str>
Choose algorithm for numerical quadrature. By default,
tanh-sinh quadrature is used. For oscillatory
integrals on an infinite interval, try quad='osc'.
"""
from .numbers import Float, I, Integer
if subs and is_sequence(subs):
raise TypeError('subs must be given as a dictionary')
if not evalf_table:
_create_evalf_table()
prec = dps_to_prec(dps)
options = {'maxprec': max(prec, int(maxn*LG10)), 'chop': chop,
'strict': strict}
if subs is not None:
options['subs'] = subs
if quad is not None:
options['quad'] = quad
try:
result = evalf(self, prec + 4, options)
except PrecisionExhausted:
if self.is_Float and self._prec >= prec:
return Float._new(self._mpf_, prec)
else:
raise
except NotImplementedError:
# Fall back to the ordinary evalf
v = self._eval_evalf(prec) # pylint: disable=assignment-from-none
if v is None:
return self
else:
# Normalize result
return v.subs({_: _.evalf(dps, strict=strict)
for _ in v.atoms(Float)})
re, im, re_acc, im_acc = result
if re:
p = max(min(prec, re_acc), 1)
re = Float._new(re, p)
else:
re = Integer(0)
if im:
p = max(min(prec, im_acc), 1)
im = Float._new(im, p)
return re + im*I
else:
return re
def _evalf(self, prec):
"""Helper for evalf. Does the same thing but takes binary precision."""
r = self._eval_evalf(prec) # pylint: disable=assignment-from-none
if r is None:
r = self
return r
def _eval_evalf(self, prec):
return
def _to_mpmath(self, prec):
# mpmath functions accept ints as input
errmsg = 'cannot convert to mpmath number'
if hasattr(self, '_as_mpf_val'):
return make_mpf(self._as_mpf_val(prec))
try:
re, im, _, _ = evalf(self, prec, {'maxprec': DEFAULT_MAXPREC})
if im:
if not re:
re = fzero
return make_mpc((re, im))
elif re:
return make_mpf(re)
else:
return make_mpf(fzero)
except NotImplementedError as exc:
v = self._eval_evalf(prec) # pylint: disable=assignment-from-none
if v is None:
raise ValueError(errmsg) from exc
re, im = v.as_real_imag()
if re.is_Float:
re = re._mpf_
else:
raise ValueError(errmsg) from exc
if im.is_Float:
im = im._mpf_
else:
raise ValueError(errmsg) from exc
return make_mpc((re, im))
def N(x, dps=15, **options):
r"""
Calls x.evalf(dps, \*\*options).
Examples
========
>>> Sum(1/k**k, (k, 1, oo))
Sum(k**(-k), (k, 1, oo))
>>> N(_, 4)
1.291
See Also
========
diofant.core.evalf.EvalfMixin.evalf
"""
return sympify(x).evalf(dps, **options)
| bsd-3-clause | 90257d3ac540e11c70dcd45141bbdac9 | 32.190977 | 100 | 0.534546 | 3.657635 | false | false | false | false |
diofant/diofant | diofant/utilities/iterables.py | 1 | 58179 | import operator
from collections import defaultdict
from itertools import (combinations, combinations_with_replacement,
permutations, product)
# this is the logical location of these functions
from ..core.compatibility import as_int, is_sequence, iterable
from .enumerative import (MultisetPartitionTraverser, list_visitor,
multiset_partitions_taocp)
def flatten(iterable, levels=None, cls=None):
"""
Recursively denest iterable containers.
>>> flatten([1, 2, 3])
[1, 2, 3]
>>> flatten([1, 2, [3]])
[1, 2, 3]
>>> flatten([1, [2, 3], [4, 5]])
[1, 2, 3, 4, 5]
>>> flatten([1.0, 2, (1, None)])
[1.0, 2, 1, None]
If you want to denest only a specified number of levels of
nested containers, then set ``levels`` flag to the desired
number of levels::
>>> ls = [[(-2, -1), (1, 2)], [(0, 0)]]
>>> flatten(ls, levels=1)
[(-2, -1), (1, 2), (0, 0)]
If cls argument is specified, it will only flatten instances of that
class, for example:
>>> class MyOp(Basic):
... pass
...
>>> flatten([MyOp(1, MyOp(2, 3))], cls=MyOp)
[1, 2, 3]
adapted from https://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks
"""
if levels is not None:
if not levels:
return iterable
elif levels > 0:
levels -= 1
else:
raise ValueError(
f'expected non-negative number of levels, got {levels}')
if cls is None:
def reducible(x):
return is_sequence(x, set)
else:
def reducible(x):
return isinstance(x, cls)
result = []
for el in iterable:
if reducible(el):
if hasattr(el, 'args'):
el = el.args
result.extend(flatten(el, levels=levels, cls=cls))
else:
result.append(el)
return result
def unflatten(iter, n=2):
"""Group ``iter`` into tuples of length ``n``. Raise an error if
the length of ``iter`` is not a multiple of ``n``.
"""
if n < 1 or len(iter) % n:
raise ValueError(f'iter length is not a multiple of {n:d}')
return list(zip(*(iter[i::n] for i in range(n))))
def group(seq, multiple=True):
"""
Splits a sequence into a list of lists of equal, adjacent elements.
Examples
========
>>> group([1, 1, 1, 2, 2, 3])
[[1, 1, 1], [2, 2], [3]]
>>> group([1, 1, 1, 2, 2, 3], multiple=False)
[(1, 3), (2, 2), (3, 1)]
>>> group([1, 1, 3, 2, 2, 1], multiple=False)
[(1, 2), (3, 1), (2, 2), (1, 1)]
See Also
========
multiset
"""
if not seq:
return []
current, groups = [seq[0]], []
for elem in seq[1:]:
if elem == current[-1]:
current.append(elem)
else:
groups.append(current)
current = [elem]
groups.append(current)
if multiple:
return groups
for i, current in enumerate(groups):
groups[i] = (current[0], len(current))
return groups
def multiset(seq):
"""Return the hashable sequence in multiset form with values being the
multiplicity of the item in the sequence.
Examples
========
>>> multiset('mississippi')
{'i': 4, 'm': 1, 'p': 2, 's': 4}
See Also
========
group
"""
rv = defaultdict(int)
for s in seq:
rv[s] += 1
return dict(rv)
def postorder_traversal(node, keys=None):
"""
Do a postorder traversal of a tree.
This generator recursively yields nodes that it has visited in a postorder
fashion. That is, it descends through the tree depth-first to yield all of
a node's children's postorder traversal before yielding the node itself.
Parameters
==========
node : diofant expression
The expression to traverse.
keys : (default None) sort key(s)
The key(s) used to sort args of Basic objects. When None, args of Basic
objects are processed in arbitrary order. If key is defined, it will
be passed along to ordered() as the only key(s) to use to sort the
arguments; if ``key`` is simply True then the default keys of
``ordered`` will be used (node count and default_sort_key).
Yields
======
subtree : diofant expression
All of the subtrees in the tree.
Examples
========
>>> from diofant.abc import w
The nodes are returned in the order that they are encountered unless key
is given; simply passing key=True will guarantee that the traversal is
unique.
>>> list(postorder_traversal(w + (x + y)*z, keys=True))
[w, z, x, y, x + y, z*(x + y), w + z*(x + y)]
"""
from ..core import Basic
if isinstance(node, Basic):
args = node.args
if keys:
if keys != 1:
args = ordered(args, keys, default=False)
else:
args = ordered(args)
for arg in args:
for subtree in postorder_traversal(arg, keys):
yield subtree
elif iterable(node):
for item in node:
for subtree in postorder_traversal(item, keys):
yield subtree
yield node
def variations(seq, n, repetition=False):
"""Returns a generator of the n-sized variations of ``seq`` (size N).
``repetition`` controls whether items in ``seq`` can appear more than once;
Examples
========
variations(seq, n) will return N! / (N - n)! permutations without
repetition of seq's elements:
>>> list(variations([1, 2], 2))
[(1, 2), (2, 1)]
variations(seq, n, True) will return the N**n permutations obtained
by allowing repetition of elements:
>>> list(variations([1, 2], 2, repetition=True))
[(1, 1), (1, 2), (2, 1), (2, 2)]
If you ask for more items than are in the set you get the empty set unless
you allow repetitions:
>>> list(variations([0, 1], 3, repetition=False))
[]
>>> list(variations([0, 1], 3, repetition=True))[:4]
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)]
"""
if not repetition:
seq = tuple(seq)
if len(seq) < n:
return
for i in permutations(seq, n):
yield i
else:
if n == 0:
yield ()
else:
for i in product(seq, repeat=n):
yield i
def subsets(seq, k=None, repetition=False):
"""Generates all k-subsets (combinations) from an n-element set, seq.
A k-subset of an n-element set is any subset of length exactly k. The
number of k-subsets of an n-element set is given by binomial(n, k),
whereas there are 2**n subsets all together. If k is None then all
2**n subsets will be returned from shortest to longest.
Examples
========
subsets(seq, k) will return the n!/k!/(n - k)! k-subsets (combinations)
without repetition, i.e. once an item has been removed, it can no
longer be "taken":
>>> from diofant.utilities.iterables import subsets
>>> list(subsets([1, 2], 2))
[(1, 2)]
>>> list(subsets([1, 2]))
[(), (1,), (2,), (1, 2)]
>>> list(subsets([1, 2, 3], 2))
[(1, 2), (1, 3), (2, 3)]
subsets(seq, k, repetition=True) will return the (n - 1 + k)!/k!/(n - 1)!
combinations *with* repetition:
>>> list(subsets([1, 2], 2, repetition=True))
[(1, 1), (1, 2), (2, 2)]
If you ask for more items than are in the set you get the empty set unless
you allow repetitions:
>>> list(subsets([0, 1], 3, repetition=False))
[]
>>> list(subsets([0, 1], 3, repetition=True))
[(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)]
"""
if k is None:
for k in range(len(seq) + 1):
for i in subsets(seq, k, repetition):
yield i
else:
if not repetition:
for i in combinations(seq, k):
yield i
else:
for i in combinations_with_replacement(seq, k):
yield i
def filter_symbols(iterator, exclude):
"""
Only yield elements from `iterator` that do not occur in `exclude`.
Parameters
==========
iterator : iterable
iterator to take elements from
exclude : iterable
elements to exclude
Returns
=======
iterator : iterator
filtered iterator
"""
exclude = set(exclude)
for s in iterator:
if s not in exclude:
yield s
def numbered_symbols(prefix='x', cls=None, start=0, exclude=[], *args, **assumptions):
"""
Generate an infinite stream of Symbols consisting of a prefix and
increasing subscripts provided that they do not occur in `exclude`.
Parameters
==========
prefix : str, optional
The prefix to use. By default, this function will generate symbols of
the form "x0", "x1", etc.
cls : class, optional
The class to use. By default, it uses Symbol, but you can also use Wild or Dummy.
start : int, optional
The start number. By default, it is 0.
Returns
=======
sym : Symbol
The subscripted symbols.
"""
exclude = set(exclude or [])
if cls is None:
# We can't just make the default cls=Symbol because it isn't
# imported yet.
from ..core import Symbol
cls = Symbol
while True:
name = f'{prefix}{start}'
s = cls(name, *args, **assumptions)
if s not in exclude:
yield s
start += 1
def capture(func):
r"""Return the printed output of func().
`func` should be a function without arguments that produces output with
print statements.
>>> def foo():
... print('hello world!')
...
>>> 'hello' in capture(foo) # foo, not foo()
True
>>> capture(lambda: pprint(2/x, use_unicode=False))
'2\n-\nx\n'
"""
import sys
from io import StringIO
stdout = sys.stdout
sys.stdout = file = StringIO()
try:
func()
finally:
sys.stdout = stdout
return file.getvalue()
def sift(seq, keyfunc):
"""
Sift the sequence, ``seq`` into a dictionary according to keyfunc.
OUTPUT: each element in expr is stored in a list keyed to the value
of keyfunc for the element.
Examples
========
>>> from collections import defaultdict
>>> sift(range(5), lambda x: x % 2) == defaultdict(int, {0: [0, 2, 4], 1: [1, 3]})
True
sift() returns a defaultdict() object, so any key that has no matches will
give [].
>>> dl = sift([x], lambda x: x.is_commutative)
>>> dl == defaultdict(list, {True: [x]})
True
>>> dl[False]
[]
Sometimes you won't know how many keys you will get:
>>> (sift([sqrt(x), exp(x), (y**x)**2],
... lambda x: x.as_base_exp()[0]) ==
... defaultdict(list, {E: [exp(x)], x: [sqrt(x)], y: [y**(2*x)]}))
True
If you need to sort the sifted items it might be better to use
``ordered`` which can economically apply multiple sort keys
to a squence while sorting.
See Also
========
ordered
"""
m = defaultdict(list)
for i in seq:
m[keyfunc(i)].append(i)
return m
def common_prefix(*seqs):
"""Return the subsequence that is a common start of sequences in ``seqs``.
>>> common_prefix(list(range(3)))
[0, 1, 2]
>>> common_prefix(list(range(3)), list(range(4)))
[0, 1, 2]
>>> common_prefix([1, 2, 3], [1, 2, 5])
[1, 2]
>>> common_prefix([1, 2, 3], [1, 3, 5])
[1]
"""
if any(not s for s in seqs):
return []
elif len(seqs) == 1:
return seqs[0]
i = 0
for i in range(min(len(s) for s in seqs)):
if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))):
break
else:
i += 1
return seqs[0][:i]
def common_suffix(*seqs):
"""Return the subsequence that is a common ending of sequences in ``seqs``.
>>> common_suffix(list(range(3)))
[0, 1, 2]
>>> common_suffix(list(range(3)), list(range(4)))
[]
>>> common_suffix([1, 2, 3], [9, 2, 3])
[2, 3]
>>> common_suffix([1, 2, 3], [9, 7, 3])
[3]
"""
if any(not s for s in seqs):
return []
elif len(seqs) == 1:
return seqs[0]
i = 0
for i in range(-1, -min(len(s) for s in seqs) - 1, -1):
if not all(seqs[j][i] == seqs[0][i] for j in range(len(seqs))):
break
else:
i -= 1
if i == -1:
return []
else:
return seqs[0][i + 1:]
def prefixes(seq):
"""
Generate all prefixes of a sequence.
Examples
========
>>> list(prefixes([1, 2, 3, 4]))
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
"""
n = len(seq)
for i in range(n):
yield seq[:i + 1]
def postfixes(seq):
"""
Generate all postfixes of a sequence.
Examples
========
>>> list(postfixes([1, 2, 3, 4]))
[[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]]
"""
n = len(seq)
for i in range(n):
yield seq[n - i - 1:]
def topological_sort(graph, key=None):
r"""
Topological sort of graph's vertices.
Parameters
==========
``graph`` : ``tuple[list, list[tuple[T, T]]``
A tuple consisting of a list of vertices and a list of edges of
a graph to be sorted topologically.
``key`` : ``callable[T]`` (optional)
Ordering key for vertices on the same level. By default the natural
(e.g. lexicographic) ordering is used (in this case the base type
must implement ordering relations).
Examples
========
Consider a graph::
+---+ +---+ +---+
| 7 |\ | 5 | | 3 |
+---+ \ +---+ +---+
| _\___/ ____ _/ |
| / \___/ \ / |
V V V V |
+----+ +---+ |
| 11 | | 8 | |
+----+ +---+ |
| | \____ ___/ _ |
| \ \ / / \ |
V \ V V / V V
+---+ \ +---+ | +----+
| 2 | | | 9 | | | 10 |
+---+ | +---+ | +----+
\________/
where vertices are integers. This graph can be encoded using
elementary Python's data structures as follows::
>>> V = [2, 3, 5, 7, 8, 9, 10, 11]
>>> E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10),
... (11, 2), (11, 9), (11, 10), (8, 9)]
To compute a topological sort for graph ``(V, E)`` issue::
>>> topological_sort((V, E))
[3, 5, 7, 8, 11, 2, 9, 10]
If specific tie breaking approach is needed, use ``key`` parameter::
>>> topological_sort((V, E), key=lambda v: -v)
[7, 5, 11, 3, 10, 8, 9, 2]
Only acyclic graphs can be sorted. If the input graph has a cycle,
then ValueError will be raised::
>>> topological_sort((V, E + [(10, 7)]))
Traceback (most recent call last):
...
ValueError: cycle detected
References
==========
* https://en.wikipedia.org/wiki/Topological_sorting
"""
V, E = graph
L = []
S = set(V)
E = list(E)
for v, u in E:
S.discard(u)
if key is None:
def key(value):
return value
S = sorted(S, key=key, reverse=True)
while S:
node = S.pop()
L.append(node)
for u, v in list(E):
if u == node:
E.remove((u, v))
for _u, _v in E:
if v == _v:
break
else:
kv = key(v)
for i, s in enumerate(S):
ks = key(s)
if kv > ks:
S.insert(i, v)
break
else:
S.append(v)
if E:
raise ValueError('cycle detected')
return L
def rotate_left(x, y):
"""
Left rotates a list x by the number of steps specified
in y.
Examples
========
>>> a = [0, 1, 2]
>>> rotate_left(a, 1)
[1, 2, 0]
"""
if len(x) == 0:
return []
y = y % len(x)
return x[y:] + x[:y]
def rotate_right(x, y):
"""
Right rotates a list x by the number of steps specified
in y.
Examples
========
>>> a = [0, 1, 2]
>>> rotate_right(a, 1)
[2, 0, 1]
"""
if len(x) == 0:
return []
y = len(x) - y % len(x)
return x[y:] + x[:y]
def multiset_combinations(m, n, g=None):
"""
Return the unique combinations of size ``n`` from multiset ``m``.
Examples
========
>>> from itertools import combinations
>>> [''.join(i) for i in multiset_combinations('baby', 3)]
['abb', 'aby', 'bby']
>>> def count(f, s):
... return len(list(f(s, 3)))
The number of combinations depends on the number of letters; the
number of unique combinations depends on how the letters are
repeated.
>>> s1 = 'abracadabra'
>>> s2 = 'banana tree'
>>> count(combinations, s1), count(multiset_combinations, s1)
(165, 23)
>>> count(combinations, s2), count(multiset_combinations, s2)
(165, 54)
"""
if g is None:
if type(m) is dict:
if n > sum(m.values()):
return
g = [[k, m[k]] for k in ordered(m)]
else:
m = list(m)
if n > len(m):
return
try:
m = multiset(m)
g = [(k, m[k]) for k in ordered(m)]
except TypeError:
m = list(ordered(m))
g = [list(i) for i in group(m, multiple=False)]
del m
if sum(v for k, v in g) < n or not n:
yield []
else:
for i, (k, v) in enumerate(g):
if v >= n:
yield [k]*n
v = n - 1
for v in range(min(n, v), 0, -1):
for j in multiset_combinations(None, n - v, g[i + 1:]):
rv = [k]*v + j
if len(rv) == n:
yield rv
def multiset_permutations(m, size=None, g=None):
"""
Return the unique permutations of multiset ``m``.
Examples
========
>>> [''.join(i) for i in multiset_permutations('aab')]
['aab', 'aba', 'baa']
>>> factorial(len('banana'))
720
>>> len(list(multiset_permutations('banana')))
60
"""
if g is None:
if type(m) is dict:
g = [[k, m[k]] for k in ordered(m)]
else:
m = list(ordered(m))
g = [list(i) for i in group(m, multiple=False)]
del m
do = [gi for gi in g if gi[1] > 0]
SUM = sum(gi[1] for gi in do)
if not do or size is not None and (size > SUM or size < 1):
if size < 1:
yield []
elif size == 1:
for k, v in do:
yield [k]
elif len(do) == 1:
k, v = do[0]
v = v if size is None else (size if size <= v else 0)
yield [k for i in range(v)]
elif all(v == 1 for k, v in do):
for p in permutations([k for k, v in do], size):
yield list(p)
else:
size = size if size is not None else SUM
for i, (k, v) in enumerate(do):
do[i][1] -= 1
for j in multiset_permutations(None, size - 1, do):
yield [k] + j
do[i][1] += 1
def _partition(seq, vector, m=None):
"""
Return the partion of seq as specified by the partition vector.
Examples
========
>>> _partition('abcde', [1, 0, 1, 2, 0])
[['b', 'e'], ['a', 'c'], ['d']]
Specifying the number of bins in the partition is optional:
>>> _partition('abcde', [1, 0, 1, 2, 0], 3)
[['b', 'e'], ['a', 'c'], ['d']]
The output of _set_partitions can be passed as follows:
>>> output = (3, [1, 0, 1, 2, 0])
>>> _partition('abcde', *output)
[['b', 'e'], ['a', 'c'], ['d']]
See Also
========
combinatorics.partitions.Partition.from_rgs()
"""
if m is None:
m = max(vector) + 1
elif type(vector) is int: # entered as m, vector
vector, m = m, vector
p = [[] for i in range(m)]
for i, v in enumerate(vector):
p[v].append(seq[i])
return p
def _set_partitions(n):
"""Cycle through all partitions of n elements, yielding the
current number of partitions, ``m``, and a mutable list, ``q``
such that element[i] is in part q[i] of the partition.
NOTE: ``q`` is modified in place and generally should not be changed
between function calls.
Examples
========
>>> for m, q in _set_partitions(3):
... print(f'{m} {q} { _partition("abc", q, m)}')
1 [0, 0, 0] [['a', 'b', 'c']]
2 [0, 0, 1] [['a', 'b'], ['c']]
2 [0, 1, 0] [['a', 'c'], ['b']]
2 [0, 1, 1] [['a'], ['b', 'c']]
3 [0, 1, 2] [['a'], ['b'], ['c']]
Notes
=====
This algorithm is similar to, and solves the same problem as,
Algorithm 7.2.1.5H, from volume 4A of Knuth's The Art of Computer
Programming. Knuth uses the term "restricted growth string" where
this code refers to a "partition vector". In each case, the meaning is
the same: the value in the ith element of the vector specifies to
which part the ith set element is to be assigned.
At the lowest level, this code implements an n-digit big-endian
counter (stored in the array q) which is incremented (with carries) to
get the next partition in the sequence. A special twist is that a
digit is constrained to be at most one greater than the maximum of all
the digits to the left of it. The array p maintains this maximum, so
that the code can efficiently decide when a digit can be incremented
in place or whether it needs to be reset to 0 and trigger a carry to
the next digit. The enumeration starts with all the digits 0 (which
corresponds to all the set elements being assigned to the same 0th
part), and ends with 0123...n, which corresponds to each set element
being assigned to a different, singleton, part.
This routine was rewritten to use 0-based lists while trying to
preserve the beauty and efficiency of the original algorithm.
References
==========
* Nijenhuis, Albert and Wilf, Herbert. (1978) Combinatorial Algorithms,
2nd Ed, p 91, algorithm "nexequ". Available online from
http://www.math.upenn.edu/~wilf/website/CombAlgDownld.html (viewed
November 17, 2012).
"""
p = [0]*n
q = [0]*n
nc = 1
yield nc, q
while nc != n:
m = n
while 1:
m -= 1
i = q[m]
if p[i] != 1:
break
q[m] = 0
i += 1
q[m] = i
m += 1
nc += m - n
p[0] += n - m
if i == nc:
p[nc] = 0
nc += 1
p[i - 1] -= 1
p[i] += 1
yield nc, q
def multiset_partitions(multiset, m=None):
"""
Return unique partitions of the given multiset (in list form).
If ``m`` is None, all multisets will be returned, otherwise only
partitions with ``m`` parts will be returned.
If ``multiset`` is an integer, a range [0, 1, ..., multiset - 1]
will be supplied.
*Counting*
The number of partitions of a set is given by the bell number:
>>> len(list(multiset_partitions(5))) == bell(5) == 52
True
The number of partitions of length k from a set of size n is given by the
Stirling Number of the 2nd kind:
>>> def s2(n, k):
... from diofant import Dummy, Sum, binomial, factorial
... if k > n:
... return 0
... j = Dummy()
... arg = (-1)**(k-j)*j**n*binomial(k, j)
... return 1/factorial(k)*Sum(arg, (j, 0, k)).doit()
...
>>> s2(5, 2) == len(list(multiset_partitions(5, 2))) == 15
True
These comments on counting apply to *sets*, not multisets.
Examples
========
>>> list(multiset_partitions([1, 2, 3, 4], 2))
[[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 2], [3, 4]],
[[1, 3, 4], [2]], [[1, 3], [2, 4]], [[1, 4], [2, 3]],
[[1], [2, 3, 4]]]
>>> list(multiset_partitions([1, 2, 3, 4], 1))
[[[1, 2, 3, 4]]]
Only unique partitions are returned and these will be returned in a
canonical order regardless of the order of the input:
>>> a = [1, 2, 2, 1]
>>> ans = list(multiset_partitions(a, 2))
>>> a.sort()
>>> list(multiset_partitions(a, 2)) == ans
True
>>> a = range(3, 1, -1)
>>> (list(multiset_partitions(a)) ==
... list(multiset_partitions(sorted(a))))
True
If m is omitted then all partitions will be returned:
>>> list(multiset_partitions([1, 1, 2]))
[[[1, 1, 2]], [[1, 1], [2]], [[1, 2], [1]], [[1], [1], [2]]]
>>> list(multiset_partitions([1]*3))
[[[1, 1, 1]], [[1], [1, 1]], [[1], [1], [1]]]
Notes
=====
When all the elements are the same in the multiset, the order
of the returned partitions is determined by the ``partitions``
routine. If one is counting partitions then it is better to use
the ``nT`` function.
See Also
========
partitions
diofant.combinatorics.partitions.Partition
diofant.combinatorics.partitions.IntegerPartition
diofant.functions.combinatorial.numbers.nT
"""
# This function looks at the supplied input and dispatches to
# several special-case routines as they apply.
if type(multiset) is int:
n = multiset
if m and m > n:
return
multiset = list(range(n))
if m == 1:
yield [multiset[:]]
return
# If m is not None, it can sometimes be faster to use
# MultisetPartitionTraverser.enum_range() even for inputs
# which are sets. Since the _set_partitions code is quite
# fast, this is only advantageous when the overall set
# partitions outnumber those with the desired number of parts
# by a large factor. (At least 60.) Such a switch is not
# currently implemented.
for nc, q in _set_partitions(n):
if m is None or nc == m:
rv = [[] for i in range(nc)]
for i in range(n):
rv[q[i]].append(multiset[i])
yield rv
return
if len(multiset) == 1 and type(multiset) is str:
multiset = [multiset]
if not has_variety(multiset):
# Only one component, repeated n times. The resulting
# partitions correspond to partitions of integer n.
n = len(multiset)
if m and m > n:
return
if m == 1:
yield [multiset[:]]
return
x = multiset[:1]
for size, p in partitions(n, m, size=True):
if m is None or size == m:
rv = []
for k in sorted(p):
rv.extend([x*k]*p[k])
yield rv
else:
multiset = list(ordered(multiset))
n = len(multiset)
if m and m > n:
return
if m == 1:
yield [multiset[:]]
return
# Split the information of the multiset into two lists -
# one of the elements themselves, and one (of the same length)
# giving the number of repeats for the corresponding element.
elements, multiplicities = zip(*group(multiset, False))
if len(elements) < len(multiset):
# General case - multiset with more than one distinct element
# and at least one element repeated more than once.
if m:
mpt = MultisetPartitionTraverser()
for state in mpt.enum_range(multiplicities, m-1, m):
yield list_visitor(state, elements)
else:
for state in multiset_partitions_taocp(multiplicities):
yield list_visitor(state, elements)
else:
# Set partitions case - no repeated elements. Pretty much
# same as int argument case above, with same possible, but
# currently unimplemented optimization for some cases when
# m is not None
for nc, q in _set_partitions(n):
if m is None or nc == m:
rv = [[] for i in range(nc)]
for i in range(n):
rv[q[i]].append(i)
yield [[multiset[j] for j in i] for i in rv]
def partitions(n, m=None, k=None, size=False):
"""Generate all partitions of positive integer, n.
Parameters
==========
``m`` : integer (default gives partitions of all sizes)
limits number of parts in partition (mnemonic: m, maximum parts).
Default value, None, gives partitions from 1 through n.
``k`` : integer (default gives partitions number from 1 through n)
limits the numbers that are kept in the partition (mnemonic: k, keys)
``size`` : bool (default False, only partition is returned)
when ``True`` then (M, P) is returned where M is the sum of the
multiplicities and P is the generated partition.
Each partition is represented as a dictionary, mapping an integer
to the number of copies of that integer in the partition. For example,
the first partition of 4 returned is {4: 1}, "4: one of them".
Examples
========
The numbers appearing in the partition (the key of the returned dict)
are limited with k:
>>> from diofant.utilities.iterables import partitions
>>> for p in partitions(6, k=2):
... print(p)
{2: 3}
{2: 2, 1: 2}
{2: 1, 1: 4}
{1: 6}
The maximum number of parts in the partition (the sum of the values in
the returned dict) are limited with m:
>>> for p in partitions(6, m=2):
... print(p)
...
{6: 1}
{5: 1, 1: 1}
{4: 1, 2: 1}
{3: 2}
Note that the _same_ dictionary object is returned each time.
This is for speed: generating each partition goes quickly,
taking constant time, independent of n.
>>> list(partitions(6, k=2))
[{1: 6}, {1: 6}, {1: 6}, {1: 6}]
If you want to build a list of the returned dictionaries then
make a copy of them:
>>> [p.copy() for p in partitions(6, k=2)]
[{2: 3}, {1: 2, 2: 2}, {1: 4, 2: 1}, {1: 6}]
>>> [(M, p.copy()) for M, p in partitions(6, k=2, size=True)]
[(3, {2: 3}), (4, {1: 2, 2: 2}), (5, {1: 4, 2: 1}), (6, {1: 6})]
References
==========
* http://code.activestate.com/recipes/218332-generator-for-integer-partitions/
Notes
=====
Modified from Tim Peter's version to allow for k and m values.
See Also
========
diofant.combinatorics.partitions.Partition
diofant.combinatorics.partitions.IntegerPartition
"""
if (n <= 0 or m is not None and m < 1 or
k is not None and k < 1 or m and k and m*k < n):
# the empty set is the only way to handle these inputs
# and returning {} to represent it is consistent with
# the counting convention, e.g. nT(0) == 1.
if size:
yield 0, {}
else:
yield {}
return
if m is None:
m = n
else:
m = min(m, n)
k = min(k or n, n)
n, m, k = as_int(n), as_int(m), as_int(k)
q, r = divmod(n, k)
ms = {k: q}
keys = [k] # ms keys, from largest to smallest
if r:
ms[r] = 1
keys.append(r)
room = m - q - bool(r)
if size:
yield sum(ms.values()), ms
else:
yield ms
while keys != [1]:
# Reuse any 1's.
if keys[-1] == 1:
del keys[-1]
reuse = ms.pop(1)
room += reuse
else:
reuse = 0
while 1:
# Let i be the smallest key larger than 1. Reuse one
# instance of i.
i = keys[-1]
newcount = ms[i] = ms[i] - 1
reuse += i
if newcount == 0:
del keys[-1], ms[i]
room += 1
# Break the remainder into pieces of size i-1.
i -= 1
q, r = divmod(reuse, i)
need = q + bool(r)
if need > room:
if not keys:
return
continue
ms[i] = q
keys.append(i)
if r:
ms[r] = 1
keys.append(r)
break
room -= need
if size:
yield sum(ms.values()), ms
else:
yield ms
def ordered_partitions(n, m=None, sort=True):
"""Generates ordered partitions of integer ``n``.
Parameters
==========
``m`` : int or None, optional
By default (None) gives partitions of all sizes, else only
those with size m. In addition, if ``m`` is not None then
partitions are generated *in place* (see examples).
``sort`` : bool, optional
Controls whether partitions are
returned in sorted order (default) when ``m`` is not None; when False,
the partitions are returned as fast as possible with elements
sorted, but when m|n the partitions will not be in
ascending lexicographical order.
Examples
========
All partitions of 5 in ascending lexicographical:
>>> for p in ordered_partitions(5):
... print(p)
[1, 1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 3]
[1, 2, 2]
[1, 4]
[2, 3]
[5]
Only partitions of 5 with two parts:
>>> for p in ordered_partitions(5, 2):
... print(p)
[1, 4]
[2, 3]
When ``m`` is given, a given list objects will be used more than
once for speed reasons so you will not see the correct partitions
unless you make a copy of each as it is generated:
>>> list(ordered_partitions(7, 3))
[[1, 1, 1], [1, 1, 1], [1, 1, 1], [2, 2, 2]]
>>> [list(p) for p in ordered_partitions(7, 3)]
[[1, 1, 5], [1, 2, 4], [1, 3, 3], [2, 2, 3]]
When ``n`` is a multiple of ``m``, the elements are still sorted
but the partitions themselves will be *unordered* if sort is False;
the default is to return them in ascending lexicographical order.
>>> for p in ordered_partitions(6, 2):
... print(p)
[1, 5]
[2, 4]
[3, 3]
But if speed is more important than ordering, sort can be set to
False:
>>> for p in ordered_partitions(6, 2, sort=False):
... print(p)
[1, 5]
[3, 3]
[2, 4]
References
==========
* Generating Integer Partitions, [online],
Available: http://jeromekelleher.net/generating-integer-partitions.html
* Jerome Kelleher and Barry O'Sullivan, "Generating All
Partitions: A Comparison Of Two Encodings", [online],
Available: https://arxiv.org/pdf/0909.2331v2.pdf
"""
if n < 1 or m is not None and m < 1:
# the empty set is the only way to handle these inputs
# and returning {} to represent it is consistent with
# the counting convention, e.g. nT(0) == 1.
yield []
return
if m is None:
# The list `a`'s leading elements contain the partition in which
# y is the biggest element and x is either the same as y or the
# 2nd largest element; v and w are adjacent element indices
# to which x and y are being assigned, respectively.
a = [1]*n
y = -1
v = n
while v > 0:
v -= 1
x = a[v] + 1
while y >= 2 * x:
a[v] = x
y -= x
v += 1
w = v + 1
while x <= y:
a[v] = x
a[w] = y
yield a[:w + 1]
x += 1
y -= 1
a[v] = x + y
y = a[v] - 1
yield a[:w]
elif m == 1:
yield [n]
elif n == m:
yield [1]*n
else:
# recursively generate partitions of size m
for b in range(1, n//m + 1):
a = [b]*m
x = n - b*m
if not x:
if sort:
yield a
elif not sort and x <= m:
for ax in ordered_partitions(x, sort=False):
mi = len(ax)
a[-mi:] = [i + b for i in ax]
yield a
a[-mi:] = [b]*mi
else:
for mi in range(1, m):
for ax in ordered_partitions(x, mi, sort=True):
a[-mi:] = [i + b for i in ax]
yield a
a[-mi:] = [b]*mi
def binary_partitions(n):
"""
Generates the binary partition of n.
A binary partition consists only of numbers that are
powers of two. Each step reduces a 2**(k+1) to 2**k and
2**k. Thus 16 is converted to 8 and 8.
References
==========
* TAOCP 4, section 7.2.1.5, problem 64
Examples
========
>>> for i in binary_partitions(5):
... print(i)
...
[4, 1]
[2, 2, 1]
[2, 1, 1, 1]
[1, 1, 1, 1, 1]
"""
from math import ceil, log
pow = 2**ceil(log(n, 2))
sum = 0
partition = []
while pow:
if sum + pow <= n:
partition.append(pow)
sum += pow
pow >>= 1
last_num = len(partition) - 1 - (n & 1)
while last_num >= 0:
yield partition
if partition[last_num] == 2:
partition[last_num] = 1
partition.append(1)
last_num -= 1
continue
partition.append(1)
partition[last_num] >>= 1
x = partition[last_num + 1] = partition[last_num]
last_num += 1
while x > 1:
if x <= len(partition) - last_num - 1:
del partition[-x + 1:]
last_num += 1
partition[last_num] = x
else:
x >>= 1
yield [1]*n
def has_dups(seq):
"""Return True if there are any duplicate elements in ``seq``.
Examples
========
>>> has_dups((1, 2, 1))
True
>>> has_dups(range(3))
False
>>> all(has_dups(c) is False for c in (set(), Set(), {}, Dict()))
True
"""
from ..core import Dict
from ..sets import Set
if isinstance(seq, (dict, set, Dict, Set)):
return False
uniq = set()
return any(True for s in seq if s in uniq or uniq.add(s))
def has_variety(seq):
"""Return True if there are any different elements in ``seq``.
Examples
========
>>> has_variety((1, 2, 1))
True
>>> has_variety((1, 1, 1))
False
"""
for i, s in enumerate(seq):
if i == 0:
sentinel = s
else:
if s != sentinel:
return True
return False
def uniq(seq, result=None):
"""
Yield unique elements from ``seq`` as an iterator. The second
parameter ``result`` is used internally; it is not necessary to pass
anything for this.
Examples
========
>>> dat = [1, 4, 1, 5, 4, 2, 1, 2]
>>> type(uniq(dat)) in (list, tuple)
False
>>> list(uniq(dat))
[1, 4, 5, 2]
>>> list(uniq(x for x in dat))
[1, 4, 5, 2]
>>> list(uniq([[1], [2, 1], [1]]))
[[1], [2, 1]]
"""
try:
seen = set()
result = result or []
for i, s in enumerate(seq):
if not (s in seen or seen.add(s)):
yield s
except TypeError:
if s not in result:
yield s
result.append(s)
if hasattr(seq, '__getitem__'):
for s in uniq(seq[i + 1:], result): # pylint: disable=used-before-assignment
yield s
else:
for s in uniq(seq, result):
yield s
def generate_involutions(n):
"""
Generates involutions.
An involution is a permutation that when multiplied
by itself equals the identity permutation. In this
implementation the involutions are generated using
Fixed Points.
Alternatively, an involution can be considered as
a permutation that does not contain any cycles with
a length that is greater than two.
References
==========
* https://mathworld.wolfram.com/PermutationInvolution.html
Examples
========
>>> list(generate_involutions(3))
[(0, 1, 2), (0, 2, 1), (1, 0, 2), (2, 1, 0)]
>>> len(list(generate_involutions(4)))
10
"""
idx = list(range(n))
for p in permutations(idx):
for i in idx:
if p[p[i]] != i:
break
else:
yield p
def generate_derangements(perm):
"""
Routine to generate unique derangements.
TODO: This will be rewritten to use the
ECO operator approach once the permutations
branch is in master.
Examples
========
>>> list(generate_derangements([0, 1, 2]))
[[1, 2, 0], [2, 0, 1]]
>>> list(generate_derangements([0, 1, 2, 3]))
[[1, 0, 3, 2], [1, 2, 3, 0], [1, 3, 0, 2], [2, 0, 3, 1],
[2, 3, 0, 1], [2, 3, 1, 0], [3, 0, 1, 2], [3, 2, 0, 1],
[3, 2, 1, 0]]
>>> list(generate_derangements([0, 1, 1]))
[]
See Also
========
diofant.functions.combinatorial.factorials.subfactorial
"""
p = multiset_permutations(perm)
indices = range(len(perm))
p0 = next(p) # pylint: disable=stop-iteration-return
for pi in p:
if all(pi[i] != p0[i] for i in indices):
yield pi
def necklaces(n, k, free=False):
"""
A routine to generate necklaces that may (free=True) or may not
(free=False) be turned over to be viewed. The "necklaces" returned
are comprised of ``n`` integers (beads) with ``k`` different
values (colors). Only unique necklaces are returned.
Examples
========
>>> def show(s, i):
... return ''.join(s[j] for j in i)
The "unrestricted necklace" is sometimes also referred to as a
"bracelet" (an object that can be turned over, a sequence that can
be reversed) and the term "necklace" is used to imply a sequence
that cannot be reversed. So ACB == ABC for a bracelet (rotate and
reverse) while the two are different for a necklace since rotation
alone cannot make the two sequences the same.
(mnemonic: Bracelets can be viewed Backwards, but Not Necklaces.)
>>> B = [show('ABC', i) for i in bracelets(3, 3)]
>>> N = [show('ABC', i) for i in necklaces(3, 3)]
>>> set(N) - set(B)
{'ACB'}
>>> list(necklaces(4, 2))
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 1),
(0, 1, 0, 1), (0, 1, 1, 1), (1, 1, 1, 1)]
>>> [show('.o', i) for i in bracelets(4, 2)]
['....', '...o', '..oo', '.o.o', '.ooo', 'oooo']
References
==========
https://mathworld.wolfram.com/Necklace.html
"""
return uniq(minlex(i, directed=not free) for i in
variations(list(range(k)), n, repetition=True))
def bracelets(n, k):
"""Wrapper to necklaces to return a free (unrestricted) necklace."""
return necklaces(n, k, free=True)
def minlex(seq, directed=True, is_set=False, small=None):
"""
Return a tuple where the smallest element appears first; if
``directed`` is True (default) then the order is preserved, otherwise
the sequence will be reversed if that gives a smaller ordering.
If every element appears only once then is_set can be set to True
for more efficient processing.
If the smallest element is known at the time of calling, it can be
passed and the calculation of the smallest element will be omitted.
Examples
========
>>> minlex((1, 2, 0))
(0, 1, 2)
>>> minlex((1, 0, 2))
(0, 2, 1)
>>> minlex((1, 0, 2), directed=False)
(0, 1, 2)
>>> minlex('11010011000', directed=True)
'00011010011'
>>> minlex('11010011000', directed=False)
'00011001011'
"""
is_str = isinstance(seq, str)
seq = list(seq)
if small is None:
small = min(seq, key=default_sort_key)
if is_set:
i = seq.index(small)
if not directed:
n = len(seq)
p = (i + 1) % n
m = (i - 1) % n
if default_sort_key(seq[p]) > default_sort_key(seq[m]):
seq = list(reversed(seq))
i = n - i - 1
if i:
seq = rotate_left(seq, i)
best = seq
else:
count = seq.count(small)
if count == 1 and directed:
best = rotate_left(seq, seq.index(small))
else:
# if not directed, and not a set, we can't just
# pass this off to minlex with is_set True since
# peeking at the neighbor may not be sufficient to
# make the decision so we continue...
best = seq
for i in range(count):
seq = rotate_left(seq, seq.index(small, count != 1))
if seq < best:
best = seq
# it's cheaper to rotate now rather than search
# again for these in reversed order so we test
# the reverse now
if not directed:
seq = rotate_left(seq, 1)
seq = list(reversed(seq))
if seq < best:
best = seq
seq = list(reversed(seq))
seq = rotate_right(seq, 1)
# common return
if is_str:
return ''.join(best)
return tuple(best)
def runs(seq, op=operator.gt):
"""Group the sequence into lists in which successive elements
all compare the same with the comparison operator, ``op``:
op(seq[i + 1], seq[i]) is True from all elements in a run.
Examples
========
>>> import operator
>>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2])
[[0, 1, 2], [2], [1, 4], [3], [2], [2]]
>>> runs([0, 1, 2, 2, 1, 4, 3, 2, 2], op=operator.ge)
[[0, 1, 2, 2], [1, 4], [3], [2, 2]]
"""
cycles = []
seq = iter(seq)
try:
run = [next(seq)]
except StopIteration:
return []
while True:
try:
ei = next(seq)
except StopIteration:
break
if op(ei, run[-1]):
run.append(ei)
continue
cycles.append(run)
run = [ei]
cycles.append(run)
return cycles
def cantor_product(*args):
"""Breadth-first (diagonal) cartesian product of iterables.
Each iterable is advanced in turn in a round-robin fashion. As usual with
breadth-first, this comes at the cost of memory consumption.
>>> from itertools import count, islice
>>> list(islice(cantor_product(count(), count()), 9))
[(0, 0), (0, 1), (1, 0), (1, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]
"""
args = list(map(iter, args))
try:
argslist = [[next(a)] for a in args]
except StopIteration:
return
else:
yield tuple(a[0] for a in argslist)
nargs = len(args)
exhausted = [False]*nargs
n = nargs
while not all(exhausted):
n = (n - 1) % nargs
if not exhausted[n]:
try:
argslist[n].append(next(args[n]))
except StopIteration:
exhausted[n] = True
else:
for result in product(*(argslist[:n] + [argslist[n][-1:]] +
argslist[n + 1:])):
yield result
def permute_signs(t):
"""Return iterator in which the signs of non-zero elements
of t are permuted.
Examples
========
>>> list(permute_signs((0, 1, 2)))
[(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2)]
"""
for signs in product(*[(1, -1)]*(len(t) - t.count(0))):
signs = list(signs)
yield type(t)([i*signs.pop() if i else i for i in t])
def signed_permutations(t):
"""Return iterator in which the signs of non-zero elements
of t and the order of the elements are permuted.
Examples
========
>>> list(signed_permutations((0, 1, 2)))
[(0, 1, 2), (0, -1, 2), (0, 1, -2), (0, -1, -2), (0, 2, 1),
(0, -2, 1), (0, 2, -1), (0, -2, -1), (1, 0, 2), (-1, 0, 2),
(1, 0, -2), (-1, 0, -2), (1, 2, 0), (-1, 2, 0), (1, -2, 0),
(-1, -2, 0), (2, 0, 1), (-2, 0, 1), (2, 0, -1), (-2, 0, -1),
(2, 1, 0), (-2, 1, 0), (2, -1, 0), (-2, -1, 0)]
"""
return (type(t)(i) for j in permutations(t)
for i in permute_signs(j))
def _nodes(e):
"""
A helper for ordered() which returns the node count of ``e`` which
for Basic objects is the number of Basic nodes in the expression tree
but for other objects is 1 (unless the object is an iterable or dict
for which the sum of nodes is returned).
"""
from ..core import Basic
if isinstance(e, Basic):
return e.count(Basic)
elif iterable(e):
return 1 + sum(_nodes(ei) for ei in e)
elif isinstance(e, dict):
return 1 + sum(_nodes(k) + _nodes(v) for k, v in e.items())
else:
return 1
def ordered(seq, keys=None, default=True, warn=False):
"""Return an iterator of the seq where keys are used to break ties in
a conservative fashion: if, after applying a key, there are no ties
then no other keys will be computed.
Two default keys will be applied if 1) keys are not provided or 2) the
given keys don't resolve all ties (but only if `default` is True). The
two keys are `_nodes` (which places smaller expressions before large) and
`default_sort_key` which (if the `sort_key` for an object is defined
properly) should resolve any ties.
If ``warn`` is True then an error will be raised if there were no
keys remaining to break ties. This can be used if it was expected that
there should be no ties between items that are not identical.
Examples
========
The count_ops is not sufficient to break ties in this list and the first
two items appear in their original order (i.e. the sorting is stable):
>>> list(ordered([y + 2, x + 2, x**2 + y + 3],
... count_ops, default=False, warn=False))
[y + 2, x + 2, x**2 + y + 3]
The default_sort_key allows the tie to be broken:
>>> list(ordered([y + 2, x + 2, x**2 + y + 3]))
[x + 2, y + 2, x**2 + y + 3]
Here, sequences are sorted by length, then sum:
>>> seq, keys = [[[1, 2, 1], [0, 3, 1], [1, 1, 3], [2], [1]],
... [lambda x: len(x), lambda x: sum(x)]]
>>> list(ordered(seq, keys, default=False, warn=False))
[[1], [2], [1, 2, 1], [0, 3, 1], [1, 1, 3]]
If ``warn`` is True, an error will be raised if there were not
enough keys to break ties:
>>> list(ordered(seq, keys, default=False, warn=True))
Traceback (most recent call last):
...
ValueError: not enough keys to break ties
Notes
=====
The decorated sort is one of the fastest ways to sort a sequence for
which special item comparison is desired: the sequence is decorated,
sorted on the basis of the decoration (e.g. making all letters lower
case) and then undecorated. If one wants to break ties for items that
have the same decorated value, a second key can be used. But if the
second key is expensive to compute then it is inefficient to decorate
all items with both keys: only those items having identical first key
values need to be decorated. This function applies keys successively
only when needed to break ties. By yielding an iterator, use of the
tie-breaker is delayed as long as possible.
This function is best used in cases when use of the first key is
expected to be a good hashing function; if there are no unique hashes
from application of a key then that key should not have been used. The
exception, however, is that even if there are many collisions, if the
first group is small and one does not need to process all items in the
list then time will not be wasted sorting what one was not interested
in. For example, if one were looking for the minimum in a list and
there were several criteria used to define the sort order, then this
function would be good at returning that quickly if the first group
of candidates is small relative to the number of items being processed.
"""
d = defaultdict(list)
if keys:
if not isinstance(keys, (list, tuple)):
keys = [keys]
keys = list(keys)
f = keys.pop(0)
for a in seq:
d[f(a)].append(a)
else:
if not default:
raise ValueError('if default=False then keys must be provided')
d[None].extend(seq)
for k in sorted(d):
if len(d[k]) > 1:
if keys:
d[k] = ordered(d[k], keys, default, warn)
elif default:
d[k] = ordered(d[k], (_nodes, default_sort_key,),
default=False, warn=warn)
elif warn:
u = list(uniq(d[k]))
if len(u) > 1:
raise ValueError(f'not enough keys to break ties: {u}')
for v in d[k]:
yield v
d.pop(k)
def default_sort_key(item, order=None):
"""
Return a key that can be used for sorting.
The key has the structure:
(class_key, (len(args), args), exponent.sort_key(), coefficient)
This key is supplied by the sort_key routine of Basic objects when
``item`` is a Basic object or an object (other than a string) that
sympifies to a Basic object. Otherwise, this function produces the
key.
The ``order`` argument is passed along to the sort_key routine and is
used to determine how the terms *within* an expression are ordered.
(See examples below) ``order`` options are: 'lex', 'grlex', 'grevlex',
and reversed values of the same (e.g. 'rev-lex'). The default order
value is None (which translates to 'lex').
Examples
========
>>> from diofant.core.function import UndefinedFunction
The following are equivalent ways of getting the key for an object:
>>> x.sort_key() == default_sort_key(x)
True
Here are some examples of the key that is produced:
>>> default_sort_key(UndefinedFunction('f'))
((0, 0, 'UndefinedFunction'), (1, ('f',)), ((1, 0, 'Number'),
(0, ()), (), 1), 1)
>>> default_sort_key('1')
((0, 0, 'str'), (1, ('1',)), ((1, 0, 'Number'), (0, ()), (), 1), 1)
>>> default_sort_key(Integer(1))
((1, 0, 'Number'), (0, ()), (), 1)
>>> default_sort_key(2)
((1, 0, 'Number'), (0, ()), (), 2)
While sort_key is a method only defined for Diofant objects,
default_sort_key will accept anything as an argument so it is
more robust as a sorting key. For the following, using key=
lambda i: i.sort_key() would fail because 2 doesn't have a sort_key
method; that's why default_sort_key is used. Note, that it also
handles sympification of non-string items likes ints:
>>> a = [2, I, -I]
>>> sorted(a, key=default_sort_key)
[2, -I, I]
The returned key can be used anywhere that a key can be specified for
a function, e.g. sort, min, max, etc...:
>>> a.sort(key=default_sort_key)
>>> a[0]
2
>>> min(a, key=default_sort_key)
2
Notes
=====
The key returned is useful for getting items into a canonical order
that will be the same across platforms. It is not directly useful for
sorting lists of expressions:
>>> a, b = x, 1/x
Since ``a`` has only 1 term, its value of sort_key is unaffected by
``order``:
>>> a.sort_key() == a.sort_key('rev-lex')
True
If ``a`` and ``b`` are combined then the key will differ because there
are terms that can be ordered:
>>> eq = a + b
>>> eq.sort_key() == eq.sort_key('rev-lex')
False
>>> eq.as_ordered_terms()
[x, 1/x]
>>> eq.as_ordered_terms('rev-lex')
[1/x, x]
But since the keys for each of these terms are independent of ``order``'s
value, they don't sort differently when they appear separately in a list:
>>> sorted(eq.args, key=default_sort_key)
[1/x, x]
>>> sorted(eq.args, key=lambda i: default_sort_key(i, order='rev-lex'))
[1/x, x]
The order of terms obtained when using these keys is the order that would
be obtained if those terms were *factors* in a product.
Although it is useful for quickly putting expressions in canonical order,
it does not sort expressions based on their complexity defined by the
number of operations, power of variables and others:
>>> sorted([sin(x)*cos(x), sin(x)], key=default_sort_key)
[sin(x)*cos(x), sin(x)]
>>> sorted([x, x**2, sqrt(x), x**3], key=default_sort_key)
[sqrt(x), x, x**2, x**3]
See Also
========
ordered
diofant.core.expr.Expr.as_ordered_factors
diofant.core.expr.Expr.as_ordered_terms
"""
from ..core import Basic, Integer, SympifyError, sympify
if isinstance(item, Basic):
return item.sort_key(order=order)
if iterable(item, exclude=(str,)):
if isinstance(item, dict):
args = item.items()
unordered = True
elif isinstance(item, set):
args = item
unordered = True
else:
# e.g. tuple, list
args = list(item)
unordered = False
args = [default_sort_key(arg, order=order) for arg in args]
if unordered: # e.g. dict, set
args = sorted(args)
cls_index, args = 10, (len(args), tuple(args))
else:
if not isinstance(item, str):
try:
item = sympify(item)
except SympifyError:
# e.g. lambda x: x
pass
else:
if isinstance(item, Basic):
# e.g int -> Integer
return default_sort_key(item)
# e.g. UndefinedFunction
# e.g. str
cls_index, args = 0, (1, (str(item),))
return (cls_index, 0, item.__class__.__name__
), args, Integer(1).sort_key(), Integer(1)
| bsd-3-clause | 3c40f2953bae1e36c3a24cceffa3e994 | 27.324732 | 89 | 0.530741 | 3.593958 | false | false | false | false |
diofant/diofant | diofant/printing/python.py | 1 | 2979 | import keyword as kw
from .repr import ReprPrinter
from .str import StrPrinter
# A list of classes that should be printed using StrPrinter
STRPRINT = ('Add', 'Infinity', 'Integer', 'Mul', 'NegativeInfinity',
'Pow', 'Zero')
class PythonPrinter(ReprPrinter, StrPrinter):
"""A printer which converts an expression into its Python interpretation."""
def __init__(self, settings=None):
ReprPrinter.__init__(self)
StrPrinter.__init__(self, settings)
self.symbols = []
self.functions = []
# Create print methods for classes that should use StrPrinter instead
# of ReprPrinter.
for name in STRPRINT:
f_name = f'_print_{name}'
f = getattr(StrPrinter, f_name)
setattr(PythonPrinter, f_name, f)
def _print_Function(self, expr):
import diofant
func = expr.func.__name__
if not hasattr(diofant, func) and func not in self.functions:
self.functions.append(func)
return StrPrinter._print_Function(self, expr)
# procedure (!) for defining symbols which have be defined in python()
def _print_Symbol(self, expr):
symbol = self._str(expr)
if symbol not in self.symbols:
self.symbols.append(symbol)
return StrPrinter._print_Symbol(self, expr)
_print_BaseSymbol = StrPrinter._print_BaseSymbol
def python(expr, **settings):
"""Return Python interpretation of passed expression
(can be passed to the exec() function without any modifications)
"""
from ..core import Function, Symbol
printer = PythonPrinter(settings)
exprp = printer.doprint(expr)
result = ''
# Returning found symbols and functions
renamings = {}
for symbolname in printer.symbols:
newsymbolname = symbolname
# Escape symbol names that are reserved python keywords
if kw.iskeyword(newsymbolname):
while True:
newsymbolname += '_'
if (newsymbolname not in printer.symbols and
newsymbolname not in printer.functions):
renamings[Symbol(symbolname)] = Symbol(newsymbolname)
break
result += newsymbolname + " = Symbol('" + symbolname + "')\n"
for functionname in printer.functions:
newfunctionname = functionname
# Escape function names that are reserved python keywords
if kw.iskeyword(newfunctionname):
while True:
newfunctionname += '_'
if (newfunctionname not in printer.symbols and
newfunctionname not in printer.functions):
renamings[Function(functionname)] = Function(newfunctionname)
break
result += newfunctionname + " = Function('" + functionname + "')\n"
if len(renamings) != 0:
exprp = expr.subs(renamings)
result += 'e = ' + printer._str(exprp)
return result
| bsd-3-clause | 0141883ca96d5795c1d12a6cd26732dc | 34.891566 | 81 | 0.615307 | 4.433036 | false | false | false | false |
diofant/diofant | diofant/tests/polys/test_specialpolys.py | 1 | 5434 | """Tests for functions for generating interesting polynomials."""
import random
import pytest
from diofant import (ZZ, cyclotomic_poly, interpolating_poly, random_poly,
ring, swinnerton_dyer_poly, symbols, symmetric_poly)
from diofant.abc import x, y, z
__all__ = ()
def test_swinnerton_dyer_poly():
pytest.raises(ValueError, lambda: swinnerton_dyer_poly(0, x))
assert swinnerton_dyer_poly(1, x, polys=True) == (x**2 - 2).as_poly()
assert swinnerton_dyer_poly(1, polys=True) == (x**2 - 2).as_poly()
assert swinnerton_dyer_poly(1, x) == x**2 - 2
assert swinnerton_dyer_poly(2, x) == x**4 - 10*x**2 + 1
assert swinnerton_dyer_poly(3, x) == (x**8 - 40*x**6 +
352*x**4 - 960*x**2 + 576)
assert swinnerton_dyer_poly(4, x) == (x**16 - 136*x**14 + 6476*x**12 -
141912*x**10 + 1513334*x**8 -
7453176*x**6 + 13950764*x**4 -
5596840*x**2 + 46225)
def test_cyclotomic_poly():
pytest.raises(ValueError, lambda: cyclotomic_poly(0, x))
assert cyclotomic_poly(1, x, polys=True) == (x - 1).as_poly()
assert cyclotomic_poly(1, polys=True) == (x - 1).as_poly()
assert cyclotomic_poly(1, x) == x - 1
assert cyclotomic_poly(2, x) == x + 1
assert cyclotomic_poly(3, x) == x**2 + x + 1
assert cyclotomic_poly(4, x) == x**2 + 1
assert cyclotomic_poly(5, x) == x**4 + x**3 + x**2 + x + 1
assert cyclotomic_poly(6, x) == x**2 - x + 1
def test_symmetric_poly():
pytest.raises(ValueError, lambda: symmetric_poly(-1, x, y, z))
pytest.raises(ValueError, lambda: symmetric_poly(5, x, y, z))
assert symmetric_poly(1, x, y, z, polys=True) == (x + y + z).as_poly()
assert symmetric_poly(0, x, y, z) == 1
assert symmetric_poly(1, x, y, z) == x + y + z
assert symmetric_poly(2, x, y, z) == x*y + x*z + y*z
assert symmetric_poly(3, x, y, z) == x*y*z
def test_random_poly():
poly = random_poly(x, 10, -100, 100)
assert poly.as_poly().degree() == 10
assert all(-100 <= coeff <= 100 for coeff in poly.as_poly().coeffs()) is True
poly = random_poly(x, 10, -100, 100, polys=True)
assert poly.degree() == 10
assert all(-100 <= coeff <= 100 for coeff in poly.coeffs()) is True
poly = random_poly(x, 0, -10, 10, polys=True)
assert poly.degree() == 0
assert all(-10 <= c <= 10 for c in poly.all_coeffs())
poly = random_poly(x, 1, -20, 20, polys=True)
assert poly.degree() == 1
assert all(-20 <= c <= 20 for c in poly.all_coeffs())
poly = random_poly(x, 2, -30, 30, polys=True)
assert poly.degree() == 2
assert all(-30 <= c <= 30 for c in poly.all_coeffs())
poly = random_poly(x, 3, -40, 40, polys=True)
assert poly.degree() == 3
assert all(-40 <= c <= 40 for c in poly.all_coeffs())
poly = random_poly(x, 3, -400, 400, polys=True)
assert poly.degree() == 3
assert all(-400 <= c <= 400 for c in poly.all_coeffs())
random.seed(11)
assert random_poly(x, 10, -1, 1, polys=True).all_coeffs() == [1, 0, 1, 1,
-1, 0, 0, -1,
0, 0, 1]
for _ in range(10):
poly = random_poly(x, 3, -10, 10, percent=50, polys=True)
assert poly.all_coeffs()[-1]
assert len([c for c in poly.all_coeffs() if c == 0]) == 2
def test_interpolating_poly():
x0, x1, x2, y0, y1, y2 = symbols('x:3, y:3')
assert interpolating_poly(0, x) == 0
assert interpolating_poly(1, x) == y0
assert interpolating_poly(2, x) == \
y0*(x - x1)/(x0 - x1) + y1*(x - x0)/(x1 - x0)
assert interpolating_poly(3, x) == \
y0*(x - x1)*(x - x2)/((x0 - x1)*(x0 - x2)) + \
y1*(x - x0)*(x - x2)/((x1 - x0)*(x1 - x2)) + \
y2*(x - x0)*(x - x1)/((x2 - x0)*(x2 - x1))
def test_fateman_poly_F_1():
R, x, y = ring('x y', ZZ)
f, g, h = R.fateman_poly_F_1()
assert f == (1 + sum(R.gens))*(2 + sum(R.gens))
assert g == (1 + sum(_**2 for _ in R.gens))*(-3*y*x**2 + y**2 - 1)
assert h == 1
R, x, y, *_ = ring('x y z t', ZZ)
f, g, h = R.fateman_poly_F_1()
assert f == (1 + sum(R.gens))*(2 + sum(R.gens))
assert g == (1 + sum(_**2 for _ in R.gens))*(-3*y*x**2 + y**2 - 1)
def test_fateman_poly_F_2():
R, x, _ = ring('x y', ZZ)
f, g, h = R.fateman_poly_F_2()
D = (1 + sum(R.gens))**2
assert f == D*(-2 + x - sum(R.gens[1:]))**2
assert g == D*(2 + sum(R.gens))**2
assert h == D
R, x, *_ = ring('x y z t', ZZ)
f, g, h = R.fateman_poly_F_2()
D = (1 + sum(R.gens))**2
assert f == D*(-2 + x - sum(R.gens[1:]))**2
assert g == D*(2 + sum(R.gens))**2
assert h == D
def test_fateman_poly_F_3():
R, x, _ = ring('x y', ZZ)
f, g, h = R.fateman_poly_F_3()
D = (1 + sum(_**R.ngens for _ in R.gens))**2
assert f == D*(-2 + x**R.ngens - sum(_**R.ngens for _ in R.gens[1:]))**2
assert g == D*(+2 + sum(_**R.ngens for _ in R.gens))**2
assert h == D
R, x, *_ = ring('x y z t', ZZ)
f, g, h = R.fateman_poly_F_3()
D = (1 + sum(_**R.ngens for _ in R.gens))**2
assert f == D*(-2 + x**R.ngens - sum(_**R.ngens for _ in R.gens[1:]))**2
assert g == D*(+2 + sum(_**R.ngens for _ in R.gens))**2
assert h == D
| bsd-3-clause | bfe887da9479c3a4066d9c97ed7a6bed | 30.410405 | 81 | 0.508281 | 2.64557 | false | true | false | false |
diofant/diofant | diofant/functions/elementary/piecewise.py | 1 | 22234 | from ...core import (Basic, Dummy, Equality, Expr, Function, Integer, Tuple,
diff, nan, oo)
from ...core.relational import Relational
from ...logic import And, Not, Or, false, to_cnf, true
from ...logic.boolalg import Boolean
from ...sets import ExtendedReals
from ...utilities import default_sort_key
from .miscellaneous import Max, Min
class ExprCondPair(Tuple):
"""Represents an expression, condition pair."""
def __new__(cls, expr, cond):
return super().__new__(cls, expr, cond)
@property
def expr(self):
"""Returns the expression of this pair."""
return self.args[0]
@property
def cond(self):
"""Returns the condition of this pair."""
return self.args[1]
@property
def is_commutative(self):
return self.expr.is_commutative
class Piecewise(Function):
"""
Represents a piecewise function.
Usage:
Piecewise( (expr,cond), (expr,cond), ... )
- Each argument is a 2-tuple defining an expression and condition
- The conds are evaluated in turn returning the first that is True.
If any of the evaluated conds are not determined explicitly False,
e.g. x < 1, the function is returned in symbolic form.
- Pairs where the cond is explicitly False, will be removed.
- The last condition is explicitely True. It's value is a default
value for the function (nan if not specified othewise).
Examples
========
>>> f = x**2
>>> g = log(x)
>>> p = Piecewise((0, x < -1), (f, x <= 1), (g, True))
>>> p.subs({x: 1})
1
>>> p.subs({x: 5})
log(5)
See Also
========
diofant.functions.elementary.piecewise.piecewise_fold
"""
nargs = None
is_Piecewise = True
def __new__(cls, *args, **options):
newargs = []
for ec in args:
# ec could be a ExprCondPair or a tuple
pair = ExprCondPair(*getattr(ec, 'args', ec))
cond = pair.cond
if cond == false:
continue
if not isinstance(cond, (bool, Relational, Boolean)):
raise TypeError(
f'Cond {cond} is of type {type(cond)}, but must be a Relational,'
' Boolean, or a built-in bool.')
newargs.append(pair)
if cond == true:
break
if cond != true:
newargs.append(ExprCondPair(nan, true))
if options.pop('evaluate', True):
r = cls.eval(*newargs)
else:
r = None
if r is None:
return Expr.__new__(cls, *newargs, **options)
else:
return r
@classmethod
def eval(cls, *args):
# Check for situations where we can evaluate the Piecewise object.
# 1) Hit an unevaluable cond (e.g. x<1) -> keep object
# 2) Hit a true condition -> return that expr
# 3) Remove false conditions, if no conditions left -> raise ValueError
all_conds_evaled = True # Do all conds eval to a bool?
piecewise_again = False # Should we pass args to Piecewise again?
non_false_ecpairs = []
or1 = Or(*[cond for (_, cond) in args if cond != true])
for expr, cond in args:
# Check here if expr is a Piecewise and collapse if one of
# the conds in expr matches cond. This allows the collapsing
# of Piecewise((Piecewise(x,x<0),x<0)) to Piecewise((x,x<0)).
# This is important when using piecewise_fold to simplify
# multiple Piecewise instances having the same conds.
# Eventually, this code should be able to collapse Piecewise's
# having different intervals, but this will probably require
# using the new assumptions.
if isinstance(expr, Piecewise):
or2 = Or(*[c for (_, c) in expr.args if c != true])
for e, c in expr.args:
# Don't collapse if cond is "True" as this leads to
# incorrect simplifications with nested Piecewises.
if c == cond and (or1 == or2 or cond != true):
expr = e
piecewise_again = True
cond_eval = cls.__eval_cond(cond)
if cond_eval is None:
all_conds_evaled = False
elif cond_eval:
if all_conds_evaled:
return expr
if len(non_false_ecpairs) != 0:
if non_false_ecpairs[-1].cond == cond:
continue
if non_false_ecpairs[-1].expr == expr:
newcond = Or(cond, non_false_ecpairs[-1].cond)
if isinstance(newcond, (And, Or)):
newcond = to_cnf(newcond)
non_false_ecpairs[-1] = ExprCondPair(expr, newcond)
continue
non_false_ecpairs.append(ExprCondPair(expr, cond))
if len(non_false_ecpairs) != len(args) or piecewise_again:
return cls(*non_false_ecpairs)
def doit(self, **hints):
"""Evaluate this piecewise function."""
newargs = []
for e, c in self.args:
if hints.get('deep', True):
e = e.doit(**hints)
c = c.doit(**hints)
newargs.append((e, c))
return self.func(*newargs)
def _eval_as_leading_term(self, x):
for e, c in self.args: # pragma: no branch
if c == true or c.subs({x: 0}) == true:
return e.as_leading_term(x)
def _eval_adjoint(self):
return self.func(*[(e.adjoint(), c) for e, c in self.args])
def _eval_conjugate(self):
return self.func(*[(e.conjugate(), c) for e, c in self.args])
def _eval_derivative(self, s):
return self.func(*[(diff(e, s), c) for e, c in self.args])
def _eval_evalf(self, prec):
return self.func(*[(e.evalf(prec), c) for e, c in self.args])
def _eval_integral(self, x):
from ...integrals import integrate
return self.func(*[(integrate(e, x), c) for e, c in self.args])
def _eval_interval(self, x, a, b):
"""Evaluates the function along the sym in a given interval ab."""
# FIXME: Currently complex intervals are not supported. A possible
# replacement algorithm, discussed in issue sympy/sympy#5227, can be found in the
# following papers;
# http://portal.acm.org/citation.cfm?id=281649
# http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.70.4127&rep=rep1&type=pdf
from .complexes import Abs
if x.is_real is None:
d = Dummy('d', real=True)
return self.subs({x: d})._eval_interval(d, a, b)
if self.has(Abs):
return piecewise_fold(self.rewrite(Abs, Piecewise))._eval_interval(x, a, b)
if a is None or b is None:
# In this case, it is just simple substitution
return piecewise_fold(super()._eval_interval(x, a, b))
mul = 1
if a == b:
return Integer(0)
elif (a > b) == true:
a, b, mul = b, a, -1
elif (a <= b) != true:
newargs = []
for e, c in self.args:
intervals = self._sort_expr_cond(
x, -oo, oo, c)
values = []
for lower, upper, expr in intervals:
if (a < lower) == true:
mid = lower
rep = b
val = e._eval_interval(x, mid, b)
val += self._eval_interval(x, a, mid)
elif (a > upper) == true:
mid = upper
rep = b
val = e._eval_interval(x, mid, b)
val += self._eval_interval(x, a, mid)
elif (a >= lower) == true and (a <= upper) == true:
rep = b
val = e._eval_interval(x, a, b)
elif (b < lower) == true:
mid = lower
rep = a
val = e._eval_interval(x, a, mid)
val += self._eval_interval(x, mid, b)
elif (b > upper) == true:
mid = upper
rep = a
val = e._eval_interval(x, a, mid)
val += self._eval_interval(x, mid, b)
elif ((b >= lower) == true) and ((b <= upper) == true):
rep = a
val = e._eval_interval(x, a, b)
else:
raise NotImplementedError(
"""The evaluation of a Piecewise interval when both the lower
and the upper limit are symbolic is not yet implemented.""")
values.append(val)
if len(set(values)) == 1:
c = c.subs({x: rep})
e = values[0]
newargs.append((e, c))
else:
for i, vi in enumerate(values):
newargs.append((vi, (c == true and i == len(values) - 1) or
And(rep >= intervals[i][0], rep <= intervals[i][1])))
return self.func(*newargs)
# Determine what intervals the expr,cond pairs affect.
int_expr = self._sort_expr_cond(x, a, b)
# Finally run through the intervals and sum the evaluation.
ret_fun = 0
for int_a, int_b, expr in int_expr:
if isinstance(expr, Piecewise):
# If we still have a Piecewise by now, _sort_expr_cond would
# already have determined that its conditions are independent
# of the integration variable, thus we just use substitution.
ret_fun += piecewise_fold(
super(Piecewise, expr)._eval_interval(x, Max(a, int_a), Min(b, int_b)))
else:
ret_fun += expr._eval_interval(x, Max(a, int_a), Min(b, int_b))
return mul * ret_fun
def _sort_expr_cond(self, sym, a, b, targetcond=None):
"""Determine what intervals the expr, cond pairs affect.
1) If cond is True, then log it as default
1.1) Currently if cond can't be evaluated, throw NotImplementedError.
2) For each inequality, if previous cond defines part of the interval
update the new conds interval.
- eg x < 1, x < 3 -> [oo,1],[1,3] instead of [oo,1],[oo,3]
3) Sort the intervals to make it easier to find correct exprs
Under normal use, we return the expr,cond pairs in increasing order
along the real axis corresponding to the symbol sym. If targetcond
is given, we return a list of (lowerbound, upperbound) pairs for
this condition.
"""
from ...solvers.inequalities import solve_univariate_inequality
default = None
int_expr = []
expr_cond = []
or_cond = False
or_intervals = []
independent_expr_cond = []
if isinstance(targetcond, Relational) and targetcond.has(sym):
targetcond = solve_univariate_inequality(targetcond, sym)
for expr, cond in self.args: # pragma: no branch
if isinstance(cond, Relational) and cond.has(sym):
cond = solve_univariate_inequality(cond, sym)
if isinstance(cond, Or):
for cond2 in sorted(cond.args, key=default_sort_key):
expr_cond.append((expr, cond2))
else:
expr_cond.append((expr, cond))
if cond == true:
break
for expr, cond in expr_cond: # pragma: no branch
if cond == true:
independent_expr_cond.append((expr, cond))
default = self.func(*independent_expr_cond)
break
orig_cond = cond
if sym not in cond.free_symbols:
independent_expr_cond.append((expr, cond))
continue
if isinstance(cond, Equality):
continue
if isinstance(cond, And):
lower = -oo
upper = oo
for cond2 in cond.args:
if sym not in [cond2.lts, cond2.gts]:
cond2 = solve_univariate_inequality(cond2, sym)
if cond2.lts == sym:
upper = Min(cond2.gts, upper)
elif cond2.gts == sym:
lower = Max(cond2.lts, lower)
else:
raise NotImplementedError(
'Unable to handle interval evaluation of expression.')
else:
lower, upper = cond.lts, cond.gts # part 1: initialize with givens
if cond.lts == sym: # part 1a: expand the side ...
lower = -oo # e.g. x <= 0 ---> -oo <= 0
elif cond.gts == sym: # part 1a: ... that can be expanded
upper = oo # e.g. x >= 0 ---> oo >= 0
else:
raise NotImplementedError(
'Unable to handle interval evaluation of expression.')
# part 1b: Reduce (-)infinity to what was passed in.
lower, upper = Max(a, lower), Min(b, upper)
for n, ni in enumerate(int_expr):
# Part 2: remove any interval overlap. For any conflicts, the
# iterval already there wins, and the incoming interval updates
# its bounds accordingly.
if self.__eval_cond(lower < ni[1]) and \
self.__eval_cond(lower >= ni[0]):
lower = ni[1]
elif len(ni[1].free_symbols) and \
self.__eval_cond(lower >= ni[0]):
if self.__eval_cond(lower == ni[0]):
lower = ni[1]
else:
int_expr[n][1] = Min(lower, ni[1])
elif len(ni[0].free_symbols) and \
self.__eval_cond(upper == ni[1]):
upper = Min(upper, ni[0])
elif len(ni[1].free_symbols) and \
(lower >= ni[0]) != true and \
(ni[1] == Min(lower, upper)) is not True:
upper = Min(upper, ni[0])
elif self.__eval_cond(upper > ni[0]) and \
self.__eval_cond(upper <= ni[1]):
upper = ni[0]
elif len(ni[0].free_symbols) and \
self.__eval_cond(upper < ni[1]):
int_expr[n][0] = Max(upper, ni[0])
if self.__eval_cond(lower >= upper) is not True: # Is it still an interval?
int_expr.append([lower, upper, expr])
if orig_cond == targetcond:
return [(lower, upper, None)]
elif isinstance(targetcond, Or) and cond in targetcond.args:
or_cond = Or(or_cond, cond)
or_intervals.append((lower, upper, None))
if or_cond == targetcond:
or_intervals.sort(key=lambda x: x[0])
return or_intervals
int_expr.sort(key=lambda x: x[1].sort_key(
) if x[1].is_number else (-oo).sort_key())
int_expr.sort(key=lambda x: x[0].sort_key(
) if x[0].is_number else oo.sort_key())
for n, ni in enumerate(int_expr):
if len(ni[0].free_symbols) or len(ni[1].free_symbols):
if isinstance(ni[1], Min) or ni[1] == b:
newval = Min(*ni[:-1])
if n > 0 and ni[0] == int_expr[n - 1][1]:
int_expr[n - 1][1] = newval
int_expr[n][0] = newval
else:
newval = Max(*ni[:-1])
if n < len(int_expr) - 1 and ni[1] == int_expr[n + 1][0]:
int_expr[n + 1][0] = newval
int_expr[n][1] = newval
# Add holes to list of intervals if there is a default value,
# otherwise raise a ValueError.
holes = []
curr_low = a
for int_a, int_b, expr in int_expr:
if (curr_low < int_a) == true:
holes.append([curr_low, Min(b, int_a), default])
elif (curr_low >= int_a) != true:
holes.append([curr_low, Min(b, int_a), default])
curr_low = Min(b, int_b)
if (curr_low < b) == true:
holes.append([Min(b, curr_low), b, default])
elif (curr_low >= b) != true:
holes.append([Min(b, curr_low), b, default])
if holes and default is not None:
int_expr.extend(holes)
if targetcond == true:
return [(h[0], h[1], None) for h in holes]
return int_expr
def _eval_nseries(self, x, n, logx):
args = [(ec.expr._eval_nseries(x, n, logx),
ec.cond.limit(x, 0)) for ec in self.args]
return self.func(*args)
def _eval_power(self, other):
return self.func(*[(e**other, c) for e, c in self.args])
def _eval_subs(self, old, new):
"""Piecewise conditions may contain bool which are not of Basic type."""
args = list(self.args)
for i, (e, c) in enumerate(args): # pragma: no branch
c = c._subs(old, new)
if c != false:
e = e._subs(old, new)
args[i] = e, c
if c == true:
return self.func(*args)
def _eval_transpose(self):
return self.func(*[(e.transpose(), c) for e, c in self.args])
def _eval_template_is_attr(self, is_attr, when_multiple=None):
b = None
for expr, _ in self.args:
a = getattr(expr, is_attr)
if a is None:
return
if b is None:
b = a
elif b is not a:
return when_multiple
return b
def _eval_is_finite(self):
return self._eval_template_is_attr('is_finite')
def _eval_is_complex(self):
return self._eval_template_is_attr('is_complex')
def _eval_is_imaginary(self):
return self._eval_template_is_attr('is_imaginary')
def _eval_is_integer(self):
return self._eval_template_is_attr('is_integer')
def _eval_is_irrational(self):
return self._eval_template_is_attr('is_irrational')
def _eval_is_negative(self):
return self._eval_template_is_attr('is_negative')
def _eval_is_nonnegative(self):
return self._eval_template_is_attr('is_nonnegative')
def _eval_is_nonpositive(self):
return self._eval_template_is_attr('is_nonpositive')
def _eval_is_nonzero(self):
return self._eval_template_is_attr('is_nonzero')
def _eval_is_odd(self):
return self._eval_template_is_attr('is_odd')
def _eval_is_polar(self):
return self._eval_template_is_attr('is_polar')
def _eval_is_positive(self):
return self._eval_template_is_attr('is_positive')
def _eval_is_extended_real(self):
return self._eval_template_is_attr('is_extended_real')
def _eval_is_zero(self):
return self._eval_template_is_attr('is_zero')
@classmethod
def __eval_cond(cls, cond):
"""Return the truth value of the condition."""
if cond == true:
return True
if isinstance(cond, Equality):
diff = cond.lhs - cond.rhs
if diff.is_commutative:
return diff.is_zero
def as_expr_set_pairs(self):
exp_sets = []
U = ExtendedReals
for expr, cond in self.args:
cond_int = U.intersection(cond.as_set())
U = U - cond_int
exp_sets.append((expr, cond_int))
return exp_sets
def _eval_rewrite_as_tractable(self, *args, wrt=None, **kwargs):
if wrt is not None:
for a, c in args: # pragma: no branch
if c.free_symbols - {wrt}:
return
if c.limit(wrt, oo):
return a
def piecewise_fold(expr):
"""
Takes an expression containing a piecewise function and returns the
expression in piecewise form.
Examples
========
>>> p = Piecewise((x, x < 1), (1, True))
>>> piecewise_fold(x*p)
Piecewise((x**2, x < 1), (x, true))
See Also
========
diofant.functions.elementary.piecewise.Piecewise
"""
if not isinstance(expr, Basic) or not expr.has(Piecewise):
return expr
new_args = list(map(piecewise_fold, expr.args))
if isinstance(expr, ExprCondPair):
return ExprCondPair(*new_args)
piecewise_args = []
for n, arg in enumerate(new_args):
if isinstance(arg, Piecewise):
piecewise_args.append(n)
if len(piecewise_args) > 0:
n = piecewise_args[0]
new_args = [(expr.func(*(new_args[:n] + [e] + new_args[n + 1:])), c)
for e, c in new_args[n].args]
if isinstance(expr, Boolean):
# If expr is Boolean, we must return some kind of PiecewiseBoolean.
# This is constructed by means of Or, And and Not.
# piecewise_fold(0 < Piecewise( (sin(x), x<0), (cos(x), True)))
# can't return Piecewise((0 < sin(x), x < 0), (0 < cos(x), True))
# but instead Or(And(x < 0, 0 < sin(x)), And(0 < cos(x), Not(x<0)))
other = True
rtn = False
for e, c in new_args:
rtn = Or(rtn, And(other, c, e))
other = And(other, Not(c))
if len(piecewise_args) > 1:
return piecewise_fold(rtn)
return rtn
if len(piecewise_args) > 1:
return piecewise_fold(Piecewise(*new_args))
return Piecewise(*new_args)
else:
return expr.func(*new_args)
| bsd-3-clause | 4788eab2dc961bd86f624730f18d9094 | 38.282686 | 96 | 0.506207 | 3.929657 | false | false | false | false |
diofant/diofant | diofant/printing/repr.py | 1 | 6770 | """
A Printer for generating executable code.
The most important function here is srepr (that is an exact equivalent of
builtin repr, except for optional arguments) that returns a string so that the
relation eval(srepr(expr))=expr holds in an appropriate environment.
"""
from __future__ import annotations
import typing
import mpmath.libmp as mlib
from mpmath.libmp import prec_to_dps, repr_dps
from ..core.function import AppliedUndef
from ..utilities import default_sort_key
from .defaults import DefaultPrinting
from .printer import Printer
class ReprPrinter(Printer):
"""Repr printer."""
printmethod = '_diofantrepr'
_default_settings: dict[str, typing.Any] = {
'order': None
}
def reprify(self, args, sep):
"""
Prints each item in `args` and joins them with `sep`.
"""
return sep.join([self.doprint(item) for item in args])
def emptyPrinter(self, expr):
"""
The fallback printer.
"""
if hasattr(expr, 'args') and hasattr(expr.args, '__iter__'):
l = []
for o in expr.args:
l.append(self._print(o))
return expr.__class__.__name__ + '(%s)' % ', '.join(l)
elif hasattr(expr, '__repr__') and not issubclass(expr.__class__,
DefaultPrinting):
return repr(expr)
else:
return object.__repr__(expr)
def _print_Dict(self, expr):
l = []
for o in sorted(expr.args, key=default_sort_key):
l.append(self._print(o))
return expr.__class__.__name__ + '(%s)' % ', '.join(l)
def _print_Add(self, expr, order=None):
args = expr.as_ordered_terms(order=order or self.order)
args = map(self._print, args)
return 'Add(%s)' % ', '.join(args)
def _print_Function(self, expr):
r = self._print(expr.func)
r += '(%s)' % ', '.join([self._print(a) for a in expr.args])
return r
def _print_FunctionClass(self, expr):
if issubclass(expr, AppliedUndef):
return f'Function({expr.__name__!r})'
else:
return expr.__name__
def _print_RationalConstant(self, expr):
return f'Rational({expr.numerator}, {expr.denominator})'
def _print_AtomicExpr(self, expr):
return str(expr)
def _print_NumberSymbol(self, expr):
return str(expr)
def _print_Integer(self, expr):
return 'Integer(%i)' % int(expr.numerator)
def _print_list(self, expr):
return '[%s]' % self.reprify(expr, ', ')
def _print_MatrixBase(self, expr):
# special case for some empty matrices
if (expr.rows == 0) ^ (expr.cols == 0):
return '%s(%s, %s, %s)' % (expr.__class__.__name__,
self._print(expr.rows),
self._print(expr.cols),
self._print([]))
l = []
for i in range(expr.rows):
l.append([])
for j in range(expr.cols):
l[-1].append(expr[i, j])
return f'{expr.__class__.__name__}({self._print(l)})'
def _print_BooleanTrue(self, expr):
return 'true'
def _print_BooleanFalse(self, expr):
return 'false'
def _print_NaN(self, expr):
return 'nan'
def _print_Mul(self, expr, order=None):
terms = expr.args
args = expr._new_rawargs(*terms).as_ordered_factors()
args = map(self._print, args)
return 'Mul(%s)' % ', '.join(args)
def _print_Rational(self, expr):
return 'Rational(%s, %s)' % (self._print(int(expr.numerator)),
self._print(int(expr.denominator)))
def _print_Float(self, expr):
dps = prec_to_dps(expr._prec)
r = mlib.to_str(expr._mpf_, repr_dps(expr._prec))
return f"{expr.__class__.__name__}('{r}', dps={dps:d})"
def _print_BaseSymbol(self, expr):
d = expr._assumptions.generator
if d == {}:
return f'{expr.__class__.__name__}({self._print(expr.name)})'
else:
attr = [f'{k}={v}' for k, v in d.items()]
return '%s(%s, %s)' % (expr.__class__.__name__,
self._print(expr.name), ', '.join(attr))
def _print_str(self, expr):
return repr(expr)
def _print_tuple(self, expr):
if len(expr) == 1:
return '(%s,)' % self._print(expr[0])
else:
return '(%s)' % self.reprify(expr, ', ')
def _print_WildFunction(self, expr):
return f"{expr.__class__.__name__}('{expr.name}')"
def _print_PolynomialRing(self, ring):
return '%s(%s, %s, %s)' % (ring.__class__.__name__,
self._print(ring.domain),
self._print(ring.symbols),
self._print(ring.order))
def _print_GMPYIntegerRing(self, expr):
return f'{expr.__class__.__name__}()'
_print_GMPYRationalField = _print_GMPYIntegerRing
_print_PythonIntegerRing = _print_GMPYIntegerRing
_print_PythonRationalField = _print_GMPYIntegerRing
_print_LexOrder = _print_GMPYIntegerRing
_print_GradedLexOrder = _print_LexOrder
def _print_FractionField(self, field):
return '%s(%s, %s, %s)' % (field.__class__.__name__,
self._print(field.domain), self._print(field.symbols), self._print(field.order))
def _print_PolyElement(self, poly):
terms = list(poly.items())
terms.sort(key=poly.ring.order, reverse=True)
return f'{poly.__class__.__name__}({self._print(poly.ring)}, {self._print(terms)})'
def _print_FracElement(self, frac):
numer_terms = list(frac.numerator.items())
numer_terms.sort(key=frac.field.order, reverse=True)
denom_terms = list(frac.denominator.items())
denom_terms.sort(key=frac.field.order, reverse=True)
numer = self._print(numer_terms)
denom = self._print(denom_terms)
return f'{frac.__class__.__name__}({self._print(frac.field)}, {numer}, {denom})'
def _print_AlgebraicField(self, expr):
return 'AlgebraicField(%s, %s)' % (self._print(expr.domain),
self._print(expr.ext.as_expr()))
def _print_AlgebraicElement(self, expr):
return '%s(%s)' % (self._print(expr.parent),
self._print(list(map(expr.domain.domain.to_expr, expr.rep.all_coeffs()))))
def _print_Domain(self, expr):
return expr.rep
def srepr(expr, **settings):
"""Return expr in repr form."""
return ReprPrinter(settings).doprint(expr)
| bsd-3-clause | 6f4a6bc47923595a712ec601d62e4cf3 | 33.717949 | 115 | 0.542541 | 3.681349 | false | false | false | false |
diofant/diofant | diofant/utilities/autowrap.py | 1 | 31290 | """Module for compiling codegen output, and wrap the binary for use in
python.
This module provides a common interface for different external backends, such
as f2py, fwrap, Cython, SWIG(?) etc. (Currently only f2py and Cython are
implemented) The goal is to provide access to compiled binaries of acceptable
performance with a one-button user interface, i.e.
>>> expr = ((x - y)**25).expand()
>>> binary_callable = autowrap(expr)
>>> binary_callable(1, 2)
-1.0
The callable returned from autowrap() is a binary python function, not a
Diofant object. If it is desired to use the compiled function in symbolic
expressions, it is better to use binary_function() which returns a Diofant
Function object. The binary callable is attached as the _imp_ attribute and
invoked when a numerical evaluation is requested with evalf(), or with
lambdify().
>>> f = binary_function('f', expr)
>>> 2*f(x, y) + y
y + 2*f(x, y)
>>> (2*f(x, y) + y).evalf(2, subs={x: 1, y: 2}, strict=False)
0.e-190
The idea is that a Diofant user will primarily be interested in working with
mathematical expressions, and should not have to learn details about wrapping
tools in order to evaluate expressions numerically, even if they are
computationally expensive.
When is this useful?
1) For computations on large arrays, Python iterations may be too slow,
and depending on the mathematical expression, it may be difficult to
exploit the advanced index operations provided by NumPy.
2) For *really* long expressions that will be called repeatedly, the
compiled binary should be significantly faster than Diofant's .evalf()
3) If you are generating code with the codegen utility in order to use
it in another project, the automatic python wrappers let you test the
binaries immediately from within Diofant.
4) To create customized ufuncs for use with numpy arrays.
See *ufuncify*.
When is this module NOT the best approach?
1) If you are really concerned about speed or memory optimizations,
you will probably get better results by working directly with the
wrapper tools and the low level code. However, the files generated
by this utility may provide a useful starting point and reference
code. Temporary files will be left intact if you supply the keyword
tempdir="path/to/files/".
2) If the array computation can be handled easily by numpy, and you
don't need the binaries for another project.
"""
_doctest_depends_on = {'exe': ('f2py', 'gfortran', 'gcc'), 'modules': ('numpy',)}
import os
import shutil
import sys
import tempfile
from string import Template
from subprocess import STDOUT, CalledProcessError, check_output
from ..core import Dummy, Eq, Lambda, Symbol, cacheit
from ..core.compatibility import iterable
from ..tensor import Idx, IndexedBase
from .codegen import (CCodeGen, CodeGenArgumentListError, InOutArgument,
InputArgument, OutputArgument, Result, ResultBase,
get_code_generator, make_routine)
from .decorator import doctest_depends_on
from .lambdify import implemented_function
class CodeWrapError(Exception):
"""Generic code wrapping error."""
class CodeWrapper:
"""Base Class for code wrappers."""
_filename = 'wrapped_code'
_module_basename = 'wrapper_module'
_module_counter = 0
@property
def filename(self):
return f'{self._filename}_{CodeWrapper._module_counter}'
@property
def module_name(self):
return f'{self._module_basename}_{CodeWrapper._module_counter}'
def __init__(self, generator, filepath=None, flags=[], verbose=False):
"""Generator -- the code generator to use."""
self.generator = generator
self.filepath = filepath
self.flags = flags
self.quiet = not verbose
@property
def include_header(self):
return bool(self.filepath)
@property
def include_empty(self):
return bool(self.filepath)
def _generate_code(self, main_routine, routines):
routines.append(main_routine)
self.generator.write(
routines, self.filename, True, self.include_header,
self.include_empty)
def wrap_code(self, routine, helpers=[]):
workdir = self.filepath or tempfile.mkdtemp('_diofant_compile')
if not os.access(workdir, os.F_OK):
os.mkdir(workdir)
oldwork = os.getcwd()
os.chdir(workdir)
try:
sys.path.append(workdir)
self._generate_code(routine, helpers)
self._prepare_files(routine)
self._process_files(routine)
mod = __import__(self.module_name)
finally:
sys.path.remove(workdir)
CodeWrapper._module_counter += 1
os.chdir(oldwork)
if not self.filepath:
shutil.rmtree(workdir)
return self._get_wrapped_function(mod, routine.name)
def _process_files(self, routine):
command = self.command
command.extend(self.flags)
try:
retoutput = check_output(command, stderr=STDOUT)
except CalledProcessError as exc:
raise CodeWrapError(
'Error while executing command: %s. Command output is:\n%s' % (
' '.join(command), exc.output.decode())) from exc
if not self.quiet:
print(retoutput)
class DummyWrapper(CodeWrapper):
"""Class used for testing independent of backends."""
template = """# dummy module for testing of Diofant
def %(name)s():
return "%(expr)s"
%(name)s.args = "%(args)s"
%(name)s.returns = "%(retvals)s"
"""
def _prepare_files(self, routine):
return
def _generate_code(self, main_routine, routines):
with open(f'{self.module_name}.py', 'w', encoding='utf-8') as f:
printed = ', '.join(
[str(res.expr) for res in main_routine.result_variables])
# convert OutputArguments to return value like f2py
args = filter(lambda x: not isinstance(
x, OutputArgument), main_routine.arguments)
retvals = []
for val in main_routine.result_variables:
if isinstance(val, Result):
retvals.append('nameless')
else:
retvals.append(val.result_var)
print(DummyWrapper.template % {
'name': main_routine.name,
'expr': printed,
'args': ', '.join([str(a.name) for a in args]),
'retvals': ', '.join([str(val) for val in retvals])
}, end='', file=f)
def _process_files(self, routine):
return
@classmethod
def _get_wrapped_function(cls, mod, name):
return getattr(mod, name)
class CythonCodeWrapper(CodeWrapper):
"""Wrapper that uses Cython."""
setup_template = (
'from setuptools import setup\n'
'from setuptools.extension import Extension\n'
'from Cython.Distutils import build_ext\n'
'{np_import}'
'\n'
'setup(\n'
" cmdclass = {{'build_ext': build_ext}},\n"
' ext_modules = [Extension({ext_args},\n'
" extra_compile_args=['-std=c99'])],\n"
'{np_includes}'
' )')
pyx_imports = (
'import numpy as np\n'
'cimport numpy as np\n\n')
pyx_header = (
"cdef extern from '{header_file}.h':\n"
' {prototype}\n\n')
pyx_func = (
'def {name}_c({arg_string}):\n'
'\n'
'{declarations}'
'{body}')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._need_numpy = False
@property
def command(self):
command = [sys.executable, 'setup.py', 'build_ext', '--inplace']
return command
def _prepare_files(self, routine):
pyxfilename = self.module_name + '.pyx'
codefilename = f'{self.filename}.{self.generator.code_extension}'
# pyx
with open(pyxfilename, 'w', encoding='utf-8') as f:
self.dump_pyx([routine], f, self.filename)
# setup.py
ext_args = [repr(self.module_name), repr([pyxfilename, codefilename])]
if self._need_numpy:
np_import = 'import numpy as np\n'
np_includes = ' include_dirs = [np.get_include()],\n'
else:
np_import = ''
np_includes = ''
with open('setup.py', 'w', encoding='utf-8') as f:
f.write(self.setup_template.format(ext_args=', '.join(ext_args),
np_import=np_import,
np_includes=np_includes))
@classmethod
def _get_wrapped_function(cls, mod, name):
return getattr(mod, name + '_c')
def dump_pyx(self, routines, f, prefix):
"""Write a Cython file with python wrappers
This file contains all the definitions of the routines in c code and
refers to the header file.
Parameters
==========
routines : list
List of Routine instances
f : file
File-like object to write the file to
prefix : str
The filename prefix, used to refer to the proper header file.
Only the basename of the prefix is used.
"""
headers = []
functions = []
for routine in routines:
prototype = self.generator.get_prototype(routine)
# C Function Header Import
headers.append(self.pyx_header.format(header_file=prefix,
prototype=prototype))
# Partition the C function arguments into categories
py_rets, py_args, py_loc, py_inf = self._partition_args(routine.arguments)
# Function prototype
name = routine.name
arg_string = ', '.join(self._prototype_arg(arg) for arg in py_args)
# Local Declarations
local_decs = []
for arg, val in py_inf.items():
proto = self._prototype_arg(arg)
mat, ind = val
local_decs.append(f' cdef {proto} = {mat}.shape[{ind}]')
local_decs.extend([f' cdef {self._declare_arg(a)}' for a in py_loc])
declarations = '\n'.join(local_decs)
if declarations:
declarations = declarations + '\n'
# Function Body
args_c = ', '.join([self._call_arg(a) for a in routine.arguments])
rets = ', '.join([str(r.name) for r in py_rets])
if routine.results:
body = f' return {routine.name}({args_c})'
else:
body = f' {routine.name}({args_c})\n'
body = body + ' return ' + rets
functions.append(self.pyx_func.format(name=name, arg_string=arg_string,
declarations=declarations, body=body))
# Write text to file
if self._need_numpy:
# Only import numpy if required
f.write(self.pyx_imports)
f.write('\n'.join(headers))
f.write('\n'.join(functions))
def _partition_args(self, args):
"""Group function arguments into categories."""
py_args = []
py_returns = []
py_locals = []
py_inferred = {}
for arg in args:
if isinstance(arg, OutputArgument):
py_returns.append(arg)
py_locals.append(arg)
elif isinstance(arg, InOutArgument):
py_returns.append(arg)
py_args.append(arg)
else:
py_args.append(arg)
# Find arguments that are array dimensions. These can be inferred
# locally in the Cython code.
if isinstance(arg, (InputArgument, InOutArgument)) and arg.dimensions:
dims = [d[1] + 1 for d in arg.dimensions]
sym_dims = [(i, d) for (i, d) in enumerate(dims) if isinstance(d, (Dummy, Symbol))]
for (i, d) in sym_dims:
py_inferred[d] = (arg.name, i)
for arg in args:
if arg.name in py_inferred:
py_inferred[arg] = py_inferred.pop(arg.name)
# Filter inferred arguments from py_args
py_args = [a for a in py_args if a not in py_inferred]
return py_returns, py_args, py_locals, py_inferred
def _prototype_arg(self, arg):
mat_dec = 'np.ndarray[{mtype}, ndim={ndim}] {name}'
np_types = {'double': 'np.double_t',
'int': 'np.int_t'}
t = arg.get_datatype('c')
if arg.dimensions:
self._need_numpy = True
ndim = len(arg.dimensions)
mtype = np_types[t]
return mat_dec.format(mtype=mtype, ndim=ndim, name=arg.name)
else:
return f'{t} {arg.name!s}'
def _declare_arg(self, arg):
proto = self._prototype_arg(arg)
if arg.dimensions:
shape = '(' + ','.join(str(i[1] + 1) for i in arg.dimensions) + ')'
return proto + f' = np.empty({shape})'
else:
return proto + ' = 0'
def _call_arg(self, arg):
if arg.dimensions:
t = arg.get_datatype('c')
return f'<{t}*> {arg.name}.data'
elif isinstance(arg, ResultBase):
return f'&{arg.name}'
else:
return str(arg.name)
class F2PyCodeWrapper(CodeWrapper):
"""Wrapper that uses f2py."""
@property
def command(self):
filename = self.filename + '.' + self.generator.code_extension
args = ['-c', '-m', self.module_name, filename]
command = [sys.executable, '-c', 'import numpy.f2py as f2py2e;f2py2e.main()']+args
return command
def _prepare_files(self, routine):
pass
@classmethod
def _get_wrapped_function(cls, mod, name):
return getattr(mod, name)
def _get_code_wrapper_class(backend):
wrappers = {'F2PY': F2PyCodeWrapper, 'CYTHON': CythonCodeWrapper,
'DUMMY': DummyWrapper}
return wrappers[backend.upper()]
# Here we define a lookup of backends -> tuples of languages. For now, each
# tuple is of length 1, but if a backend supports more than one language,
# the most preferable language is listed first.
_lang_lookup = {'CYTHON': ('C',),
'F2PY': ('F95',),
'NUMPY': ('C',),
'DUMMY': ('F95',)} # Dummy here just for testing
def _infer_language(backend):
"""For a given backend, return the top choice of language."""
langs = _lang_lookup.get(backend.upper(), False)
if not langs:
raise ValueError('Unrecognized backend: ' + backend)
return langs[0]
def _validate_backend_language(backend, language):
"""Throws error if backend and language are incompatible."""
langs = _lang_lookup.get(backend.upper(), False)
if not langs:
raise ValueError('Unrecognized backend: ' + backend)
if language.upper() not in langs:
raise ValueError(f'Backend {backend} and language {language} are '
'incompatible')
@cacheit
@doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',))
def autowrap(expr, language=None, backend='f2py', tempdir=None, args=None,
flags=None, verbose=False, helpers=[]):
"""Generates python callable binaries based on the math expression.
Parameters
==========
expr
The Diofant expression that should be wrapped as a binary routine.
language : string, optional
If supplied, (options: 'C' or 'F95'), specifies the language of the
generated code. If ``None`` [default], the language is inferred based
upon the specified backend.
backend : string, optional
Backend used to wrap the generated code. Either 'f2py' [default],
or 'cython'.
tempdir : string, optional
Path to directory for temporary files. If this argument is supplied,
the generated code and the wrapper input files are left intact in the
specified path.
args : iterable, optional
An ordered iterable of symbols. Specifies the argument sequence for the
function.
flags : iterable, optional
Additional option flags that will be passed to the backend.
verbose : bool, optional
If True, autowrap will not mute the command line backends. This can be
helpful for debugging.
helpers : iterable, optional
Used to define auxillary expressions needed for the main expr. If the
main expression needs to call a specialized function it should be put
in the ``helpers`` iterable. Autowrap will then make sure that the
compiled main expression can link to the helper routine. Items should
be tuples with (<function_name>, <diofant_expression>, <arguments>). It
is mandatory to supply an argument sequence to helper routines.
Examples
========
>>> expr = ((x - y + z)**13).expand()
>>> binary_func = autowrap(expr)
>>> binary_func(1, 4, 2)
-1.0
"""
if language:
_validate_backend_language(backend, language)
else:
language = _infer_language(backend)
flags = flags if flags else ()
args = list(args) if iterable(args, exclude=set) else args
code_generator = get_code_generator(language, 'autowrap')
CodeWrapperClass = _get_code_wrapper_class(backend)
code_wrapper = CodeWrapperClass(code_generator, tempdir, flags, verbose)
helps = []
for name_h, expr_h, args_h in helpers:
helps.append(make_routine(name_h, expr_h, args_h))
for name_h, expr_h, args_h in helpers:
if expr.has(expr_h):
name_h = binary_function(name_h, expr_h, backend='dummy')
expr = expr.subs({expr_h: name_h(*args_h)})
try:
routine = make_routine('autofunc', expr, args)
except CodeGenArgumentListError as e:
# if all missing arguments are for pure output, we simply attach them
# at the end and try again, because the wrappers will silently convert
# them to return values anyway.
new_args = []
for missing in e.missing_args:
if not isinstance(missing, OutputArgument):
raise
new_args.append(missing.name)
routine = make_routine('autofunc', expr, list(args) + new_args)
return code_wrapper.wrap_code(routine, helpers=helps)
@doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',))
def binary_function(symfunc, expr, **kwargs):
"""Returns a diofant function with expr as binary implementation
This is a convenience function that automates the steps needed to
autowrap the Diofant expression and attaching it to a Function object
with implemented_function().
>>> expr = ((x - y)**25).expand()
>>> f = binary_function('f', expr)
>>> type(f)
<class 'diofant.core.function.UndefinedFunction'>
>>> 2*f(x, y)
2*f(x, y)
>>> f(x, y).evalf(2, subs={x: 1, y: 2})
-1.0
"""
binary = autowrap(expr, **kwargs)
return implemented_function(symfunc, binary)
#################################################################
# UFUNCIFY #
#################################################################
_ufunc_top = Template("""\
#include "Python.h"
#include "math.h"
#include "numpy/ndarraytypes.h"
#include "numpy/ufuncobject.h"
#include "numpy/halffloat.h"
#include ${include_file}
static PyMethodDef ${module}Methods[] = {
{NULL, NULL, 0, NULL}
};""")
_ufunc_body = Template("""\
static void ${funcname}_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data)
{
npy_intp i;
npy_intp n = dimensions[0];
${declare_args}
${declare_steps}
for (i = 0; i < n; i++) {
*((double *)out1) = ${funcname}(${call_args});
${step_increments}
}
}
PyUFuncGenericFunction ${funcname}_funcs[1] = {&${funcname}_ufunc};
static char ${funcname}_types[${n_types}] = ${types}
static void *${funcname}_data[1] = {NULL};""")
_ufunc_bottom = Template("""\
#if PY_VERSION_HEX >= 0x03000000
static struct PyModuleDef moduledef = {
PyModuleDef_HEAD_INIT,
"${module}",
NULL,
-1,
${module}Methods,
NULL,
NULL,
NULL,
NULL
};
PyMODINIT_FUNC PyInit_${module}(void)
{
PyObject *m, *d;
${function_creation}
m = PyModule_Create(&moduledef);
if (!m) {
return NULL;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
${ufunc_init}
return m;
}
#else
PyMODINIT_FUNC init${module}(void)
{
PyObject *m, *d;
${function_creation}
m = Py_InitModule("${module}", ${module}Methods);
if (m == NULL) {
return;
}
import_array();
import_umath();
d = PyModule_GetDict(m);
${ufunc_init}
}
#endif\
""")
_ufunc_init_form = Template("""\
ufunc${ind} = PyUFunc_FromFuncAndData(${funcname}_funcs, ${funcname}_data, ${funcname}_types, 1, ${n_in}, ${n_out},
PyUFunc_None, "${module}", ${docstring}, 0);
PyDict_SetItemString(d, "${funcname}", ufunc${ind});
Py_DECREF(ufunc${ind});""")
_ufunc_setup = Template("""\
def configuration(parent_package='', top_path=None):
import numpy
from numpy.distutils.misc_util import Configuration
config = Configuration('',
parent_package,
top_path)
config.add_extension('${module}', sources=['${module}.c', '${filename}.c'])
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(configuration=configuration)""")
class UfuncifyCodeWrapper(CodeWrapper):
"""Wrapper for Ufuncify."""
@property
def command(self):
command = [sys.executable, 'setup.py', 'build_ext', '--inplace']
return command
def _prepare_files(self, routine):
# C
codefilename = self.module_name + '.c'
with open(codefilename, 'w', encoding='utf-8') as f:
self.dump_c([routine], f, self.filename)
# setup.py
with open('setup.py', 'w', encoding='utf-8') as f:
self.dump_setup(f)
@classmethod
def _get_wrapped_function(cls, mod, name):
return getattr(mod, name)
def dump_setup(self, f):
setup = _ufunc_setup.substitute(module=self.module_name,
filename=self.filename)
f.write(setup)
def dump_c(self, routines, f, prefix):
"""Write a C file with python wrappers
This file contains all the definitions of the routines in c code.
Parameters
==========
routines : list
List of Routine instances
f : file
File-like object to write the file to
prefix : str
The filename prefix, used to name the imported module.
"""
functions = []
function_creation = []
ufunc_init = []
module = self.module_name
include_file = f'"{prefix}.h"'
top = _ufunc_top.substitute(include_file=include_file, module=module)
for r_index, routine in enumerate(routines):
name = routine.name
# Partition the C function arguments into categories
py_in, _ = self._partition_args(routine.arguments)
n_in = len(py_in)
n_out = 1
# Declare Args
form = 'char *{0}{1} = args[{2}];'
arg_decs = [form.format('in', i, i) for i in range(n_in)]
arg_decs.append(form.format('out', 1, n_in))
declare_args = '\n '.join(arg_decs)
# Declare Steps
form = 'npy_intp {0}{1}_step = steps[{2}];'
step_decs = [form.format('in', i, i) for i in range(n_in)]
step_decs.append(form.format('out', 1, n_in))
declare_steps = '\n '.join(step_decs)
# Call Args
form = '*(double *)in{0}'
call_args = ', '.join([form.format(a) for a in range(n_in)])
# Step Increments
form = '{0}{1} += {0}{1}_step;'
step_incs = [form.format('in', i) for i in range(n_in)]
step_incs.append(form.format('out', 1))
step_increments = '\n '.join(step_incs)
# Types
n_types = n_in + n_out
types = '{' + ', '.join(['NPY_DOUBLE']*n_types) + '};'
# Docstring
docstring = '"Created in Diofant with Ufuncify"'
# Function Creation
function_creation.append(f'PyObject *ufunc{r_index};')
# Ufunc initialization
init_form = _ufunc_init_form.substitute(module=module,
funcname=name,
docstring=docstring,
n_in=n_in, n_out=n_out,
ind=r_index)
ufunc_init.append(init_form)
body = _ufunc_body.substitute(module=module, funcname=name,
declare_args=declare_args,
declare_steps=declare_steps,
call_args=call_args,
step_increments=step_increments,
n_types=n_types, types=types)
functions.append(body)
body = '\n\n'.join(functions)
ufunc_init = '\n '.join(ufunc_init)
function_creation = '\n '.join(function_creation)
bottom = _ufunc_bottom.substitute(module=module,
ufunc_init=ufunc_init,
function_creation=function_creation)
text = [top, body, bottom]
f.write('\n\n'.join(text))
def _partition_args(self, args):
"""Group function arguments into categories."""
py_in = []
py_out = []
for arg in args:
if isinstance(arg, OutputArgument):
if py_out:
msg = "Ufuncify doesn't support multiple OutputArguments"
raise ValueError(msg)
py_out.append(arg)
elif isinstance(arg, InOutArgument):
raise ValueError("Ufuncify doesn't support InOutArguments")
else:
py_in.append(arg)
return py_in, py_out
@cacheit
@doctest_depends_on(exe=('f2py', 'gfortran', 'gcc'), modules=('numpy',))
def ufuncify(args, expr, language=None, backend='numpy', tempdir=None,
flags=None, verbose=False, helpers=[]):
"""
Generates a binary function that supports broadcasting on numpy arrays.
Parameters
==========
args : iterable
Either a Symbol or an iterable of symbols. Specifies the argument
sequence for the function.
expr
A Diofant expression that defines the element wise operation.
language : string, optional
If supplied, (options: 'C' or 'F95'), specifies the language of the
generated code. If ``None`` [default], the language is inferred based
upon the specified backend.
backend : string, optional
Backend used to wrap the generated code. Either 'numpy' [default],
'cython', or 'f2py'.
tempdir : string, optional
Path to directory for temporary files. If this argument is supplied,
the generated code and the wrapper input files are left intact in the
specified path.
flags : iterable, optional
Additional option flags that will be passed to the backend
verbose : bool, optional
If True, autowrap will not mute the command line backends. This can be
helpful for debugging.
helpers : iterable, optional
Used to define auxillary expressions needed for the main expr. If the
main expression needs to call a specialized function it should be put
in the ``helpers`` iterable. Autowrap will then make sure that the
compiled main expression can link to the helper routine. Items should
be tuples with (<function_name>, <diofant_expression>, <arguments>). It
is mandatory to supply an argument sequence to helper routines.
Notes
=====
The default backend ('numpy') will create actual instances of
``numpy.ufunc``. These support ndimensional broadcasting, and implicit type
conversion. Use of the other backends will result in a "ufunc-like"
function, which requires equal length 1-dimensional arrays for all
arguments, and will not perform any type conversions.
References
==========
* https://docs.scipy.org/doc/numpy/reference/ufuncs.html
Examples
========
>>> import numpy as np
>>> f = ufuncify((x, y), y + x**2)
>>> type(f) is np.ufunc
True
>>> f([1, 2, 3], 2)
[ 3. 6. 11.]
>>> f(np.arange(5), 3)
[ 3. 4. 7. 12. 19.]
For the F2Py and Cython backends, inputs are required to be equal length
1-dimensional arrays. The F2Py backend will perform type conversion, but
the Cython backend will error if the inputs are not of the expected type.
>>> f_fortran = ufuncify((x, y), y + x**2, backend='F2Py')
>>> f_fortran(1, 2)
[ 3.]
>>> f_fortran(np.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]))
[ 2. 6. 12.]
"""
if isinstance(args, (Dummy, Symbol)):
args = args,
else:
args = tuple(args)
if language:
_validate_backend_language(backend, language)
else:
language = _infer_language(backend)
flags = flags if flags else ()
if backend.upper() == 'NUMPY':
helps = []
for name_h, expr_h, args_h in helpers:
helps.append(make_routine(name_h, expr_h, args_h))
for name_h, expr_h, args_h in helpers:
if expr.has(expr_h):
name_h = binary_function(name_h, expr_h, backend='dummy')
expr = expr.subs({expr_h: name_h(*args_h)})
routine = make_routine('autofunc', expr, args)
code_wrapper = UfuncifyCodeWrapper(CCodeGen('ufuncify'), tempdir,
flags, verbose)
return code_wrapper.wrap_code(routine, helpers=helps)
else:
# Dummies are used for all added expressions to prevent name clashes
# within the original expression.
y = IndexedBase(Dummy())
m = Dummy(integer=True)
i = Idx(Dummy(integer=True), m)
f = implemented_function(Dummy().name, Lambda(args, expr))
# For each of the args create an indexed version.
indexed_args = [IndexedBase(Dummy(str(a))) for a in args]
# Order the arguments (out, args, dim)
args = [y] + indexed_args + [m]
args_with_indices = [a[i] for a in indexed_args]
return autowrap(Eq(y[i], f(*args_with_indices)), language, backend,
tempdir, tuple(args), flags, verbose, helpers)
| bsd-3-clause | 31bf9082aee62f8472ab591d344192de | 34.236486 | 115 | 0.578012 | 3.991581 | false | false | false | false |
diofant/diofant | diofant/calculus/finite_diff.py | 1 | 13119 | """
Finite difference weights
=========================
This module implements an algorithm for efficient generation of finite
difference weights for ordinary differentials of functions for
derivatives from 0 (interpolation) up to arbitrary order.
The core algorithm is provided in the finite difference weight generating
function (finite_diff_weights), and two convenience functions are provided
for:
- estimating a derivative (or interpolate) directly from a series of points
is also provided (``apply_finite_diff``).
- making a finite difference approximation of a Derivative instance
(``as_finite_diff``).
"""
from ..core import Integer
from ..core.compatibility import iterable
def finite_diff_weights(order, x_list, x0=Integer(0)):
"""
Calculates the finite difference weights for an arbitrarily
spaced one-dimensional grid (x_list) for derivatives at 'x0'
of order 0, 1, ..., up to 'order' using a recursive formula.
Order of accuracy is at least len(x_list) - order, if x_list
is defined accurately.
Parameters
==========
order: int
Up to what derivative order weights should be calculated.
0 corresponds to interpolation.
x_list: sequence
Sequence of (unique) values for the independent variable.
It is useful (but not necessary) to order x_list from
nearest to furthest from x0; see examples below.
x0: Number or Symbol
Root or value of the independent variable for which the finite
difference weights should be generated. Defaults to Integer(0).
Returns
=======
list
A list of sublists, each corresponding to coefficients for
increasing derivative order, and each containing lists of
coefficients for increasing subsets of x_list.
Examples
========
>>> res = finite_diff_weights(1, [-Rational(1, 2), Rational(1, 2),
... Rational(3, 2), Rational(5, 2)], 0)
>>> res
[[[1, 0, 0, 0],
[1/2, 1/2, 0, 0],
[3/8, 3/4, -1/8, 0],
[5/16, 15/16, -5/16, 1/16]],
[[0, 0, 0, 0],
[-1, 1, 0, 0],
[-1, 1, 0, 0],
[-23/24, 7/8, 1/8, -1/24]]]
>>> res[0][-1] # FD weights for 0th derivative, using full x_list
[5/16, 15/16, -5/16, 1/16]
>>> res[1][-1] # FD weights for 1st derivative
[-23/24, 7/8, 1/8, -1/24]
>>> res[1][-2] # FD weights for 1st derivative, using x_list[:-1]
[-1, 1, 0, 0]
>>> res[1][-1][0] # FD weight for 1st deriv. for x_list[0]
-23/24
>>> res[1][-1][1] # FD weight for 1st deriv. for x_list[1], etc.
7/8
Each sublist contains the most accurate formula at the end.
Note, that in the above example res[1][1] is the same as res[1][2].
Since res[1][2] has an order of accuracy of
len(x_list[:3]) - order = 3 - 1 = 2, the same is true for res[1][1]!
>>> res = finite_diff_weights(1, [Integer(0), Integer(1), -Integer(1),
... Integer(2), -Integer(2)], 0)[1]
>>> res
[[0, 0, 0, 0, 0],
[-1, 1, 0, 0, 0],
[0, 1/2, -1/2, 0, 0],
[-1/2, 1, -1/3, -1/6, 0],
[0, 2/3, -2/3, -1/12, 1/12]]
>>> res[0] # no approximation possible, using x_list[0] only
[0, 0, 0, 0, 0]
>>> res[1] # classic forward step approximation
[-1, 1, 0, 0, 0]
>>> res[2] # classic centered approximation
[0, 1/2, -1/2, 0, 0]
>>> res[3:] # higher order approximations
[[-1/2, 1, -1/3, -1/6, 0], [0, 2/3, -2/3, -1/12, 1/12]]
Let us compare this to a differently defined x_list. Pay attention to
foo[i][k] corresponding to the gridpoint defined by x_list[k].
>>> foo = finite_diff_weights(1, [-Integer(2), -Integer(1), Integer(0),
... Integer(1), Integer(2)], 0)[1]
>>> foo
[[0, 0, 0, 0, 0],
[-1, 1, 0, 0, 0],
[1/2, -2, 3/2, 0, 0],
[1/6, -1, 1/2, 1/3, 0],
[1/12, -2/3, 0, 2/3, -1/12]]
>>> foo[1] # not the same and of lower accuracy as res[1]!
[-1, 1, 0, 0, 0]
>>> foo[2] # classic double backward step approximation
[1/2, -2, 3/2, 0, 0]
>>> foo[4] # the same as res[4]
[1/12, -2/3, 0, 2/3, -1/12]
Note that, unless you plan on using approximations based on subsets of
x_list, the order of gridpoints does not matter.
The capability to generate weights at arbitrary points can be
used e.g. to minimize Runge's phenomenon by using Chebyshev nodes:
>>> N, h = 4, symbols('h')
>>> x_list = [x + h*cos(i*pi/(N)) for i in range(N, -1, -1)] # chebyshev nodes
>>> x_list
[-h + x, -sqrt(2)*h/2 + x, x, sqrt(2)*h/2 + x, h + x]
>>> mycoeffs = finite_diff_weights(1, x_list, 0)[1][4]
>>> [simplify(c) for c in mycoeffs]
[(h**3/2 + h**2*x - 3*h*x**2 - 4*x**3)/h**4,
(-sqrt(2)*h**3 - 4*h**2*x + 3*sqrt(2)*h*x**2 + 8*x**3)/h**4,
6*x/h**2 - 8*x**3/h**4,
(sqrt(2)*h**3 - 4*h**2*x - 3*sqrt(2)*h*x**2 + 8*x**3)/h**4,
(-h**3/2 + h**2*x + 3*h*x**2 - 4*x**3)/h**4]
Notes
=====
If weights for a finite difference approximation of 3rd order
derivative is wanted, weights for 0th, 1st and 2nd order are
calculated "for free", so are formulae using subsets of x_list.
This is something one can take advantage of to save computational cost.
Be aware that one should define x_list from nearest to farest from
x_list. If not, subsets of x_list will yield poorer approximations,
which might not grand an order of accuracy of len(x_list) - order.
See also
========
diofant.calculus.finite_diff.apply_finite_diff
References
==========
* Generation of Finite Difference Formulas on Arbitrarily Spaced
Grids, Bengt Fornberg; Mathematics of computation; 51; 184;
(1988); 699-706; doi:10.1090/S0025-5718-1988-0935077-0
"""
# The notation below closely corresponds to the one used in the paper.
if order < 0:
raise ValueError('Negative derivative order illegal.')
if int(order) != order:
raise ValueError('Non-integer order illegal')
M = order
N = len(x_list) - 1
delta = [[[0 for nu in range(N+1)] for n in range(N+1)] for
m in range(M+1)]
delta[0][0][0] = Integer(1)
c1 = Integer(1)
for n in range(1, N+1):
c2 = Integer(1)
for nu in range(n):
c3 = x_list[n]-x_list[nu]
c2 = c2 * c3
if n <= M:
delta[n][n-1][nu] = 0
for m in range(min(n, M)+1):
delta[m][n][nu] = (x_list[n]-x0)*delta[m][n-1][nu] -\
m*delta[m-1][n-1][nu]
delta[m][n][nu] /= c3
for m in range(min(n, M)+1):
delta[m][n][n] = c1/c2*(m*delta[m-1][n-1][n-1] -
(x_list[n-1]-x0)*delta[m][n-1][n-1])
c1 = c2
return delta
def apply_finite_diff(order, x_list, y_list, x0=Integer(0)):
r"""
Calculates the finite difference approximation of
the derivative of requested order at x0 from points
provided in x_list and y_list.
Parameters
==========
order: int
order of derivative to approximate. 0 corresponds to interpolation.
x_list: sequence
Sequence of (unique) values for the independent variable.
y_list: sequence
The function value at corresponding values for the independent
variable in x_list.
x0: Number or Symbol
At what value of the independent variable the derivative should be
evaluated. Defaults to Integer(0).
Returns
=======
diofant.core.add.Add or diofant.core.numbers.Number
The finite difference expression approximating the requested
derivative order at x0.
Examples
========
>>> def cube(arg):
... return (1.0*arg)**3
>>> xlist = range(-3, 4)
>>> apply_finite_diff(2, xlist, list(map(cube, xlist)), 2) - 12
-3.55271367880050e-15
we see that the example above only contain rounding errors.
apply_finite_diff can also be used on more abstract objects:
>>> x, y = map(IndexedBase, 'xy')
>>> i = Idx('i')
>>> x_list, y_list = zip(*[(x[i + j], y[i + j]) for j in range(-1, 2)])
>>> apply_finite_diff(1, x_list, y_list, x[i])
(-1 + (x[i + 1] - x[i])/(-x[i - 1] + x[i]))*y[i]/(x[i + 1] - x[i]) +
(-x[i - 1] + x[i])*y[i + 1]/((-x[i - 1] + x[i + 1])*(x[i + 1] - x[i])) -
(x[i + 1] - x[i])*y[i - 1]/((-x[i - 1] + x[i + 1])*(-x[i - 1] + x[i]))
Notes
=====
Order = 0 corresponds to interpolation.
Only supply so many points you think makes sense
to around x0 when extracting the derivative (the function
need to be well behaved within that region). Also beware
of Runge's phenomenon.
See also
========
diofant.calculus.finite_diff.finite_diff_weights
References
==========
Fortran 90 implementation with Python interface for numerics: finitediff_
.. _finitediff: https://github.com/bjodah/finitediff
"""
# In the original paper the following holds for the notation:
# M = order
# N = len(x_list) - 1
N = len(x_list) - 1
if len(x_list) != len(y_list):
raise ValueError('x_list and y_list not equal in length.')
delta = finite_diff_weights(order, x_list, x0)
derivative = 0
for nu in range(len(x_list)):
derivative += delta[order][N][nu]*y_list[nu]
return derivative
def as_finite_diff(derivative, points=1, x0=None, wrt=None):
r"""
Returns an approximation of a derivative of a function in
the form of a finite difference formula. The expression is a
weighted sum of the function at a number of discrete values of
(one of) the independent variable(s).
Parameters
==========
derivative: a Derivative instance (needs to have an variables
and expr attribute).
points: sequence or coefficient, optional
If sequence: discrete values (length >= order+1) of the
independent variable used for generating the finite
difference weights.
If it is a coefficient, it will be used as the step-size
for generating an equidistant sequence of length order+1
centered around x0. default: 1 (step-size 1)
x0: number or Symbol, optional
the value of the independent variable (wrt) at which the
derivative is to be approximated. default: same as wrt
wrt: Symbol, optional
"with respect to" the variable for which the (partial)
derivative is to be approximated for. If not provided it
is required that the Derivative is ordinary. default: None
Examples
========
>>> h = symbols('h')
>>> as_finite_diff(f(x).diff(x))
-f(x - 1/2) + f(x + 1/2)
The default step size and number of points are 1 and ``order + 1``
respectively. We can change the step size by passing a symbol
as a parameter:
>>> as_finite_diff(f(x).diff(x), h)
-f(-h/2 + x)/h + f(h/2 + x)/h
We can also specify the discretized values to be used in a sequence:
>>> as_finite_diff(f(x).diff(x), [x, x+h, x+2*h])
-3*f(x)/(2*h) + 2*f(h + x)/h - f(2*h + x)/(2*h)
The algorithm is not restricted to use equidistant spacing, nor
do we need to make the approximation around x0, but we can get
an expression estimating the derivative at an offset:
>>> e, sq2 = exp(1), sqrt(2)
>>> xl = [x-h, x+h, x+e*h]
>>> as_finite_diff(f(x).diff((x, 1)), xl, x+h*sq2)
2*h*f(E*h + x)*((h + sqrt(2)*h)/(2*h) -
(-sqrt(2)*h + h)/(2*h))/((-h + E*h)*(h + E*h)) +
f(-h + x)*(-(-sqrt(2)*h + h)/(2*h) - (-sqrt(2)*h + E*h)/(2*h))/(h +
E*h) + f(h + x)*(-(h + sqrt(2)*h)/(2*h) + (-sqrt(2)*h +
E*h)/(2*h))/(-h + E*h)
Partial derivatives are also supported:
>>> d2fdxdy = f(x, y).diff(x, y)
>>> as_finite_diff(d2fdxdy, wrt=x)
-f(x - 1/2, y) + f(x + 1/2, y)
See also
========
diofant.calculus.finite_diff.apply_finite_diff
diofant.calculus.finite_diff.finite_diff_weights
"""
if wrt is None:
wrt = derivative.variables[0]
# we need Derivative to be univariate to guess wrt
if any(v != wrt for v in derivative.variables):
raise ValueError('if the function is not univariate' +
' then `wrt` must be given')
order = derivative.variables.count(wrt)
if x0 is None:
x0 = wrt
if not iterable(points):
# points is simply the step-size, let's make it a
# equidistant sequence centered around x0
if order % 2 == 0:
# even order => odd number of points, grid point included
points = [x0 + points*i for i
in range(-order//2, order//2 + 1)]
else:
# odd order => even number of points, half-way wrt grid point
points = [x0 + points*i/Integer(2) for i
in range(-order, order + 1, 2)]
if len(points) < order+1:
raise ValueError(f'Too few points for order {order:d}')
return apply_finite_diff(order, points, [
derivative.expr.subs({wrt: x}) for x in points], x0)
| bsd-3-clause | 7fbe79fd5cb4dbbcc6b6b432ffc8364a | 33.523684 | 83 | 0.57512 | 3.204446 | false | false | false | false |
diofant/diofant | diofant/solvers/ode.py | 1 | 283430 | r"""
This module contains :py:meth:`~diofant.solvers.ode.dsolve` and different helper
functions that it uses.
:py:meth:`~diofant.solvers.ode.dsolve` solves ordinary differential equations.
See the docstring on the various functions for their uses. Note that partial
differential equations support is in ``pde.py``. Note that hint functions
have docstrings describing their various methods, but they are intended for
internal use. Use ``dsolve(ode, func, hint=hint)`` to solve an ODE using a
specific hint. See also the docstring on
:py:meth:`~diofant.solvers.ode.dsolve`.
**Functions in this module**
These are the user functions in this module:
- :py:meth:`~diofant.solvers.ode.dsolve` - Solves ODEs.
- :py:meth:`~diofant.solvers.ode.classify_ode` - Classifies ODEs into
possible hints for :py:meth:`~diofant.solvers.ode.dsolve`.
- :py:meth:`~diofant.solvers.ode.checkodesol` - Checks if an equation is the
solution to an ODE.
- :py:meth:`~diofant.solvers.ode.homogeneous_order` - Returns the
homogeneous order of an expression.
- :py:meth:`~diofant.solvers.ode.infinitesimals` - Returns the infinitesimals
of the Lie group of point transformations of an ODE, such that it is
invariant.
These are the non-solver helper functions that are for internal use. The
user should use the various options to
:py:meth:`~diofant.solvers.ode.dsolve` to obtain the functionality provided
by these functions:
- :py:meth:`~diofant.solvers.ode.odesimp` - Does all forms of ODE
simplification.
- :py:meth:`~diofant.solvers.ode.ode_sol_simplicity` - A key function for
comparing solutions by simplicity.
- :py:meth:`~diofant.solvers.ode.constantsimp` - Simplifies arbitrary
constants.
- :py:meth:`~diofant.solvers.ode.constant_renumber` - Renumber arbitrary
constants.
- :py:meth:`~diofant.solvers.ode._handle_Integral` - Evaluate unevaluated
Integrals.
See also the docstrings of these functions.
**Currently implemented solver methods**
The following methods are implemented for solving ordinary differential
equations. See the docstrings of the various hint functions for more
information on each (run ``help(ode)``):
- 1st order separable differential equations.
- 1st order differential equations whose coefficients or `dx` and `dy` are
functions homogeneous of the same order.
- 1st order exact differential equations.
- 1st order linear differential equations.
- 1st order Bernoulli differential equations.
- Power series solutions for first order differential equations.
- Lie Group method of solving first order differential equations.
- 2nd order Liouville differential equations.
- Power series solutions for second order differential equations
at ordinary and regular singular points.
- `n`\th order linear homogeneous differential equation with constant
coefficients.
- `n`\th order linear inhomogeneous differential equation with constant
coefficients using the method of undetermined coefficients.
- `n`\th order linear inhomogeneous differential equation with constant
coefficients using the method of variation of parameters.
**Philosophy behind this module**
This module is designed to make it easy to add new ODE solving methods without
having to mess with the solving code for other methods. The idea is that
there is a :py:meth:`~diofant.solvers.ode.classify_ode` function, which takes in
an ODE and tells you what hints, if any, will solve the ODE. It does this
without attempting to solve the ODE, so it is fast. Each solving method is a
hint, and it has its own function, named ``ode_<hint>``. That function takes
in the ODE and any match expression gathered by
:py:meth:`~diofant.solvers.ode.classify_ode` and returns a solved result. If
this result has any integrals in it, the hint function will return an
unevaluated :py:class:`~diofant.integrals.integrals.Integral` class.
:py:meth:`~diofant.solvers.ode.dsolve`, which is the user wrapper function
around all of this, will then call :py:meth:`~diofant.solvers.ode.odesimp` on
the result, which, among other things, will attempt to solve the equation for
the dependent variable (the function we are solving for), simplify the
arbitrary constants in the expression, and evaluate any integrals, if the hint
allows it.
**How to add new solution methods**
If you have an ODE that you want :py:meth:`~diofant.solvers.ode.dsolve` to be
able to solve, try to avoid adding special case code here. Instead, try
finding a general method that will solve your ODE, as well as others. This
way, the :py:mod:`~diofant.solvers.ode` module will become more robust, and
unhindered by special case hacks. WolphramAlpha and Maple's
DETools[odeadvisor] function are two resources you can use to classify a
specific ODE. It is also better for a method to work with an `n`\th order ODE
instead of only with specific orders, if possible.
To add a new method, there are a few things that you need to do. First, you
need a hint name for your method. Try to name your hint so that it is
unambiguous with all other methods, including ones that may not be implemented
yet. If your method uses integrals, also include a ``hint_Integral`` hint.
If there is more than one way to solve ODEs with your method, include a hint
for each one, as well as a ``<hint>_best`` hint. Your ``ode_<hint>_best()``
function should choose the best using min with ``ode_sol_simplicity`` as the
key argument. See
:py:meth:`~diofant.solvers.ode.ode_1st_homogeneous_coeff_best`, for example.
The function that uses your method will be called ``ode_<hint>()``, so the
hint must only use characters that are allowed in a Python function name
(alphanumeric characters and the underscore '``_``' character). Include a
function for every hint, except for ``_Integral`` hints
(:py:meth:`~diofant.solvers.ode.dsolve` takes care of those automatically).
Hint names should be all lowercase, unless a word is commonly capitalized
(such as Integral or Bernoulli). If you have a hint that you do not want to
run with ``all_Integral`` that doesn't have an ``_Integral`` counterpart (such
as a best hint that would defeat the purpose of ``all_Integral``), you will
need to remove it manually in the :py:meth:`~diofant.solvers.ode.dsolve` code.
See also the :py:meth:`~diofant.solvers.ode.classify_ode` docstring for
guidelines on writing a hint name.
Determine *in general* how the solutions returned by your method compare with
other methods that can potentially solve the same ODEs. Then, put your hints
in the :py:data:`~diofant.solvers.ode.allhints` tuple in the order that they
should be called. The ordering of this tuple determines which hints are
default. Note that exceptions are ok, because it is easy for the user to
choose individual hints with :py:meth:`~diofant.solvers.ode.dsolve`. In
general, ``_Integral`` variants should go at the end of the list, and
``_best`` variants should go before the various hints they apply to. For
example, the ``undetermined_coefficients`` hint comes before the
``variation_of_parameters`` hint because, even though variation of parameters
is more general than undetermined coefficients, undetermined coefficients
generally returns cleaner results for the ODEs that it can solve than
variation of parameters does, and it does not require integration, so it is
much faster.
Next, you need to have a match expression or a function that matches the type
of the ODE, which you should put in :py:meth:`~diofant.solvers.ode.classify_ode`
(if the match function is more than just a few lines, like
:py:meth:`~diofant.solvers.ode._undetermined_coefficients_match`, it should go
outside of :py:meth:`~diofant.solvers.ode.classify_ode`). It should match the
ODE without solving for it as much as possible, so that
:py:meth:`~diofant.solvers.ode.classify_ode` remains fast and is not hindered by
bugs in solving code. Be sure to consider corner cases. For example, if your
solution method involves dividing by something, make sure you exclude the case
where that division will be 0.
In most cases, the matching of the ODE will also give you the various parts
that you need to solve it. You should put that in a dictionary (``.match()``
will do this for you), and add that as ``matching_hints['hint'] = matchdict``
in the relevant part of :py:meth:`~diofant.solvers.ode.classify_ode`.
:py:meth:`~diofant.solvers.ode.classify_ode` will then send this to
:py:meth:`~diofant.solvers.ode.dsolve`, which will send it to your function as
the ``match`` argument. Your function should be named ``ode_<hint>(eq, func,
order, match)`. If you need to send more information, put it in the ``match``
dictionary. For example, if you had to substitute in a dummy variable in
:py:meth:`~diofant.solvers.ode.classify_ode` to match the ODE, you will need to
pass it to your function using the `match` dict to access it. You can access
the independent variable using ``func.args[0]``, and the dependent variable
(the function you are trying to solve for) as ``func.func``. If, while trying
to solve the ODE, you find that you cannot, raise ``NotImplementedError``.
:py:meth:`~diofant.solvers.ode.dsolve` will catch this error with the ``all``
meta-hint, rather than causing the whole routine to fail.
Add a docstring to your function that describes the method employed. Like
with anything else in Diofant, you will need to add a doctest to the docstring,
in addition to real tests in ``test_ode.py``. Try to maintain consistency
with the other hint functions' docstrings. Add your method to the list at the
top of this docstring. Also, add your method to ``ode.rst`` in the
``docs/src`` directory, so that the Sphinx docs will pull its docstring into
the main Diofant documentation. Be sure to make the Sphinx documentation by
running ``make html`` from within the docs directory to verify that the
docstring formats correctly.
If your solution method involves integrating, use :py:meth:`Integral()
<diofant.integrals.integrals.Integral>` instead of
:py:meth:`~diofant.integrals.integrals.integrate`. This allows the user to bypass
hard/slow integration by using the ``_Integral`` variant of your hint. In
most cases, calling :py:meth:`diofant.core.basic.Basic.doit` will integrate your
solution. If this is not the case, you will need to write special code in
:py:meth:`~diofant.solvers.ode._handle_Integral`. Arbitrary constants should be
symbols named ``C1``, ``C2``, and so on. All solution methods should return
an equality instance. If you need an arbitrary number of arbitrary constants,
you can use ``constants = numbered_symbols(prefix='C', cls=Symbol, start=1)``.
If it is possible to solve for the dependent function in a general way, do so.
Otherwise, do as best as you can, but do not call solve in your
``ode_<hint>()`` function. :py:meth:`~diofant.solvers.ode.odesimp` will attempt
to solve the solution for you, so you do not need to do that. Lastly, if your
ODE has a common simplification that can be applied to your solutions, you can
add a special case in :py:meth:`~diofant.solvers.ode.odesimp` for it. For
example, solutions returned from the ``1st_homogeneous_coeff`` hints often
have many :py:meth:`~diofant.functions.elementary.exponential.log` terms, so
:py:meth:`~diofant.solvers.ode.odesimp` calls
:py:meth:`~diofant.simplify.simplify.logcombine` on them (it also helps to write
the arbitrary constant as ``log(C1)`` instead of ``C1`` in this case). Also
consider common ways that you can rearrange your solution to have
:py:meth:`~diofant.solvers.ode.constantsimp` take better advantage of it. It is
better to put simplification in :py:meth:`~diofant.solvers.ode.odesimp` than in
your method, because it can then be turned off with the simplify flag in
:py:meth:`~diofant.solvers.ode.dsolve`. If you have any extraneous
simplification in your function, be sure to only run it using ``if
match.get('simplify', True):``, especially if it can be slow or if it can
reduce the domain of the solution.
Finally, as with every contribution to Diofant, your method will need to be
tested. Add a test for each method in ``test_ode.py``. Follow the
conventions there, i.e., test the solver using ``dsolve(eq, f(x),
hint=your_hint)``, and also test the solution using
:py:meth:`~diofant.solvers.ode.checkodesol` (you can put these in a separate
tests and skip/XFAIL if it runs too slow/doesn't work). Be sure to call your
hint specifically in :py:meth:`~diofant.solvers.ode.dsolve`, that way the test
won't be broken simply by the introduction of another matching hint. If your
method works for higher order (>1) ODEs, you will need to run ``sol =
constant_renumber(sol, 'C', 1, order)`` for each solution, where ``order`` is
the order of the ODE. This is because ``constant_renumber`` renumbers the
arbitrary constants by printing order, which is platform dependent. Try to
test every corner case of your solver, including a range of orders if it is a
`n`\th order solver, but if your solver is slow, such as if it involves hard
integration, try to keep the test run time down.
Feel free to refactor existing hints to avoid duplicating code or creating
inconsistencies. If you can show that your method exactly duplicates an
existing method, including in the simplicity and speed of obtaining the
solutions, then you can remove the old, less general method. The existing
code is tested extensively in ``test_ode.py``, so if anything is broken, one
of those tests will surely fail.
"""
from collections import defaultdict
from itertools import islice
from ..core import (Add, AtomicExpr, Derivative, Dummy, Eq, Equality, Expr,
Function, I, Integer, Mul, Number, Pow, Subs, Symbol,
Tuple, Wild, diff, expand, expand_mul, factor_terms, nan,
oo, symbols, zoo)
from ..core.compatibility import is_sequence, iterable
from ..core.function import AppliedUndef, _mexpand
from ..core.multidimensional import vectorize
from ..core.sympify import sympify
from ..functions import (conjugate, cos, exp, factorial, im, log, re, sin,
sqrt, tan)
from ..integrals import Integral, integrate
from ..logic.boolalg import BooleanAtom
from ..matrices import BlockDiagMatrix, Matrix, wronskian
from ..polys import Poly, PolynomialError, RootOf, lcm, terms_gcd
from ..polys.polyroots import roots_quartic
from ..polys.polytools import cancel, degree, div
from ..series.order import Order
from ..simplify.cse_main import cse
from ..simplify.powsimp import powsimp
from ..simplify.radsimp import collect, collect_const
from ..simplify.simplify import logcombine, posify, separatevars, simplify
from ..simplify.trigsimp import trigsimp
from ..utilities import default_sort_key, numbered_symbols, ordered, sift
from .deutils import _desolve, _preprocess, ode_order
from .pde import pdsolve
from .solvers import solve
#: This is a list of hints in the order that they should be preferred by
#: :py:meth:`~diofant.solvers.ode.classify_ode`. In general, hints earlier in the
#: list should produce simpler solutions than those later in the list (for
#: ODEs that fit both). For now, the order of this list is based on empirical
#: observations by the developers of Diofant.
#:
#: The hint used by :py:meth:`~diofant.solvers.ode.dsolve` for a specific ODE
#: can be overridden (see the docstring).
#:
#: In general, ``_Integral`` hints are grouped at the end of the list, unless
#: there is a method that returns an unevaluable integral most of the time
#: (which go near the end of the list anyway). ``default``, ``all``,
#: ``best``, and ``all_Integral`` meta-hints should not be included in this
#: list, but ``_best`` and ``_Integral`` hints should be included.
allhints = (
'separable',
'1st_exact',
'1st_linear',
'Bernoulli',
'Riccati_special_minus2',
'1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'almost_linear',
'linear_coefficients',
'separable_reduced',
'1st_power_series',
'lie_group',
'nth_linear_constant_coeff_homogeneous',
'nth_linear_euler_eq_homogeneous',
'nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters',
'Liouville',
'2nd_power_series_ordinary',
'2nd_power_series_regular',
'separable_Integral',
'1st_exact_Integral',
'1st_linear_Integral',
'Bernoulli_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral',
'almost_linear_Integral',
'linear_coefficients_Integral',
'separable_reduced_Integral',
'nth_linear_constant_coeff_variation_of_parameters_Integral',
'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral',
'Liouville_Integral',
)
lie_heuristics = (
'abaco1_simple',
'abaco1_product',
'abaco2_similar',
'abaco2_unique_unknown',
'linear',
'function_sum',
'bivariate',
'chi'
)
def sub_func_doit(eq, func, new):
r"""
When replacing the func with something else, we usually want the
derivative evaluated, so this function helps in making that happen.
To keep subs from having to look through all derivatives, we mask them off
with dummy variables, do the func sub, and then replace masked-off
derivatives with their doit values.
Examples
========
>>> sub_func_doit(3*f(x).diff(x) - 1, f(x), x)
2
>>> sub_func_doit(x*f(x).diff(x) - f(x)**2 + f(x), f(x), 1/(x*(z + 1/x)))
x*(-1/(x**2*(z + 1/x)) + 1/(x**3*(z + 1/x)**2)) + 1/(x*(z + 1/x))
...- 1/(x**2*(z + 1/x)**2)
"""
reps = {}
repu = {}
for d in eq.atoms(Derivative):
u = Dummy('u')
repu[u] = d.subs({func: new}).doit()
reps[d] = u
return eq.subs(reps).subs({func: new.doit()}).subs(repu)
def get_numbered_constants(eq, num=1, start=1, prefix='C'):
"""
Returns a list of constants that do not occur
in eq already.
"""
if isinstance(eq, Expr):
eq = [eq]
elif not iterable(eq):
raise ValueError(f'Expected Expr or iterable but got {eq}')
atom_set = set().union(*[i.free_symbols for i in eq])
functions_set = set().union(*[i.atoms(Function) for i in eq])
atom_set |= {Symbol(str(f.func)) for f in functions_set}
ncs = numbered_symbols(start=start, prefix=prefix, exclude=atom_set)
Cs = [next(ncs) for i in range(num)]
return Cs[0] if num == 1 else tuple(Cs)
def dsolve(eq, func=None, hint='default', simplify=True,
init=None, xi=None, eta=None, x0=0, n=6, **kwargs):
r"""
Solves any (supported) kind of ordinary differential equation and
system of ordinary differential equations.
**For single ordinary differential equation**
It is classified under this when number of equation in ``eq`` is one.
**Usage**
``dsolve(eq, f(x), hint)`` -> Solve ordinary differential equation
``eq`` for function ``f(x)``, using method ``hint``.
**Details**
``eq`` can be any supported ordinary differential equation (see the
:py:mod:`~diofant.solvers.ode` docstring for supported methods).
This can either be an :py:class:`~diofant.core.relational.Equality`,
or an expression, which is assumed to be equal to ``0``.
``f(x)`` is a function of one variable whose derivatives in that
variable make up the ordinary differential equation ``eq``. In
many cases it is not necessary to provide this; it will be
autodetected (and an error raised if it couldn't be detected).
``hint`` is the solving method that you want dsolve to use. Use
``classify_ode(eq, f(x))`` to get all of the possible hints for an
ODE. The default hint, ``default``, will use whatever hint is
returned first by :py:meth:`~diofant.solvers.ode.classify_ode`. See
Hints below for more options that you can use for hint.
``simplify`` enables simplification by
:py:meth:`~diofant.solvers.ode.odesimp`. See its docstring for more
information. Turn this off, for example, to disable solving of
solutions for ``func`` or simplification of arbitrary constants.
It will still integrate with this hint. Note that the solution may
contain more arbitrary constants than the order of the ODE with
this option enabled.
``xi`` and ``eta`` are the infinitesimal functions of an ordinary
differential equation. They are the infinitesimals of the Lie group
of point transformations for which the differential equation is
invariant. The user can specify values for the infinitesimals. If
nothing is specified, ``xi`` and ``eta`` are calculated using
:py:meth:`~diofant.solvers.ode.infinitesimals` with the help of various
heuristics.
``init`` is the set of initial/boundary conditions for the differential equation.
It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs({x: x2}):
x3}`` and so on. For power series solutions, if no initial
conditions are specified ``f(0)`` is assumed to be ``C0`` and the power
series solution is calculated about 0.
``x0`` is the point about which the power series solution of a differential
equation is to be evaluated.
``n`` gives the exponent of the dependent variable up to which the power series
solution of a differential equation is to be evaluated.
**Hints**
Aside from the various solving methods, there are also some meta-hints
that you can pass to :py:meth:`~diofant.solvers.ode.dsolve`:
``default``:
This uses whatever hint is returned first by
:py:meth:`~diofant.solvers.ode.classify_ode`. This is the
default argument to :py:meth:`~diofant.solvers.ode.dsolve`.
``all``:
To make :py:meth:`~diofant.solvers.ode.dsolve` apply all
relevant classification hints, use ``dsolve(ODE, func,
hint="all")``. This will return a dictionary of
``hint:solution`` terms. If a hint causes dsolve to raise the
``NotImplementedError``, value of that hint's key will be the
exception object raised. The dictionary will also include
some special keys:
- ``order``: The order of the ODE. See also
:py:meth:`~diofant.solvers.deutils.ode_order` in
``deutils.py``.
- ``best``: The simplest hint; what would be returned by
``best`` below.
- ``best_hint``: The hint that would produce the solution
given by ``best``. If more than one hint produces the best
solution, the first one in the tuple returned by
:py:meth:`~diofant.solvers.ode.classify_ode` is chosen.
- ``default``: The solution that would be returned by default.
This is the one produced by the hint that appears first in
the tuple returned by
:py:meth:`~diofant.solvers.ode.classify_ode`.
``all_Integral``:
This is the same as ``all``, except if a hint also has a
corresponding ``_Integral`` hint, it only returns the
``_Integral`` hint. This is useful if ``all`` causes
:py:meth:`~diofant.solvers.ode.dsolve` to hang because of a
difficult or impossible integral. This meta-hint will also be
much faster than ``all``, because
:py:meth:`~diofant.core.expr.Expr.integrate` is an expensive
routine.
``best``:
To have :py:meth:`~diofant.solvers.ode.dsolve` try all methods
and return the simplest one. This takes into account whether
the solution is solvable in the function, whether it contains
any Integral classes (i.e. unevaluatable integrals), and
which one is the shortest in size.
See also the :py:meth:`~diofant.solvers.ode.classify_ode` docstring for
more info on hints, and the :py:mod:`~diofant.solvers.ode` docstring for
a list of all supported hints.
**Tips**
- See ``test_ode.py`` for many tests, which serves also as a set of
examples for how to use :py:meth:`~diofant.solvers.ode.dsolve`.
- :py:meth:`~diofant.solvers.ode.dsolve` always returns an
:py:class:`~diofant.core.relational.Equality` class (except for the
case when the hint is ``all`` or ``all_Integral``). If possible, it
solves the solution explicitly for the function being solved for.
Otherwise, it returns an implicit solution.
- Arbitrary constants are symbols named ``C1``, ``C2``, and so on.
- Because all solutions should be mathematically equivalent, some
hints may return the exact same result for an ODE. Often, though,
two different hints will return the same solution formatted
differently. The two should be equivalent. Also note that sometimes
the values of the arbitrary constants in two different solutions may
not be the same, because one constant may have "absorbed" other
constants into it.
- Do ``help(ode.ode_<hintname>)`` to get help more information on a
specific hint, where ``<hintname>`` is the name of a hint without
``_Integral``.
**For system of ordinary differential equations**
**Usage**
``dsolve(eq, func)`` -> Solve a system of ordinary differential
equations ``eq`` for ``func`` being list of functions including
`x(t)`, `y(t)`, `z(t)` where number of functions in the list depends
upon the number of equations provided in ``eq``.
**Details**
``eq`` can be any supported system of ordinary differential equations
This can either be an :py:class:`~diofant.core.relational.Equality`,
or an expression, which is assumed to be equal to ``0``.
``func`` holds ``x(t)`` and ``y(t)`` being functions of one variable which
together with some of their derivatives make up the system of ordinary
differential equation ``eq``. It is not necessary to provide this; it
will be autodetected (and an error raised if it couldn't be detected).
**Hints**
The hints are formed by parameters returned by classify_sysode, combining
them give hints name used later for forming method name.
Examples
========
>>> dsolve(Derivative(f(x), x, x) + 9*f(x), f(x))
Eq(f(x), C1*sin(3*x) + C2*cos(3*x))
>>> eq = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x)
>>> dsolve(eq, hint='1st_exact')
[Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))]
>>> dsolve(eq, hint='almost_linear')
[Eq(f(x), -acos(C1/sqrt(-cos(x)**2)) + 2*pi), Eq(f(x), acos(C1/sqrt(-cos(x)**2)))]
>>> eq = (Eq(Derivative(f(t), t), 12*t*f(t) + 8*g(t)),
... Eq(Derivative(g(t), t), 21*f(t) + 7*t*g(t)))
>>> dsolve(eq)
[Eq(f(t), C1*x0(t) + C2*x0(t)*Integral(8*E**Integral(7*t, t)*E**Integral(12*t, t)/x0(t)**2, t)),
Eq(g(t), C1*y0(t) + C2*(E**Integral(7*t, t)*E**Integral(12*t, t)/x0(t) +
y0(t)*Integral(8*E**Integral(7*t, t)*E**Integral(12*t, t)/x0(t)**2, t)))]
>>> eq = (Eq(Derivative(f(t), t), f(t)*g(t)*sin(t)),
... Eq(Derivative(g(t), t), g(t)**2*sin(t)))
>>> dsolve(eq)
{Eq(f(t), -E**C1/(E**C1*C2 - cos(t))), Eq(g(t), -1/(C1 - cos(t)))}
"""
if iterable(eq):
match = classify_sysode(eq, func)
eq = match['eq']
order = match['order']
func = match['func']
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
# keep highest order term coefficient positive
for i, e in enumerate(eq):
if e.coeff(diff(func[i], (t, ode_order(e, func[i])))).is_negative:
eq[i] = -e
match['eq'] = eq
if len(set(order.values())) != 1:
raise ValueError('It solves only those systems of equations whose orders are equal')
match['order'] = list(order.values())[0]
if match['type_of_equation'] is None:
raise NotImplementedError
if match['is_linear']:
if match['type_of_equation'] == 'type1' and match['order'] == 1:
solvefunc = globals()[f"sysode_linear_neq_order{match['order']}"]
elif match['no_of_equation'] <= 3:
solvefunc = globals()[f"sysode_linear_{match['no_of_equation']}eq_order{match['order']}"]
else:
raise NotImplementedError
else:
solvefunc = globals()[f"sysode_nonlinear_{match['no_of_equation']}eq_order{match['order']}"]
sols = solvefunc(match)
if init:
constants = Tuple(*sols).free_symbols - Tuple(*eq).free_symbols
solved_constants = solve_init(sols, func, constants, init)
return [sol.subs(solved_constants) for sol in sols]
return sols
else:
given_hint = hint # hint given by the user
# See the docstring of _desolve for more details.
hints = _desolve(eq, func=func,
hint=hint, simplify=True, xi=xi, eta=eta, type='ode', init=init,
x0=x0, n=n, **kwargs)
eq = hints.pop('eq', eq)
all_ = hints.pop('all', False)
if all_:
retdict = {}
gethints = classify_ode(eq, dict=True)
orderedhints = gethints['ordered_hints']
for hint in hints:
rv = _helper_simplify(eq, hint, hints[hint], simplify)
retdict[hint] = rv
func = hints[hint]['func']
retdict['best'] = min(list(retdict.values()), key=lambda x:
ode_sol_simplicity(x, func, trysolving=not simplify))
if given_hint == 'best':
return retdict['best']
for i in orderedhints: # pragma: no branch
if retdict['best'] == retdict.get(i, None):
retdict['best_hint'] = i
break
retdict['default'] = gethints['default']
retdict['order'] = gethints['order']
return retdict
else:
# The key 'hint' stores the hint needed to be solved for.
hint = hints['hint']
return _helper_simplify(eq, hint, hints, simplify, init=init)
def _helper_simplify(eq, hint, match, simplify=True, init=None, **kwargs):
r"""
Helper function of dsolve that calls the respective
:py:mod:`~diofant.solvers.ode` functions to solve for the ordinary
differential equations. This minimises the computation in calling
:py:meth:`~diofant.solvers.deutils._desolve` multiple times.
"""
r = match
if hint.endswith('_Integral'):
solvefunc = globals()['ode_' + hint[:-len('_Integral')]]
else:
solvefunc = globals()['ode_' + hint]
func = r['func']
order = r['order']
match = r[hint]
free = eq.free_symbols
def cons(s):
return s.free_symbols.difference(free)
if simplify:
# odesimp() will attempt to integrate, if necessary, apply constantsimp(),
# attempt to solve for func, and apply any other hint specific
# simplifications
sols = solvefunc(eq, func, order, match)
if isinstance(sols, Expr):
rv = odesimp(sols, func, order, cons(sols), hint)
else:
rv = [odesimp(s, func, order, cons(s), hint) for s in sols]
else:
# We still want to integrate (you can disable it separately with the hint)
match['simplify'] = False # Some hints can take advantage of this option
rv = _handle_Integral(solvefunc(eq, func, order, match),
func, order, hint)
if init and 'power_series' not in hint:
if isinstance(rv, Expr):
solved_constants = solve_init([rv], [r['func']], cons(rv), init)
rv = rv.subs(solved_constants)
elif iterable(rv):
rv1 = []
for s in rv:
solved_constants = solve_init([s], [r['func']], cons(s), init)
rv1.append(s.subs(solved_constants))
rv = rv1
else:
raise NotImplementedError
return rv
def solve_init(sols, funcs, constants, init):
"""
Solve for the constants given initial conditions
``sols`` is a list of solutions.
``funcs`` is a list of functions.
``constants`` is a list of constants.
``init`` is the set of initial/boundary conditions for the differential
equation. It should be given in the form of ``{f(x0): x1,
f(x).diff(x).subs({x: x2}): x3}`` and so on.
Returns a dictionary mapping constants to values.
``solution.subs(constants)`` will replace the constants in ``solution``.
Example
=======
>>> C1 = symbols('C1')
>>> sols = [Eq(f(x), C1*exp(x))]
>>> funcs = [f(x)]
>>> constants = [C1]
>>> init = {f(0): 2}
>>> solved_constants = solve_init(sols, funcs, constants, init)
>>> solved_constants
{C1: 2}
>>> sols[0].subs(solved_constants)
Eq(f(x), 2*E**x)
"""
# Assume init are of the form f(x0): value or Subs(diff(f(x), x, n), (x,
# x0)): value (currently checked by classify_ode). To solve, replace x
# with x0, f(x0) with value, then solve for constants. For f^(n)(x0),
# differentiate the solution n times, so that f^(n)(x) appears.
x = funcs[0].args[0]
diff_sols = []
subs_sols = []
diff_variables = set()
init = {k.doit() if isinstance(k, Subs) else k: v
for k, v in init.items()}
for funcarg, value in init.items():
if isinstance(funcarg, AppliedUndef):
x0 = funcarg.args[0]
matching_func = [f for f in funcs if f.func == funcarg.func][0]
S = sols
elif isinstance(funcarg, (Subs, Derivative)):
if isinstance(funcarg, Subs):
deriv = funcarg.expr
x0 = funcarg.point[0]
variables = funcarg.expr.variables
matching_func = deriv
else:
deriv = funcarg
x0 = funcarg.variables[0]
variables = (x,)*len(funcarg.variables)
matching_func = deriv.subs({x0: x})
if variables not in diff_variables:
for sol in sols:
if sol.has(deriv.expr.func):
diff_sols.append(Eq(sol.lhs.diff(*variables), sol.rhs.diff(*variables)))
diff_variables.add(variables)
S = diff_sols
else:
raise NotImplementedError('Unrecognized initial condition')
for sol in S:
if sol.has(matching_func):
sol2 = sol
sol2 = sol2.subs({x: x0})
sol2 = sol2.subs({funcarg: value})
subs_sols.append(sol2)
try:
solved_constants = solve(subs_sols, constants)
except NotImplementedError:
solved_constants = []
# XXX: We can't differentiate between the solution not existing because of
# invalid initial conditions, and not existing because solve is not smart
# enough. For now, we use NotImplementedError in this case.
if not solved_constants:
raise NotImplementedError("Couldn't solve for initial conditions")
if len(solved_constants) > 1:
raise NotImplementedError('Initial conditions produced too many solutions for constants')
return solved_constants[0]
def classify_ode(eq, func=None, dict=False, init=None, **kwargs):
r"""
Returns a tuple of possible :py:meth:`~diofant.solvers.ode.dsolve`
classifications for an ODE.
The tuple is ordered so that first item is the classification that
:py:meth:`~diofant.solvers.ode.dsolve` uses to solve the ODE by default. In
general, classifications at the near the beginning of the list will
produce better solutions faster than those near the end, thought there are
always exceptions. To make :py:meth:`~diofant.solvers.ode.dsolve` use a
different classification, use ``dsolve(ODE, func,
hint=<classification>)``. See also the
:py:meth:`~diofant.solvers.ode.dsolve` docstring for different meta-hints
you can use.
If ``dict`` is true, :py:meth:`~diofant.solvers.ode.classify_ode` will
return a dictionary of ``hint:match`` expression terms. This is intended
for internal use by :py:meth:`~diofant.solvers.ode.dsolve`. Note that
because dictionaries are ordered arbitrarily, this will most likely not be
in the same order as the tuple.
You can get help on different hints by executing
``help(ode.ode_hintname)``, where ``hintname`` is the name of the hint
without ``_Integral``.
See :py:data:`~diofant.solvers.ode.allhints` or the
:py:mod:`~diofant.solvers.ode` docstring for a list of all supported hints
that can be returned from :py:meth:`~diofant.solvers.ode.classify_ode`.
Notes
=====
These are remarks on hint names.
``_Integral``
If a classification has ``_Integral`` at the end, it will return the
expression with an unevaluated :py:class:`~diofant.integrals.integrals.Integral`
class in it. Note that a hint may do this anyway if
:py:meth:`~diofant.integrals.integrals.integrate` cannot do the integral,
though just using an ``_Integral`` will do so much faster. Indeed, an
``_Integral`` hint will always be faster than its corresponding hint
without ``_Integral`` because
:py:meth:`~diofant.integrals.integrals.integrate` is an expensive routine.
If :py:meth:`~diofant.solvers.ode.dsolve` hangs, it is probably because
:py:meth:`~diofant.core.expr.Expr.integrate` is hanging on a tough or
impossible integral. Try using an ``_Integral`` hint or
``all_Integral`` to get it return something.
Note that some hints do not have ``_Integral`` counterparts. This is
because :py:meth:`~diofant.integrals.integrals.integrate` is not used in solving
the ODE for those method. For example, `n`\th order linear homogeneous
ODEs with constant coefficients do not require integration to solve,
so there is no ``nth_linear_homogeneous_constant_coeff_Integrate``
hint. You can easily evaluate any unevaluated
:py:class:`~diofant.integrals.integrals.Integral`\s in an expression by doing
``expr.doit()``.
Ordinals
Some hints contain an ordinal such as ``1st_linear``. This is to help
differentiate them from other hints, as well as from other methods
that may not be implemented yet. If a hint has ``nth`` in it, such as
the ``nth_linear`` hints, this means that the method used to applies
to ODEs of any order.
``indep`` and ``dep``
Some hints contain the words ``indep`` or ``dep``. These reference
the independent variable and the dependent function, respectively. For
example, if an ODE is in terms of `f(x)`, then ``indep`` will refer to
`x` and ``dep`` will refer to `f`.
``subs``
If a hints has the word ``subs`` in it, it means the the ODE is solved
by substituting the expression given after the word ``subs`` for a
single dummy variable. This is usually in terms of ``indep`` and
``dep`` as above. The substituted expression will be written only in
characters allowed for names of Python objects, meaning operators will
be spelled out. For example, ``indep``/``dep`` will be written as
``indep_div_dep``.
``coeff``
The word ``coeff`` in a hint refers to the coefficients of something
in the ODE, usually of the derivative terms. See the docstring for
the individual methods for more info (``help(ode)``). This is
contrast to ``coefficients``, as in ``undetermined_coefficients``,
which refers to the common name of a method.
``_best``
Methods that have more than one fundamental way to solve will have a
hint for each sub-method and a ``_best`` meta-classification. This
will evaluate all hints and return the best, using the same
considerations as the normal ``best`` meta-hint.
Examples
========
>>> classify_ode(Eq(f(x).diff(x), 0), f(x))
('separable', '1st_linear', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_homogeneous',
'separable_Integral', '1st_linear_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
>>> classify_ode(f(x).diff((x, 2)) + 3*f(x).diff(x) + 2*f(x) - 4)
('nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
"""
init = sympify(init)
prep = kwargs.pop('prep', True)
if func and len(func.args) != 1:
raise ValueError('dsolve() and classify_ode() only '
f'work with functions of one variable, not {func}')
if prep or func is None:
eq, func_ = _preprocess(eq, func)
if func is None:
func = func_
x = func.args[0]
f = func.func
y = Dummy('y')
xi = kwargs.get('xi')
eta = kwargs.get('eta')
terms = kwargs.get('n')
if isinstance(eq, Equality):
if eq.rhs != 0:
return classify_ode(eq.lhs - eq.rhs, func, init=init, xi=xi,
n=terms, eta=eta, prep=False)
eq = eq.lhs
order = ode_order(eq, f(x))
# hint:matchdict or hint:(tuple of matchdicts)
# Also will contain "default":<default hint> and "order":order items.
matching_hints = {'order': order}
if not order:
if dict:
matching_hints['default'] = None
return matching_hints
else:
return ()
df = f(x).diff(x)
a = Wild('a', exclude=[f(x)])
b = Wild('b', exclude=[f(x)])
c = Wild('c', exclude=[f(x)])
d = Wild('d', exclude=[df, f(x).diff((x, 2))])
e = Wild('e', exclude=[df])
k = Wild('k', exclude=[df])
n = Wild('n', exclude=[f(x)])
c1 = Wild('c1', exclude=[x])
a2 = Wild('a2', exclude=[x, f(x), df])
b2 = Wild('b2', exclude=[x, f(x), df])
c2 = Wild('c2', exclude=[x, f(x), df])
d2 = Wild('d2', exclude=[x, f(x), df])
a3 = Wild('a3', exclude=[f(x), df, f(x).diff((x, 2))])
b3 = Wild('b3', exclude=[f(x), df, f(x).diff((x, 2))])
c3 = Wild('c3', exclude=[f(x), df, f(x).diff((x, 2))])
r3 = {'xi': xi, 'eta': eta} # Used for the lie_group hint
boundary = {} # Used to extract initial conditions
C1 = Symbol('C1')
eq = expand(eq)
# Preprocessing to get the initial conditions out
if init is not None:
init = {k.doit() if isinstance(k, Subs) else k: v
for k, v in init.items()}
for funcarg in init:
# Separating derivatives
if isinstance(funcarg, (Subs, Derivative)):
# f(x).diff(x).subs({x: 0}) is a Subs, but
# f(x).diff(x).subs({x: y}) is a Derivative
if isinstance(funcarg, Subs):
deriv = funcarg.expr
old = funcarg.variables[0]
new = funcarg.point[0]
else:
deriv = funcarg
# No information on this. Just assume it was x
old = x
new = funcarg.variables[0]
if (isinstance(deriv, Derivative) and
isinstance(deriv.args[0], AppliedUndef) and
deriv.args[0].func == f and len(deriv.args[0].args) == 1 and
old == x and not new.has(x) and
all(i == deriv.variables[0] for i in deriv.variables) and
not init[funcarg].has(f)):
dorder = ode_order(deriv, x)
temp = 'f' + str(dorder)
boundary.update({temp: new, temp + 'val': init[funcarg]})
else:
raise ValueError('Enter valid boundary conditions for Derivatives')
# Separating functions
elif isinstance(funcarg, AppliedUndef):
if funcarg.func == f and len(funcarg.args) == 1 and not funcarg.args[0].has(x):
boundary.update({'f0': funcarg.args[0], 'f0val': init[funcarg]})
else:
raise ValueError('Enter valid boundary conditions for Function')
else:
raise ValueError('Enter boundary conditions of the form init={f(point}: value, f(x).diff(x, order).subs({x: point}): value}')
# Precondition to try remove f(x) from highest order derivative
reduced_eq = None
if eq.is_Add:
deriv_coef = eq.coeff(f(x).diff((x, order)))
if deriv_coef not in (1, 0):
r = deriv_coef.match(a*f(x)**c1)
if r and r[c1]:
den = f(x)**r[c1]
reduced_eq = Add(*[arg/den for arg in eq.args])
if not reduced_eq:
reduced_eq = eq
if order == 1:
# Linear case: a(x)*y'+b(x)*y+c(x) == 0
if eq.is_Add:
ind, dep = reduced_eq.as_independent(f)
else:
u = Dummy('u')
ind, dep = (reduced_eq + u).as_independent(f)
ind, dep = (tmp.subs({u: 0}) for tmp in [ind, dep])
r = {a: dep.coeff(df),
b: dep.coeff(f(x)),
c: ind}
# double check f[a] since the preconditioning may have failed
if not r[a].has(f) and not r[b].has(f) and (
r[a]*df + r[b]*f(x) + r[c]).expand() - reduced_eq == 0:
r['a'] = a
r['b'] = b
r['c'] = c
matching_hints['1st_linear'] = r
matching_hints['1st_linear_Integral'] = r
# Bernoulli case: a(x)*y'+b(x)*y+c(x)*y**n == 0
r = collect(
reduced_eq, f(x), exact=True).match(a*df + b*f(x) + c*f(x)**n)
if r and r[c] != 0 and r[n] != 1: # See issue sympy/sympy#4676
r['a'] = a
r['b'] = b
r['c'] = c
r['n'] = n
matching_hints['Bernoulli'] = r
matching_hints['Bernoulli_Integral'] = r
# Riccati special n == -2 case: a2*y'+b2*y**2+c2*y/x+d2/x**2 == 0
r = collect(reduced_eq,
f(x), exact=True).match(a2*df + b2*f(x)**2 + c2*f(x)/x + d2/x**2)
if r and r[b2] != 0 and (r[c2] != 0 or r[d2] != 0):
r['a2'] = a2
r['b2'] = b2
r['c2'] = c2
r['d2'] = d2
matching_hints['Riccati_special_minus2'] = r
# NON-REDUCED FORM OF EQUATION matches
r = collect(eq, df, exact=True).match(d + e * df)
if r:
r['d'] = d
r['e'] = e
r['y'] = y
r[d] = r[d].subs({f(x): y})
r[e] = r[e].subs({f(x): y})
# FIRST ORDER POWER SERIES WHICH NEEDS INITIAL CONDITIONS
# TODO: Hint first order series should match only if d/e is analytic.
# For now, only d/e and (d/e).diff(arg) is checked for existence at
# at a given point.
# This is currently done internally in ode_1st_power_series.
point = boundary.get('f0', 0)
value = boundary.get('f0val', C1)
check = cancel(r[d]/r[e])
check1 = check.subs({x: point, y: value})
check2 = (check1.diff(x)).subs({x: point, y: value})
if not check1.has(oo, zoo, nan) and not check2.has(oo, zoo, nan):
rseries = r.copy()
rseries.update({'terms': terms, 'f0': point, 'f0val': value})
matching_hints['1st_power_series'] = rseries
r3.update(r)
# Exact Differential Equation: P(x, y) + Q(x, y)*y' = 0 where
# dP/dy == dQ/dx
if r[d] != 0:
numerator = simplify(r[d].diff(y) - r[e].diff(x))
# The following few conditions try to convert a non-exact
# differential equation into an exact one.
# References : Differential equations with applications
# and historical notes - George E. Simmons
if numerator:
# If (dP/dy - dQ/dx) / Q = f(x)
# then exp(integral(f(x))*equation becomes exact
factor = simplify(numerator/r[e])
variables = factor.free_symbols
if len(variables) == 1 and x == variables.pop():
factor = exp(Integral(factor).doit())
r[d] *= factor
r[e] *= factor
matching_hints['1st_exact'] = r
matching_hints['1st_exact_Integral'] = r
else:
# If (dP/dy - dQ/dx) / -P = f(y)
# then exp(integral(f(y))*equation becomes exact
factor = simplify(-numerator/r[d])
variables = factor.free_symbols
if len(variables) == 1 and y == variables.pop():
factor = exp(Integral(factor).doit())
r[d] *= factor
r[e] *= factor
matching_hints['1st_exact'] = r
matching_hints['1st_exact_Integral'] = r
else:
matching_hints['1st_exact'] = r
matching_hints['1st_exact_Integral'] = r
# Any first order ODE can be ideally solved by the Lie Group
# method
matching_hints['lie_group'] = r3
# This match is used for several cases below; we now collect on
# f(x) so the matching works.
r = collect(reduced_eq, df, exact=True).match(d + e*df)
if r:
# Using r[d] and r[e] without any modification for hints
# linear-coefficients and separable-reduced.
num, den = r[d], r[e] # ODE = d/e + df
r['d'] = d
r['e'] = e
r['y'] = y
r[d] = num.subs({f(x): y})
r[e] = den.subs({f(x): y})
# Separable Case: y' == P(y)*Q(x)
r[d] = separatevars(r[d])
r[e] = separatevars(r[e])
# m1[coeff]*m1[x]*m1[y] + m2[coeff]*m2[x]*m2[y]*y'
m1 = separatevars(r[d], dict=True, symbols=(x, y))
m2 = separatevars(r[e], dict=True, symbols=(x, y))
if m1 and m2:
r1 = {'m1': m1, 'm2': m2, 'y': y}
matching_hints['separable'] = r1
matching_hints['separable_Integral'] = r1
# First order equation with homogeneous coefficients:
# dy/dx == F(y/x) or dy/dx == F(x/y)
ordera = homogeneous_order(r[d], x, y)
if ordera is not None:
orderb = homogeneous_order(r[e], x, y)
if ordera == orderb:
# u1=y/x and u2=x/y
u1 = Dummy('u1')
u2 = Dummy('u2')
s = '1st_homogeneous_coeff_subs'
s1 = s + '_dep_div_indep'
s2 = s + '_indep_div_dep'
if simplify((r[d] + u1*r[e]).subs({x: 1, y: u1})) != 0:
matching_hints[s1] = r
matching_hints[s1 + '_Integral'] = r
if simplify((r[e] + u2*r[d]).subs({x: u2, y: 1})) != 0:
matching_hints[s2] = r
matching_hints[s2 + '_Integral'] = r
if s1 in matching_hints and s2 in matching_hints:
matching_hints['1st_homogeneous_coeff_best'] = r
# Linear coefficients of the form
# y'+ F((a*x + b*y + c)/(a'*x + b'y + c')) = 0
# that can be reduced to homogeneous form.
F = num/den
params = _linear_coeff_match(F, func)
if params:
xarg, yarg = params
u = Dummy('u')
t = Dummy('t')
# Dummy substitution for df and f(x).
dummy_eq = reduced_eq.subs(((df, t), (f(x), u)))
reps = ((x, x + xarg), (u, u + yarg), (t, df), (u, f(x)))
dummy_eq = simplify(dummy_eq.subs(reps))
# get the re-cast values for e and d
r2 = collect(expand(dummy_eq), [df, f(x)], exact=True).match(e*df + d)
# Match arguments are passed in such a way that it
# is coherent with the already existing homogeneous
# functions.
r2[d] = r2[d].subs({f(x): y})
r2[e] = r2[e].subs({f(x): y})
r2.update({'xarg': xarg, 'yarg': yarg, 'd': d, 'e': e, 'y': y})
matching_hints['linear_coefficients'] = r2
matching_hints['linear_coefficients_Integral'] = r2
# Equation of the form y' + (y/x)*H(x^n*y) = 0
# that can be reduced to separable form
factor = simplify(x/f(x)*num/den)
# Try representing factor in terms of x^n*y
# where n is lowest power of x in factor;
# first remove terms like sqrt(2)*3 from factor.atoms(Mul)
u = None
for mul in ordered(factor.atoms(Mul)):
if mul.has(x):
_, u = mul.as_independent(x, f(x))
break
if u and u.has(f(x)):
h = x**(degree(Poly(u.subs({f(x): y}), gen=x)))*f(x)
p = Wild('p')
if (u/h == 1) or ((u/h).simplify().match(x**p)):
t = Dummy('t')
r2 = {'t': t}
xpart, _ = u.as_independent(f(x))
test = factor.subs({u: t, 1/u: 1/t})
free = test.free_symbols
if len(free) == 1 and free.pop() == t:
r2.update({'power': xpart.as_base_exp()[1], 'u': test})
matching_hints['separable_reduced'] = r2
matching_hints['separable_reduced_Integral'] = r2
# Almost-linear equation of the form f(x)*g(y)*y' + k(x)*l(y) + m(x) = 0
r = collect(eq, [df, f(x)]).match(e*df + d)
if r:
r2 = r.copy()
r2[c] = Integer(0)
if r2[d].is_Add:
# Separate the terms having f(x) to r[d] and
# remaining to r[c]
no_f, r2[d] = r2[d].as_independent(f(x))
r2[c] += no_f
factor = simplify(r2[d].diff(f(x))/r[e])
if factor and not factor.has(f(x)):
r2[d] = factor_terms(r2[d])
u = r2[d].as_independent(f(x), as_Add=False)[1]
r2.update({'a': e, 'b': d, 'c': c, 'u': u})
r2[d] /= u
r2[e] /= u.diff(f(x))
matching_hints['almost_linear'] = r2
matching_hints['almost_linear_Integral'] = r2
elif order == 2:
# Liouville ODE in the form
# f(x).diff((x, 2)) + g(f(x))*(f(x).diff(x))**2 + h(x)*f(x).diff(x)
# See Goldstein and Braun, "Advanced Methods for the Solution of
# Differential Equations", pg. 98
s = d*f(x).diff((x, 2)) + e*df**2 + k*df
r = reduced_eq.match(s)
if r and r[d] != 0:
y = Dummy('y')
g = simplify(r[e]/r[d]).subs({f(x): y})
h = simplify(r[k]/r[d])
if h.has(f(x)) or g.has(x):
pass
else:
r = {'g': g, 'h': h, 'y': y}
matching_hints['Liouville'] = r
matching_hints['Liouville_Integral'] = r
# Homogeneous second order differential equation of the form
# a3*f(x).diff((x, 2)) + b3*f(x).diff(x) + c3, where
# for simplicity, a3, b3 and c3 are assumed to be polynomials.
# It has a definite power series solution at point x0 if, b3/a3 and c3/a3
# are analytic at x0.
deq = a3*(f(x).diff((x, 2))) + b3*df + c3*f(x)
r = collect(reduced_eq,
[f(x).diff((x, 2)), f(x).diff(x), f(x)]).match(deq)
ordinary = False
if r and r[a3] != 0:
if all(r[key].is_polynomial() for key in r):
p = cancel(r[b3]/r[a3]) # Used below
q = cancel(r[c3]/r[a3]) # Used below
point = kwargs.get('x0', 0)
check = p.subs({x: point})
if not check.has(oo, zoo, nan):
check = q.subs({x: point})
if not check.has(oo, zoo, nan):
ordinary = True
r.update({'a3': a3, 'b3': b3, 'c3': c3, 'x0': point, 'terms': terms})
matching_hints['2nd_power_series_ordinary'] = r
# Checking if the differential equation has a regular singular point
# at x0. It has a regular singular point at x0, if (b3/a3)*(x - x0)
# and (c3/a3)*((x - x0)**2) are analytic at x0.
if not ordinary:
p = cancel((x - point)*p)
check = p.subs({x: point})
if not check.has(oo, zoo, nan):
q = cancel(((x - point)**2)*q)
check = q.subs({x: point})
if not check.has(oo, zoo, nan):
coeff_dict = {'p': p, 'q': q, 'x0': point, 'terms': terms}
matching_hints['2nd_power_series_regular'] = coeff_dict
# nth order linear ODE
# a_n(x)y^(n) + ... + a_1(x)y' + a_0(x)y = F(x) = b
r = _nth_linear_match(reduced_eq, func, order)
# Constant coefficient case (a_i is constant for all i)
if r and not any(r[i].has(x) for i in r if i >= 0):
# Inhomogeneous case: F(x) is not identically 0
if r[-1]:
undetcoeff = _undetermined_coefficients_match(r[-1], x)
s = 'nth_linear_constant_coeff_variation_of_parameters'
matching_hints[s] = r
matching_hints[s + '_Integral'] = r
if undetcoeff['test']:
r['trialset'] = undetcoeff['trialset']
matching_hints['nth_linear_constant_coeff_undetermined_coefficients'] = r
# Homogeneous case: F(x) is identically 0
else:
matching_hints['nth_linear_constant_coeff_homogeneous'] = r
# nth order Euler equation a_n*x**n*y^(n) + ... + a_1*x*y' + a_0*y = F(x)
# In case of Homogeneous euler equation F(x) = 0
def _test_term(coeff, order):
r"""
Linear Euler ODEs have the form K*x**order*diff(y(x),x,order) = F(x),
where K is independent of x and y(x), order>= 0.
So we need to check that for each term, coeff == K*x**order from
some K. We have a few cases, since coeff may have several
different types.
"""
if coeff == 0:
return True
if order == 0:
if x in coeff.free_symbols:
return False
return True
if coeff.is_Mul:
return x**order in coeff.args
elif coeff.is_Pow:
return coeff.as_base_exp() == (x, order)
elif order == 1:
return x == coeff
return False
if r and not any(not _test_term(r[i], i) for i in r if i >= 0):
if not r[-1]:
matching_hints['nth_linear_euler_eq_homogeneous'] = r
else:
matching_hints['nth_linear_euler_eq_nonhomogeneous_variation_of_parameters'] = r
matching_hints['nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral'] = r
e, re = posify(r[-1].subs({x: exp(x)}))
undetcoeff = _undetermined_coefficients_match(e.subs(re), x)
if undetcoeff['test']:
r['trialset'] = undetcoeff['trialset']
matching_hints['nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients'] = r
# Order keys based on allhints.
retlist = [i for i in allhints if i in matching_hints]
if dict:
# Dictionaries are ordered arbitrarily, so make note of which
# hint would come first for dsolve(). Use an ordered dict in Py 3.
matching_hints['default'] = retlist[0] if retlist else None
matching_hints['ordered_hints'] = tuple(retlist)
return matching_hints
else:
return tuple(retlist)
def classify_sysode(eq, funcs=None, **kwargs):
r"""
Returns a dictionary of parameter names and values that define the system
of ordinary differential equations in ``eq``.
The parameters are further used in
:py:meth:`~diofant.solvers.ode.dsolve` for solving that system.
The parameter names and values are:
'is_linear' (boolean), which tells whether the given system is linear.
Note that "linear" here refers to the operator: terms such as ``x*diff(x,t)`` are
nonlinear, whereas terms like ``sin(t)*diff(x,t)`` are still linear operators.
'func' (list) contains the :py:class:`~diofant.core.function.Function`s that
appear with a derivative in the ODE, i.e. those that we are trying to solve
the ODE for.
'order' (dict) with the maximum derivative for each element of the 'func'
parameter.
'func_coeff' (dict) with the coefficient for each triple ``(equation number,
function, order)``. The coefficients are those subexpressions that do not
appear in 'func', and hence can be considered constant for purposes of ODE
solving.
'eq' (list) with the equations from ``eq``, sympified and transformed into
expressions (we are solving for these expressions to be zero).
'no_of_equations' (int) is the number of equations (same as ``len(eq)``).
'type_of_equation' (string) is an internal classification of the type of
ODE.
References
==========
* http://eqworld.ipmnet.ru/en/solutions/sysode/sode-toc1.htm
* :cite:`polyanin2006handbook`
Examples
========
>>> eq = (Eq(5*f(t).diff(t), 12*f(t) - 6*g(t)),
... Eq(2*g(t).diff(t), 11*f(t) + 3*g(t)))
>>> classify_sysode(eq)
{'eq': [-12*f(t) + 6*g(t) + 5*Derivative(f(t), t), -11*f(t) - 3*g(t) + 2*Derivative(g(t), t)], 'func': [f(t), g(t)], 'func_coeff': {(0, f(t), 0): -12, (0, f(t), 1): 5, (0, g(t), 0): 6, (0, g(t), 1): 0, (1, f(t), 0): -11, (1, f(t), 1): 0, (1, g(t), 0): -3, (1, g(t), 1): 2}, 'is_linear': True, 'no_of_equation': 2, 'order': {f(t): 1, g(t): 1}, 'type_of_equation': 'type1'}
>>> eq = (Eq(diff(f(t), t), 5*t*f(t) + t**2*g(t)),
... Eq(diff(g(t), t), -t**2*f(t) + 5*t*g(t)))
>>> classify_sysode(eq)
{'eq': [-t**2*g(t) - 5*t*f(t) + Derivative(f(t), t), t**2*f(t) - 5*t*g(t) + Derivative(g(t), t)], 'func': [f(t), g(t)], 'func_coeff': {(0, f(t), 0): -5*t, (0, f(t), 1): 1, (0, g(t), 0): -t**2, (0, g(t), 1): 0, (1, f(t), 0): t**2, (1, f(t), 1): 0, (1, g(t), 0): -5*t, (1, g(t), 1): 1}, 'is_linear': True, 'no_of_equation': 2, 'order': {f(t): 1, g(t): 1}, 'type_of_equation': 'type4'}
"""
# Sympify equations and convert iterables of equations into
# a list of equations
def _sympify(eq):
return list(map(sympify, eq if iterable(eq) else [eq]))
eq, funcs = (_sympify(w) for w in [eq, funcs])
for i, fi in enumerate(eq):
if isinstance(fi, Equality):
eq[i] = fi.lhs - fi.rhs
matching_hints = {'no_of_equation': i + 1}
matching_hints['eq'] = eq
if i == 0:
raise ValueError('classify_sysode() works for systems of ODEs. '
'For scalar ODEs, classify_ode should be used')
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
# find all the functions if not given
order = {}
if funcs == [None]:
funcs = []
for eqs in eq:
derivs = eqs.atoms(Derivative)
func = set().union(*[d.atoms(AppliedUndef) for d in derivs])
for func_ in func:
order[func_] = 0
funcs.append(func_)
else:
for func_ in funcs:
order[func_] = 0
funcs = list(ordered(set(funcs)))
if len(funcs) < len(eq):
raise ValueError(f'Number of functions given is less than number of equations {funcs}')
for func in funcs:
max_order = order[func]
for eq_ in eq:
order_ = ode_order(eq_, func)
max_order = max(max_order, order_)
order[func] = max_order
matching_hints['func'] = funcs
for func in funcs:
if func and len(func.args) != 1:
raise ValueError('dsolve() and classify_sysode() work with '
f'functions of one variable only, not {func}')
# find the order of all equation in system of odes
matching_hints['order'] = order
# find coefficients of terms f(t), diff(f(t),t) and higher derivatives
# and similarly for other functions g(t), diff(g(t),t) in all equations.
# Here j denotes the equation number, funcs[l] denotes the function about
# which we are talking about and k denotes the order of function funcs[l]
# whose coefficient we are calculating.
def linearity_check(eqs, j, func, is_linear_):
for k in range(order[func]+1):
func_coef[j, func, k] = collect(eqs.expand(), [diff(func, (t, k))]).coeff(diff(func, (t, k)))
if is_linear_:
if func_coef[j, func, k] == 0:
if k == 0:
coef = eqs.as_independent(func)[1]
for xr in range(1, ode_order(eqs, func)+1):
coef -= eqs.as_independent(diff(func, (t, xr)))[1]
if coef != 0:
is_linear_ = False
else:
if eqs.as_independent(diff(func, (t, k)))[1]:
is_linear_ = False
else:
for func_ in funcs:
dep = func_coef[j, func, k].as_independent(func_)[1]
if dep not in (1, 0):
is_linear_ = False
return is_linear_
func_coef = {}
is_linear = True
for j, eqs in enumerate(eq):
for func in funcs:
is_linear = linearity_check(eqs, j, func, is_linear)
matching_hints['func_coeff'] = func_coef
matching_hints['is_linear'] = is_linear
type_of_equation = None
if len(set(order.values())) == 1:
order_eq = list(matching_hints['order'].values())[0]
if matching_hints['is_linear']:
if order_eq == 1:
type_of_equation = check_linear_neq_order1(eq, funcs, func_coef)
if type_of_equation is None:
if matching_hints['no_of_equation'] == 2:
if order_eq == 1:
type_of_equation = check_linear_2eq_order1(eq, funcs, func_coef)
elif order_eq == 2:
type_of_equation = check_linear_2eq_order2(eq, funcs, func_coef)
elif matching_hints['no_of_equation'] == 3:
if order_eq == 1:
type_of_equation = check_linear_3eq_order1(eq, funcs, func_coef)
else:
if order_eq == 1:
if matching_hints['no_of_equation'] == 2:
type_of_equation = check_nonlinear_2eq_order1(eq, funcs, func_coef)
elif matching_hints['no_of_equation'] == 3:
type_of_equation = check_nonlinear_3eq_order1(eq, funcs, func_coef)
matching_hints['type_of_equation'] = type_of_equation
return matching_hints
def check_linear_2eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = {}
# for equations Eq(a1*diff(x(t),t), b1*x(t) + c1*y(t) + d1)
# and Eq(a2*diff(y(t),t), b2*x(t) + c2*y(t) + d2)
r['a1'] = fc[0, x(t), 1]
r['a2'] = fc[1, y(t), 1]
r['b1'] = -fc[0, x(t), 0]/fc[0, x(t), 1]
r['b2'] = -fc[1, x(t), 0]/fc[1, y(t), 1]
r['c1'] = -fc[0, y(t), 0]/fc[0, x(t), 1]
r['c2'] = -fc[1, y(t), 0]/fc[1, y(t), 1]
forcing = [Integer(0), Integer(0)]
for i in range(2):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t)):
forcing[i] += j
r['d1'] = forcing[0]
r['d2'] = forcing[1]
if r['d1'] != 0 or r['d2'] != 0:
return
# Conditions to check for type 6 whose equations are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and
# Eq(diff(y(t),t), a*[f(t) + a*h(t)]x(t) + a*[g(t) - h(t)]*y(t))
p = 0
q = 0
p1 = cancel(r['b2']/(cancel(r['b2']/r['c2']).as_numer_denom()[0]))
p2 = cancel(r['b1']/(cancel(r['b1']/r['c1']).as_numer_denom()[0]))
for n, i in enumerate([p1, p2]):
for j in Mul.make_args(collect_const(i)):
if not j.has(t):
q = j
if q and n == 0:
if cancel((r['b2']/j - r['b1'])/(r['c1'] - r['c2']/j)) == j:
p = 1
elif q and n == 1:
if cancel((r['b1']/j - r['b2'])/(r['c2'] - r['c1']/j)) == j:
p = 2
# End of condition for type 6
r['b1'] = r['b1']/r['a1']
r['b2'] = r['b2']/r['a2']
r['c1'] = r['c1']/r['a1']
r['c2'] = r['c2']/r['a2']
if (r['b1'] == r['c2']) and (r['c1'] == r['b2']):
# Equation for type 3 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), g(t)*x(t) + f(t)*y(t))
return 'type3'
elif (r['b1'] == r['c2']) and (r['c1'] == -r['b2']):
# Equation for type 4 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), -g(t)*x(t) + f(t)*y(t))
return 'type4'
elif ((not cancel(r['b2']/r['c1']).has(t) and not cancel((r['c2']-r['b1'])/r['c1']).has(t))
or (not cancel(r['b1']/r['c2']).has(t) and not cancel((r['c1']-r['b2'])/r['c2']).has(t))):
# Equations for type 5 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), a*g(t)*x(t) + [f(t) + b*g(t)]*y(t)
return 'type5'
elif p:
return 'type6'
else:
# Equations for type 7 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), h(t)*x(t) + p(t)*y(t))
return 'type7'
def check_linear_2eq_order2(eq, func, func_coef):
x = func[0].func
y = func[1].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = {}
a = Wild('a', exclude=[1/t])
b = Wild('b', exclude=[1/t**2])
u = Wild('u', exclude=[t, t**2])
v = Wild('v', exclude=[t, t**2])
w = Wild('w', exclude=[t, t**2])
p = Wild('p', exclude=[t, t**2])
r['a1'] = fc[0, x(t), 2]
r['a2'] = fc[1, y(t), 2]
r['b1'] = fc[0, x(t), 1]
r['b2'] = fc[1, x(t), 1]
r['c1'] = fc[0, y(t), 1]
r['c2'] = fc[1, y(t), 1]
r['d1'] = fc[0, x(t), 0]
r['d2'] = fc[1, x(t), 0]
r['e1'] = fc[0, y(t), 0]
r['e2'] = fc[1, y(t), 0]
const = [Integer(0), Integer(0)]
for i in range(2):
for j in Add.make_args(eq[i]):
if not (j.has(x(t)) or j.has(y(t))):
const[i] += j
r['f1'] = const[0]
r['f2'] = const[1]
if r['f1'] != 0 or r['f2'] != 0:
if all(not r[k].has(t) for k in 'a1 a2 d1 d2 e1 e2 f1 f2'.split()) \
and r['b1'] == r['c1'] == r['b2'] == r['c2'] == 0:
return 'type2'
elif all(not r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2 d1 d2 e1 e1'.split()):
p = [Integer(0), Integer(0)]
q = [Integer(0), Integer(0)]
for n, e in enumerate([r['f1'], r['f2']]):
if e.has(t):
tpart = e.as_independent(t, Mul)[1]
for i in Mul.make_args(tpart):
if i.is_Exp:
b, e = i.as_base_exp()
co = e.coeff(t)
if co and not co.has(t) and co.has(I):
p[n] = 1
else:
q[n] = 1
else:
q[n] = 1
else:
q[n] = 1
if p[0] == 1 and p[1] == 1 and q[0] == 0 and q[1] == 0:
return 'type4'
else:
if r['b1'] == r['b2'] == r['c1'] == r['c2'] == 0 and all(not r[k].has(t)
for k in 'a1 a2 d1 d2 e1 e2'.split()):
return 'type1'
elif r['b1'] == r['e1'] == r['c2'] == r['d2'] == 0 and all(not r[k].has(t)
for k in 'a1 a2 b2 c1 d1 e2'.split()) and r['c1'] == -r['b2'] and \
r['d1'] == r['e2']:
return 'type3'
elif cancel(-r['b2']/r['d2']) == t and cancel(-r['c1']/r['e1']) == t and not \
(r['d2']/r['a2']).has(t) and not (r['e1']/r['a1']).has(t) and \
r['b1'] == r['d1'] == r['c2'] == r['e2'] == 0:
return 'type5'
elif ((r['a1']/r['d1']).expand()).match((p*(u*t**2+v*t+w)**2).expand()) and not \
(cancel(r['a1']*r['d2']/(r['a2']*r['d1']))).has(t) and not (r['d1']/r['e1']).has(t) and not \
(r['d2']/r['e2']).has(t) and r['b1'] == r['b2'] == r['c1'] == r['c2'] == 0:
return 'type10'
elif not cancel(r['d1']/r['e1']).has(t) and not cancel(r['d2']/r['e2']).has(t) and not \
cancel(r['d1']*r['a2']/(r['d2']*r['a1'])).has(t) and r['b1'] == r['b2'] == r['c1'] == r['c2'] == 0:
return 'type6'
elif not cancel(r['b1']/r['c1']).has(t) and not cancel(r['b2']/r['c2']).has(t) and not \
cancel(r['b1']*r['a2']/(r['b2']*r['a1'])).has(t) and r['d1'] == r['d2'] == r['e1'] == r['e2'] == 0:
return 'type7'
elif cancel(-r['b2']/r['d2']) == t and cancel(-r['c1']/r['e1']) == t and not \
cancel(r['e1']*r['a2']/(r['d2']*r['a1'])).has(t) and r['e1'].has(t) \
and r['b1'] == r['d1'] == r['c2'] == r['e2'] == 0:
return 'type8'
elif (r['b1']/r['a1']).match(a/t) and (r['b2']/r['a2']).match(a/t) and not \
(r['b1']/r['c1']).has(t) and not (r['b2']/r['c2']).has(t) and \
(r['d1']/r['a1']).match(b/t**2) and (r['d2']/r['a2']).match(b/t**2) \
and not (r['d1']/r['e1']).has(t) and not (r['d2']/r['e2']).has(t):
return 'type9'
elif -r['b1']/r['d1'] == -r['c1']/r['e1'] == -r['b2']/r['d2'] == -r['c2']/r['e2'] == t:
return 'type11'
else:
raise NotImplementedError
def check_linear_3eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
z = func[2].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = {}
r['a1'] = fc[0, x(t), 1]
r['a2'] = fc[1, y(t), 1]
r['a3'] = fc[2, z(t), 1]
r['b1'] = fc[0, x(t), 0]
r['b2'] = fc[1, x(t), 0]
r['b3'] = fc[2, x(t), 0]
r['c1'] = fc[0, y(t), 0]
r['c2'] = fc[1, y(t), 0]
r['c3'] = fc[2, y(t), 0]
r['d1'] = fc[0, z(t), 0]
r['d2'] = fc[1, z(t), 0]
r['d3'] = fc[2, z(t), 0]
forcing = [Integer(0), Integer(0), Integer(0)]
for i in range(3):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t), z(t)):
forcing[i] += j
if any(forcing):
raise NotImplementedError
for k1 in 'c1 d1 b2 d2 b3 c3'.split():
if (all(not cancel(r[k1]/r[k]).has(t)
for k in 'd1 b2 d2 b3 c3'.split() if r[k] != 0) and
all(not cancel(r[k1]/(r['b1'] - r[k])).has(t)
for k in 'b1 c2 d3'.split() if r['b1'] != r[k])):
return 'type4'
def check_linear_neq_order1(eq, func, func_coef):
n = len(eq)
fc = func_coef
t = func[0].args[0]
M = Matrix(n, n, lambda i, j: +fc[i, func[j], 1])
L = Matrix(n, n, lambda i, j: -fc[i, func[j], 0])
if M.has(t) or L.has(t):
return
r = {'M': M, 'L': L}
try:
r['Minv'] = M.inv()
except ValueError: # pragma: no cover
return
r['forcing'] = [Integer(0)]*n
for i in range(n):
for j in Add.make_args(eq[i]):
if not j.has(*func):
r['forcing'][i] += j
return 'type1'
def check_nonlinear_2eq_order1(eq, func, func_coef):
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
u, v = symbols('u, v', cls=Dummy)
x = func[0].func
y = func[1].func
fc = func_coef
n = Wild('n', exclude=[x(t), y(t)])
f1 = Wild('f1', exclude=[v, t])
f2 = Wild('f2', exclude=[v, t])
g1 = Wild('g1', exclude=[u, t])
g2 = Wild('g2', exclude=[u, t])
f, g = Wild('f'), Wild('g')
r1 = eq[0].match(t*diff(x(t), t) - x(t) + f)
r2 = eq[1].match(t*diff(y(t), t) - y(t) + g)
if not (r1 and r2):
r1 = eq[0].match(diff(x(t), t) - x(t)/t + f/t)
r2 = eq[1].match(diff(y(t), t) - y(t)/t + g/t)
if not (r1 and r2):
r1 = (-eq[0]).match(t*diff(x(t), t) - x(t) + f)
r2 = (-eq[1]).match(t*diff(y(t), t) - y(t) + g)
if not (r1 and r2):
r1 = eq[0].match(diff(x(t), t) - x(t)/t + f/t)
r2 = eq[1].match(diff(y(t), t) - y(t)/t + g/t)
if r1 and r2 and not (r1[f].subs({diff(x(t), t): u, diff(y(t), t): v}).has(t)
or r2[g].subs({diff(x(t), t): u, diff(y(t), t): v}).has(t)):
return 'type5'
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i, func[i], 1]
eq[i] = eqs
r = eq[0].match(diff(x(t), t) - x(t)**n*f)
if r:
g = (diff(y(t), t) - eq[1])/r[f]
if r and not (g.has(x(t)) or g.subs({y(t): v}).has(t) or r[f].subs({x(t): u, y(t): v}).has(t)):
return 'type1'
r = eq[0].match(diff(x(t), t) - exp(n*x(t))*f)
if r:
g = (diff(y(t), t) - eq[1])/r[f]
if r and not (g.has(x(t)) or g.subs({y(t): v}).has(t) or r[f].subs({x(t): u, y(t): v}).has(t)):
return 'type2'
g = Wild('g')
r1 = eq[0].match(diff(x(t), t) - f)
r2 = eq[1].match(diff(y(t), t) - g)
if r1 and r2 and not (r1[f].subs({x(t): u, y(t): v}).has(t) or
r2[g].subs({x(t): u, y(t): v}).has(t)):
return 'type3'
r1 = eq[0].match(diff(x(t), t) - f)
r2 = eq[1].match(diff(y(t), t) - g)
if not (r1 and r2):
return
num, den = ((r1[f].subs({x(t): u, y(t): v})) /
(r2[g].subs({x(t): u, y(t): v}))).as_numer_denom()
R1 = num.match(f1*g1)
R2 = den.match(f2*g2)
if R1 and R2:
return 'type4'
def check_nonlinear_3eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
z = func[2].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
u, v, w = symbols('u, v, w', cls=Dummy)
a = Wild('a', exclude=[x(t), y(t), z(t), t])
b = Wild('b', exclude=[x(t), y(t), z(t), t])
c = Wild('c', exclude=[x(t), y(t), z(t), t])
f = Wild('f')
for i in range(3):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i, func[i], 1]
eq[i] = eqs
r1 = eq[0].match(diff(x(t), t) - a*y(t)*z(t))
r2 = eq[1].match(diff(y(t), t) - b*z(t)*x(t))
r3 = eq[2].match(diff(z(t), t) - c*x(t)*y(t))
if r1 and r2 and r3:
num1, den1 = r1[a].as_numer_denom()
num2, den2 = r2[b].as_numer_denom()
num3, den3 = r3[c].as_numer_denom()
if solve([num1*u - den1*(v - w), num2*v - den2*(w - u),
num3*w - den3*(u - v)], [u, v]):
return 'type1'
r = eq[0].match(diff(x(t), t) - y(t)*z(t)*f)
if r:
r1 = collect_const(r[f]).match(a*f)
r2 = ((diff(y(t), t) - eq[1])/r1[f]).match(b*z(t)*x(t))
r3 = ((diff(z(t), t) - eq[2])/r1[f]).match(c*x(t)*y(t))
if r1 and r2 and r3:
num1, den1 = r1[a].as_numer_denom()
num2, den2 = r2[b].as_numer_denom()
num3, den3 = r3[c].as_numer_denom()
if solve([num1*u - den1*(v - w), num2*v - den2*(w - u),
num3*w - den3*(u - v)], [u, v]):
return 'type2'
def checksysodesol(eqs, sols, func=None):
r"""
Substitutes corresponding ``sols`` for each functions into each ``eqs`` and
checks that the result of substitutions for each equation is ``0``. The
equations and solutions passed can be any iterable.
This only works when each ``sols`` have one function only, like `x(t)` or `y(t)`.
For each function, ``sols`` can have a single solution or a list of solutions.
In most cases it will not be necessary to explicitly identify the function,
but if the function cannot be inferred from the original equation it
can be supplied through the ``func`` argument.
When a sequence of equations is passed, the same sequence is used to return
the result for each equation with each function substitued with corresponding
solutions.
It tries the following method to find zero equivalence for each equation:
Substitute the solutions for functions, like `x(t)` and `y(t)` into the
original equations containing those functions.
This function returns a tuple. The first item in the tuple is ``True`` if
the substitution results for each equation is ``0``, and ``False`` otherwise.
The second item in the tuple is what the substitution results in. Each element
of the list should always be ``0`` corresponding to each equation if the
first item is ``True``. Note that sometimes this function may return ``False``,
but with an expression that is identically equal to ``0``, instead of returning
``True``. This is because :py:meth:`~diofant.simplify.simplify.simplify` cannot
reduce the expression to ``0``. If an expression returned by each function
vanishes identically, then ``sols`` really is a solution to ``eqs``.
If this function seems to hang, it is probably because of a difficult simplification.
Examples
========
>>> C1, C2 = symbols('C1:3')
>>> eq = (Eq(diff(f(t), t), f(t) + g(t) + 17),
... Eq(diff(g(t), t), -2*f(t) + g(t) + 12))
>>> sol = [Eq(f(t), (C1*sin(sqrt(2)*t) +
... C2*cos(sqrt(2)*t))*exp(t) - Rational(5, 3)),
... Eq(g(t), (sqrt(2)*C1*cos(sqrt(2)*t) -
... sqrt(2)*C2*sin(sqrt(2)*t))*exp(t) - Rational(46, 3))]
>>> checksysodesol(eq, sol)
(True, [0, 0])
>>> eq = (Eq(diff(f(t), t), f(t)*g(t)**4), Eq(diff(g(t), t), g(t)**3))
>>> sol = [Eq(f(t), C1*exp(-1/(4*(C2 + t)))),
... Eq(g(t), -sqrt(2)*sqrt(-1/(C2 + t))/2),
... Eq(f(t), C1*exp(-1/(4*(C2 + t)))),
... Eq(g(t), sqrt(2)*sqrt(-1/(C2 + t))/2)]
>>> checksysodesol(eq, sol)
(True, [0, 0])
"""
def _sympify(eq):
return list(map(sympify, eq if iterable(eq) else [eq]))
eqs = _sympify(eqs)
for i, e in enumerate(eqs):
if isinstance(e, Equality):
eqs[i] = e.lhs - e.rhs
if func is None:
funcs = []
for eq in eqs:
derivs = eq.atoms(Derivative)
func = set().union(*[d.atoms(AppliedUndef) for d in derivs])
for func_ in func:
funcs.append(func_)
funcs = list(set(funcs))
else:
funcs = list(func)
if not all(isinstance(func, AppliedUndef) and len(func.args) == 1 for func in funcs)\
and len({func.args for func in funcs}) != 1:
raise ValueError(f'func must be a function of one variable, not {func!s}')
for sol in sols:
if len(sol.atoms(AppliedUndef)) != 1:
raise ValueError('solutions should have one function only')
if len(funcs) != len({sol.lhs for sol in sols}):
raise ValueError('number of solutions provided does not match the number of equations')
dictsol = {}
for sol in sols:
func = list(sol.atoms(AppliedUndef))[0]
if sol.rhs == func:
sol = sol.reversed
dictsol[func] = sol.rhs
checkeq = []
for eq in eqs:
for func in funcs:
eq = sub_func_doit(eq, func, dictsol[func])
ss = simplify(eq)
checkeq.append(ss)
if len(set(checkeq)) == 1 and list(set(checkeq))[0] == 0:
return True, checkeq
else:
return False, checkeq
@vectorize(0)
def odesimp(eq, func, order, constants, hint):
r"""
Simplifies ODEs, including trying to solve for ``func`` and running
:py:meth:`~diofant.solvers.ode.constantsimp`.
It may use knowledge of the type of solution that the hint returns to
apply additional simplifications.
It also attempts to integrate any :py:class:`~diofant.integrals.integrals.Integral`\s
in the expression, if the hint is not an ``_Integral`` hint.
This function should have no effect on expressions returned by
:py:meth:`~diofant.solvers.ode.dsolve`, as
:py:meth:`~diofant.solvers.ode.dsolve` already calls
:py:meth:`~diofant.solvers.ode.odesimp`, but the individual hint functions
do not call :py:meth:`~diofant.solvers.ode.odesimp` (because the
:py:meth:`~diofant.solvers.ode.dsolve` wrapper does). Therefore, this
function is designed for mainly internal use.
Examples
========
>>> C1 = symbols('C1')
>>> eq = dsolve(x*f(x).diff(x) - f(x) - x*sin(f(x)/x), f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral',
... simplify=False)
>>> pprint(eq, wrap_line=False, use_unicode=False)
x
----
f(x)
/
|
| / 1 \
| -|u2 + -------|
| | /1 \|
| | sin|--||
| \ \u2//
log(f(x)) = log(C1) + | ---------------- d(u2)
| 2
| u2
|
/
>>> pprint(odesimp(eq, f(x), 1, {C1},
... hint='1st_homogeneous_coeff_subs_indep_div_dep'),
... use_unicode=False)
f(x) = 2*x*atan(C1*x)
"""
x = func.args[0]
f = func.func
# First, integrate if the hint allows it.
eq = _handle_Integral(eq, func, order, hint)
if hint.startswith('nth_linear_euler_eq_nonhomogeneous'):
eq = simplify(eq)
if not isinstance(eq, Equality):
raise TypeError('eq should be an instance of Equality')
# Second, clean up the arbitrary constants.
# Right now, nth linear hints can put as many as 2*order constants in an
# expression. If that number grows with another hint, the third argument
# here should be raised accordingly, or constantsimp() rewritten to handle
# an arbitrary number of constants.
eq = constantsimp(eq, constants)
# Lastly, now that we have cleaned up the expression, try solving for func.
# When RootOf is implemented in solve(), we will want to return a RootOf
# everytime instead of an Equality.
# make sure we are working with lists of solutions in simplified form.
if eq.lhs == func and not eq.rhs.has(func):
# The solution is already solved
eq = [eq]
# special simplification of the rhs
if hint.startswith('nth_linear_constant_coeff'):
# Collect terms to make the solution look nice.
# This is also necessary for constantsimp to remove unnecessary
# terms from the particular solution from variation of parameters
#
# Collect is not behaving reliably here. The results for
# some linear constant-coefficient equations with repeated
# roots do not properly simplify all constants sometimes.
# 'collectterms' gives different orders sometimes, and results
# differ in collect based on that order. The
# sort-reverse trick fixes things, but may fail in the
# future. In addition, collect is splitting exponentials with
# rational powers for no reason. We have to do a match
# to fix this using Wilds.
global collectterms
collectterms.sort(key=default_sort_key)
collectterms.reverse()
assert len(eq) == 1 and eq[0].lhs == f(x)
sol = eq[0].rhs
sol = expand_mul(sol)
for i, reroot, imroot in collectterms:
sol = collect(sol, x**i*exp(reroot*x)*sin(abs(imroot)*x))
sol = collect(sol, x**i*exp(reroot*x)*cos(imroot*x))
for i, reroot, imroot in collectterms:
sol = collect(sol, x**i*exp(reroot*x))
del collectterms
# Collect is splitting exponentials with rational powers for
# no reason. We call powsimp to fix.
sol = powsimp(sol)
eq[0] = Eq(f(x), sol)
else:
# The solution is not solved, so try to solve it
try:
floats = any(i.is_Float for i in eq.atoms(Number))
eqsol = solve(eq, func, rational=not floats)
if not eqsol:
raise NotImplementedError
except (NotImplementedError, PolynomialError):
eq = [eq]
else:
def _expand(expr):
_, denom = expr.as_numer_denom()
if denom.is_Add:
return expr
else:
return powsimp(expr.expand(), combine='exp', deep=True)
# XXX: the rest of odesimp() expects each ``t`` to be in a
# specific normal form: rational expression with numerator
# expanded, but with combined exponential functions (at
# least in this setup all tests pass).
eq = [Eq(f(x), _expand(t[func])) for t in eqsol]
# special simplification of the lhs.
if hint.startswith('1st_homogeneous_coeff'):
for j, eqi in enumerate(eq):
eq[j] = logcombine(eqi, force=True)
# We cleaned up the constants before solving to help the solve engine with
# a simpler expression, but the solved expression could have introduced
# things like -C1, so rerun constantsimp() one last time before returning.
for i, eqi in enumerate(eq):
eq[i] = constantsimp(eqi, constants)
eq[i] = constant_renumber(eq[i], 'C', 1, 2*order)
# If there is only 1 solution, return it;
# otherwise return the list of solutions.
if len(eq) == 1:
eq = eq[0]
return eq
def checkodesol(ode, sol, func=None, order='auto', solve_for_func=True):
r"""
Substitutes ``sol`` into ``ode`` and checks that the result is ``0``.
This only works when ``func`` is one function, like `f(x)`. ``sol`` can
be a single solution or a list of solutions. Each solution may be an
:py:class:`~diofant.core.relational.Equality` that the solution satisfies,
e.g. ``Eq(f(x), C1), Eq(f(x) + C1, 0)``; or simply an
:py:class:`~diofant.core.expr.Expr`, e.g. ``f(x) - C1``. In most cases it
will not be necessary to explicitly identify the function, but if the
function cannot be inferred from the original equation it can be supplied
through the ``func`` argument.
If a sequence of solutions is passed, the same sort of container will be
used to return the result for each solution.
It tries the following methods, in order, until it finds zero equivalence:
1. Substitute the solution for `f` in the original equation. This only
works if ``ode`` is solved for `f`. It will attempt to solve it first
unless ``solve_for_func == False``.
2. Take `n` derivatives of the solution, where `n` is the order of
``ode``, and check to see if that is equal to the solution. This only
works on exact ODEs.
3. Take the 1st, 2nd, ..., `n`\th derivatives of the solution, each time
solving for the derivative of `f` of that order (this will always be
possible because `f` is a linear operator). Then back substitute each
derivative into ``ode`` in reverse order.
This function returns a tuple. The first item in the tuple is ``True`` if
the substitution results in ``0``, and ``False`` otherwise. The second
item in the tuple is what the substitution results in. It should always
be ``0`` if the first item is ``True``. Note that sometimes this function
will ``False``, but with an expression that is identically equal to ``0``,
instead of returning ``True``. This is because
:py:meth:`~diofant.simplify.simplify.simplify` cannot reduce the expression
to ``0``. If an expression returned by this function vanishes
identically, then ``sol`` really is a solution to ``ode``.
If this function seems to hang, it is probably because of a hard
simplification.
To use this function to test, test the first item of the tuple.
Examples
========
>>> C1 = symbols('C1')
>>> checkodesol(f(x).diff(x), Eq(f(x), C1))
(True, 0)
>>> checkodesol(f(x).diff(x), C1)
(True, 0)
>>> checkodesol(f(x).diff(x), x)
(False, 1)
>>> checkodesol(f(x).diff((x, 2)), x**2)
(False, 2)
"""
if not isinstance(ode, Equality):
ode = Eq(ode, 0)
if func is None:
_, func = _preprocess(ode.lhs)
if not isinstance(func, AppliedUndef) or len(func.args) != 1:
raise ValueError(
f'func must be a function of one variable, not {func}')
if is_sequence(sol, set):
return type(sol)([checkodesol(ode, i, order=order, solve_for_func=solve_for_func) for i in sol])
if not isinstance(sol, Equality):
sol = Eq(func, sol)
elif sol.rhs == func:
sol = sol.reversed
if order == 'auto':
order = ode_order(ode, func)
solved = sol.lhs == func and not sol.rhs.has(func)
if solve_for_func and not solved:
rhs = solve(sol, func)
if rhs and not any(isinstance(_[func], RootOf) for _ in rhs):
eqs = [Eq(func, t[func]) for t in rhs]
if len(rhs) == 1:
eqs = eqs[0]
return checkodesol(ode, eqs, order=order, solve_for_func=False)
s = True
testnum = 0
x = func.args[0]
while s:
if testnum == 0:
# First pass, try substituting a solved solution directly into the
# ODE. This has the highest chance of succeeding.
ode_diff = ode.lhs - ode.rhs
if sol.lhs == func:
s = sub_func_doit(ode_diff, func, sol.rhs)
else:
testnum += 1
continue
ss = simplify(s)
if ss:
# with the new numer_denom in power.py, if we do a simple
# expansion then testnum == 0 verifies all solutions.
s = s.expand(force=True).simplify()
else:
s = 0
testnum += 1
elif testnum == 1:
# Second pass. If we cannot substitute f, try seeing if the nth
# derivative is equal, this will only work for odes that are exact,
# by definition.
s = simplify(
trigsimp(diff(sol.lhs, (x, order)) - diff(sol.rhs, (x, order))) -
trigsimp(ode.lhs) + trigsimp(ode.rhs))
# s2 = simplify(
# diff(sol.lhs, x, order) - diff(sol.rhs, x, order) - \
# ode.lhs + ode.rhs)
testnum += 1
elif testnum == 2:
# Third pass. Try solving for df/dx and substituting that into the
# ODE. Thanks to Chris Smith for suggesting this method. Many of
# the comments below are his, too.
# The method:
# - Take each of 1..n derivatives of the solution.
# - Solve each nth derivative for d^(n)f/dx^(n)
# (the differential of that order)
# - Back substitute into the ODE in decreasing order
# (i.e., n, n-1, ...)
# - Check the result for zero equivalence
if sol.lhs == func and not sol.rhs.has(func):
diffsols = {0: sol.rhs}
else:
diffsols = {}
sol = sol.lhs - sol.rhs
for i in range(1, order + 1):
# Differentiation is a linear operator, so there should always
# be 1 solution. Nonetheless, we test just to make sure.
# We only need to solve once. After that, we automatically
# have the solution to the differential in the order we want.
if i == 1:
ds = sol.diff(x)
try:
sdf = solve(ds, func.diff((x, i)))
if not sdf:
raise NotImplementedError
except NotImplementedError:
testnum += 1
break
else:
diffsols[i] = sdf[0][func.diff((x, i))]
else:
# This is what the solution says df/dx should be.
diffsols[i] = diffsols[i - 1].diff(x)
# Make sure the above didn't fail.
if testnum > 2:
continue
# Substitute it into ODE to check for self consistency.
lhs, rhs = ode.lhs, ode.rhs
for i in range(order, -1, -1):
if i == 0 and 0 not in diffsols:
# We can only substitute f(x) if the solution was
# solved for f(x).
break
lhs = sub_func_doit(lhs, func.diff((x, i)), diffsols[i])
rhs = sub_func_doit(rhs, func.diff((x, i)), diffsols[i])
ode_or_bool = Eq(lhs, rhs)
ode_or_bool = simplify(ode_or_bool)
if isinstance(ode_or_bool, (bool, BooleanAtom)):
if ode_or_bool:
lhs = rhs = Integer(0)
else:
lhs = ode_or_bool.lhs
rhs = ode_or_bool.rhs
# No sense in overworking simplify -- just prove that the
# numerator goes to zero
num = trigsimp((lhs - rhs).as_numer_denom()[0])
# since solutions are obtained using force=True we test
# using the same level of assumptions
# replace function with dummy so assumptions will work
_func = Dummy('func')
num = num.subs({func: _func})
# posify the expression
num, reps = posify(num)
s = simplify(num).xreplace(reps).xreplace({_func: func})
testnum += 1
else:
break
if not s:
return True, s
elif s is True: # The code above never was able to change s
raise NotImplementedError('Unable to test if ' + str(sol) +
' is a solution to ' + str(ode) + '.')
else:
return False, s
def ode_sol_simplicity(sol, func, trysolving=True):
r"""
Returns an extended integer representing how simple a solution to an ODE
is.
The following things are considered, in order from most simple to least:
- ``sol`` is solved for ``func``.
- ``sol`` is not solved for ``func``, but can be if passed to solve (e.g.,
a solution returned by ``dsolve(ode, func, simplify=False``).
- If ``sol`` is not solved for ``func``, then base the result on the
length of ``sol``, as computed by ``len(str(sol))``.
- If ``sol`` has any unevaluated :py:class:`~diofant.integrals.integrals.Integral`\s,
this will automatically be considered less simple than any of the above.
This function returns an integer such that if solution A is simpler than
solution B by above metric, then ``ode_sol_simplicity(sola, func) <
ode_sol_simplicity(solb, func)``.
Currently, the following are the numbers returned, but if the heuristic is
ever improved, this may change. Only the ordering is guaranteed.
+--------------------------------------------------+-------------------+
| Simplicity | Return |
+==================================================+===================+
| ``sol`` solved for ``func`` | ``-2`` |
+--------------------------------------------------+-------------------+
| ``sol`` not solved for ``func`` but can be | ``-1`` |
+--------------------------------------------------+-------------------+
| ``sol`` is not solved nor solvable for | ``len(str(sol))`` |
| ``func`` | |
+--------------------------------------------------+-------------------+
| ``sol`` contains an | ``oo`` |
| :py:class:`~diofant.integrals.integrals.Integral`| |
+--------------------------------------------------+-------------------+
``oo`` here means the Diofant infinity, which should compare greater than
any integer.
If you already know :py:meth:`~diofant.solvers.solvers.solve` cannot solve
``sol``, you can use ``trysolving=False`` to skip that step, which is the
only potentially slow step. For example,
:py:meth:`~diofant.solvers.ode.dsolve` with the ``simplify=False`` flag
should do this.
If ``sol`` is a list of solutions, if the worst solution in the list
returns ``oo`` it returns that, otherwise it returns ``len(str(sol))``,
that is, the length of the string representation of the whole list.
Examples
========
This function is designed to be passed to ``min`` as the key argument,
such as ``min(listofsolutions, key=lambda i: ode_sol_simplicity(i,
f(x)))``.
>>> C1, C2 = symbols('C1, C2')
>>> ode_sol_simplicity(Eq(f(x), C1*x**2), f(x))
-2
>>> ode_sol_simplicity(Eq(x**2 + f(x), C1), f(x))
-1
>>> ode_sol_simplicity(Eq(f(x), C1*Integral(2*x, x)), f(x))
oo
>>> eq1 = Eq(f(x)/tan(f(x)/(2*x)), C1)
>>> eq2 = Eq(f(x)/tan(f(x)/(2*x) + f(x)), C2)
>>> [ode_sol_simplicity(eq, f(x)) for eq in [eq1, eq2]]
[28, 35]
>>> min([eq1, eq2], key=lambda i: ode_sol_simplicity(i, f(x)))
Eq(f(x)/tan(f(x)/(2*x)), C1)
"""
# TODO: if two solutions are solved for f(x), we still want to be
# able to get the simpler of the two
# See the docstring for the coercion rules. We check easier (faster)
# things here first, to save time.
if iterable(sol):
# See if there are Integrals
for i in sol:
if ode_sol_simplicity(i, func, trysolving=trysolving) == oo:
return oo
return len(str(sol))
if sol.has(Integral):
return oo
# Next, try to solve for func. This code will change slightly when RootOf
# is implemented in solve(). Probably a RootOf solution should fall
# somewhere between a normal solution and an unsolvable expression.
# First, see if they are already solved
if sol.lhs == func and not sol.rhs.has(func) or \
sol.rhs == func and not sol.lhs.has(func):
return -2
# We are not so lucky, try solving manually
if trysolving:
try:
sols = solve(sol, func)
if not sols:
raise NotImplementedError
except NotImplementedError:
pass
else:
return -1
# Finally, a naive computation based on the length of the string version
# of the expression. This may favor combined fractions because they
# will not have duplicate denominators, and may slightly favor expressions
# with fewer additions and subtractions, as those are separated by spaces
# by the printer.
# Additional ideas for simplicity heuristics are welcome, like maybe
# checking if a equation has a larger domain, or if constantsimp has
# introduced arbitrary constants numbered higher than the order of a
# given ODE that sol is a solution of.
return len(str(sol))
def _get_constant_subexpressions(expr, Cs):
Cs = set(Cs)
Ces = []
def _recursive_walk(expr):
expr_syms = expr.free_symbols
if len(expr_syms) > 0 and expr_syms.issubset(Cs):
Ces.append(expr)
else:
if expr.is_Exp:
expr = expr.expand(mul=True)
if expr.func in (Add, Mul):
d = sift(expr.args, lambda i: i.free_symbols.issubset(Cs))
if len(d[True]) > 1:
x = expr.func(*d[True])
if not x.is_number:
Ces.append(x)
elif isinstance(expr, Integral):
if expr.free_symbols.issubset(Cs) and \
all(len(x) == 3 for x in expr.limits):
Ces.append(expr)
for i in expr.args:
_recursive_walk(i)
_recursive_walk(expr)
return Ces
def __remove_linear_redundancies(expr, Cs):
cnts = {i: expr.count(i) for i in Cs}
Cs = [i for i in Cs if cnts[i] > 0]
def _linear(expr):
if isinstance(expr, Add):
xs = [i for i in Cs if expr.count(i) == cnts[i]
and 0 == expr.diff((i, 2))]
d = {}
for x in xs:
y = expr.diff(x)
if y not in d:
d[y] = []
d[y].append(x)
for y in d.values():
if len(y) > 1:
y.sort(key=str)
for x in y[1:]:
expr = expr.subs({x: 0})
return expr
def _recursive_walk(expr):
if len(expr.args) != 0:
expr = expr.func(*[_recursive_walk(i) for i in expr.args])
expr = _linear(expr)
return expr
if isinstance(expr, Equality):
lhs, rhs = map(_recursive_walk, expr.args)
def f(i):
return isinstance(i, Number) or i in Cs
if isinstance(lhs, Symbol) and lhs in Cs:
rhs, lhs = lhs, rhs
if lhs.func in (Add, Symbol) and rhs.func in (Add, Symbol):
dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f)
drhs = sift([rhs] if isinstance(rhs, AtomicExpr) else rhs.args, f)
for i in [True, False]:
for hs in [dlhs, drhs]:
if i not in hs:
hs[i] = [0]
# this calculation can be simplified
lhs = Add(*dlhs[False]) - Add(*drhs[False])
rhs = Add(*drhs[True]) - Add(*dlhs[True])
elif lhs.func in (Mul, Symbol) and rhs.func in (Mul, Symbol):
dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f)
if True in dlhs:
lhs = Mul(*dlhs[False])
rhs = rhs/Mul(*dlhs[True])
return Eq(lhs, rhs)
else:
return _recursive_walk(expr)
@vectorize(0)
def constantsimp(expr, constants):
r"""
Simplifies an expression with arbitrary constants in it.
This function is written specifically to work with
:py:meth:`~diofant.solvers.ode.dsolve`, and is not intended for general use.
Simplification is done by "absorbing" the arbitrary constants into other
arbitrary constants, numbers, and symbols that they are not independent
of.
The symbols must all have the same name with numbers after it, for
example, ``C1``, ``C2``, ``C3``. The ``symbolname`` here would be
'``C``', the ``startnumber`` would be 1, and the ``endnumber`` would be 3.
If the arbitrary constants are independent of the variable ``x``, then the
independent symbol would be ``x``. There is no need to specify the
dependent function, such as ``f(x)``, because it already has the
independent symbol, ``x``, in it.
Because terms are "absorbed" into arbitrary constants and because
constants are renumbered after simplifying, the arbitrary constants in
expr are not necessarily equal to the ones of the same name in the
returned result.
If two or more arbitrary constants are added, multiplied, or raised to the
power of each other, they are first absorbed together into a single
arbitrary constant. Then the new constant is combined into other terms if
necessary.
Absorption of constants is done with limited assistance:
1. terms of :py:class:`~diofant.core.add.Add`\s are collected to try join
constants so `e^x (C_1 \cos(x) + C_2 \cos(x))` will simplify to `e^x
C_1 \cos(x)`;
2. powers with exponents that are :py:class:`~diofant.core.add.Add`\s are
expanded so `e^{C_1 + x}` will be simplified to `C_1 e^x`.
Use :py:meth:`~diofant.solvers.ode.constant_renumber` to renumber constants
after simplification or else arbitrary numbers on constants may appear,
e.g. `C_1 + C_3 x`.
In rare cases, a single constant can be "simplified" into two constants.
Every differential equation solution should have as many arbitrary
constants as the order of the differential equation. The result here will
be technically correct, but it may, for example, have `C_1` and `C_2` in
an expression, when `C_1` is actually equal to `C_2`. Use your discretion
in such situations, and also take advantage of the ability to use hints in
:py:meth:`~diofant.solvers.ode.dsolve`.
Examples
========
>>> C1, C2, C3 = symbols('C1, C2, C3')
>>> constantsimp(2*C1*x, {C1, C2, C3})
C1*x
>>> constantsimp(C1 + 2 + x, {C1, C2, C3})
C1 + x
>>> constantsimp(C1*C2 + 2 + C2 + C3*x, {C1, C2, C3})
C1 + C3*x
"""
# This function works recursively. The idea is that, for Mul,
# Add, Pow, and Function, if the class has a constant in it, then
# we can simplify it, which we do by recursing down and
# simplifying up. Otherwise, we can skip that part of the
# expression.
Cs = constants
orig_expr = expr
constant_subexprs = _get_constant_subexpressions(expr, Cs)
for xe in constant_subexprs:
xes = list(xe.free_symbols)
if not xes:
continue
if all(expr.count(c) == xe.count(c) for c in xes):
xes.sort(key=str)
expr = expr.subs({xe: xes[0]})
# try to perform common sub-expression elimination of constant terms
try:
commons, rexpr = cse(expr)
commons.reverse()
rexpr = rexpr[0]
for s in commons:
cs = list(s[1].atoms(Symbol))
if len(cs) == 1 and cs[0] in Cs:
rexpr = rexpr.subs({s[0]: cs[0]})
else:
rexpr = rexpr.subs([s])
expr = rexpr
except PolynomialError:
pass
expr = __remove_linear_redundancies(expr, Cs)
def _conditional_term_factoring(expr):
new_expr = terms_gcd(expr, clear=False, deep=True, expand=False)
# we do not want to factor exponentials, so handle this separately
if new_expr.is_Mul:
infac = False
asfac = False
for m in new_expr.args:
if m.is_Exp:
asfac = True
elif m.is_Add:
infac = any(fi.is_Exp for t in m.args
for fi in Mul.make_args(t))
if asfac and infac:
new_expr = expr
break
return new_expr
expr = _conditional_term_factoring(expr)
# call recursively if more simplification is possible
if orig_expr != expr:
return constantsimp(expr, Cs)
return expr
def constant_renumber(expr, symbolname, startnumber, endnumber):
r"""
Renumber arbitrary constants in ``expr`` to have numbers 1 through `N`
where `N` is ``endnumber - startnumber + 1`` at most.
In the process, this reorders expression terms in a standard way.
This is a simple function that goes through and renumbers any
:py:class:`~diofant.core.symbol.Symbol` with a name in the form ``symbolname
+ num`` where ``num`` is in the range from ``startnumber`` to
``endnumber``.
Symbols are renumbered based on ``.sort_key()``, so they should be
numbered roughly in the order that they appear in the final, printed
expression. Note that this ordering is based in part on hashes, so it can
produce different results on different machines.
The structure of this function is very similar to that of
:py:meth:`~diofant.solvers.ode.constantsimp`.
Examples
========
>>> C0, C1, C2, C3, C4 = symbols('C:5')
Only constants in the given range (inclusive) are renumbered;
the renumbering always starts from 1:
>>> constant_renumber(C1 + C3 + C4, 'C', 1, 3)
C1 + C2 + C4
>>> constant_renumber(C0 + C1 + C3 + C4, 'C', 2, 4)
C0 + 2*C1 + C2
>>> constant_renumber(C0 + 2*C1 + C2, 'C', 0, 1)
C1 + 3*C2
>>> pprint(C2 + C1*x + C3*x**2, use_unicode=False)
2
C1*x + C2 + C3*x
>>> pprint(constant_renumber(C2 + C1*x + C3*x**2, 'C', 1, 3), use_unicode=False)
2
C1 + C2*x + C3*x
"""
if type(expr) in (set, list, tuple):
return type(expr)(
[constant_renumber(i, symbolname=symbolname, startnumber=startnumber, endnumber=endnumber)
for i in expr]
)
global newstartnumber
newstartnumber = 1
constants_found = [None]*(endnumber + 2)
constantsymbols = [Symbol(
symbolname + f'{t:d}') for t in range(startnumber,
endnumber + 1)]
# make a mapping to send all constantsymbols to Integer(1) and use
# that to make sure that term ordering is not dependent on
# the indexed value of C
C_1 = [(ci, Integer(1)) for ci in constantsymbols]
def sort_key(arg):
return default_sort_key(arg.subs(C_1))
def _constant_renumber(expr):
r"""
We need to have an internal recursive function so that
newstartnumber maintains its values throughout recursive calls.
"""
global newstartnumber
if isinstance(expr, Equality):
return Eq(
_constant_renumber(expr.lhs),
_constant_renumber(expr.rhs))
if type(expr) not in (Mul, Add, Pow) and not expr.is_Function and \
not expr.has(*constantsymbols):
# Base case, as above. Hope there aren't constants inside
# of some other class, because they won't be renumbered.
return expr
elif expr.is_Piecewise:
return expr
elif expr in constantsymbols:
if expr not in constants_found:
constants_found[newstartnumber] = expr
newstartnumber += 1
return expr
elif expr.is_Function or expr.is_Pow or isinstance(expr, Tuple):
return expr.func(
*[_constant_renumber(x) for x in expr.args])
else:
sortedargs = list(expr.args)
sortedargs.sort(key=sort_key)
return expr.func(*[_constant_renumber(x) for x in sortedargs])
expr = _constant_renumber(expr)
# Renumbering happens here
newconsts = symbols(f'C1:{newstartnumber:d}')
expr = expr.subs(zip(constants_found[1:], newconsts), simultaneous=True)
return expr
def _handle_Integral(expr, func, order, hint):
r"""
Converts a solution with Integrals in it into an actual solution.
For most hints, this simply runs ``expr.doit()``.
"""
global y
x = func.args[0]
f = func.func
if hint == '1st_exact':
sol = (expr.doit()).subs({y: f(x)})
del y
elif hint == '1st_exact_Integral':
sol = Eq(Subs(expr.lhs, (y, f(x))), expr.rhs)
del y
elif hint == 'nth_linear_constant_coeff_homogeneous':
sol = expr
elif not hint.endswith('_Integral'):
sol = expr.doit()
else:
sol = expr
return sol
# FIXME: replace the general solution in the docstring with
# dsolve(equation, hint='1st_exact_Integral'). You will need to be able
# to have assumptions on P and Q that dP/dy = dQ/dx.
def ode_1st_exact(eq, func, order, match):
r"""
Solves 1st order exact ordinary differential equations.
A 1st order differential equation is called exact if it is the total
differential of a function. That is, the differential equation
.. math:: P(x, y) \,\partial{}x + Q(x, y) \,\partial{}y = 0
is exact if there is some function `F(x, y)` such that `P(x, y) =
\partial{}F/\partial{}x` and `Q(x, y) = \partial{}F/\partial{}y`. It can
be shown that a necessary and sufficient condition for a first order ODE
to be exact is that `\partial{}P/\partial{}y = \partial{}Q/\partial{}x`.
Then, the solution will be as given below::
>>> x0, y0, C1 = symbols('x0 y0 C1')
>>> P, Q, F = map(Function, ['P', 'Q', 'F'])
>>> pprint(Eq(Eq(F(x, y), Integral(P(t, y), (t, x0, x)) +
... Integral(Q(x0, t), (t, y0, y))), C1), use_unicode=False)
x y
/ /
| |
F(x, y) = | P(t, y) dt + | Q(x0, t) dt = C1
| |
/ /
x0 y0
Where the first partials of `P` and `Q` exist and are continuous in a
simply connected region.
A note: Diofant currently has no way to represent inert substitution on an
expression, so the hint ``1st_exact_Integral`` will return an integral
with `dy`. This is supposed to represent the function that you are
solving for.
Examples
========
>>> dsolve(cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x),
... f(x), hint='1st_exact')
Eq(x*cos(f(x)) + f(x)**3/3, C1)
References
==========
* https://en.wikipedia.org/wiki/Exact_differential_equation
* :cite:`TenenbaumPollard63`, pp. 73.
"""
x = func.args[0]
r = match # d+e*diff(f(x),x)
e = r[r['e']]
d = r[r['d']]
global y # This is the only way to pass dummy y to _handle_Integral
y = r['y']
C1 = get_numbered_constants(eq, num=1)
# Refer Joel Moses, "Symbolic Integration - The Stormy Decade",
# Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558
# which gives the method to solve an exact differential equation.
sol = Integral(d, x) + Integral((e - (Integral(d, x).diff(y))), y)
return Eq(sol, C1)
def ode_1st_homogeneous_coeff_best(eq, func, order, match):
r"""
Returns the best solution to an ODE from the two hints
``1st_homogeneous_coeff_subs_dep_div_indep`` and
``1st_homogeneous_coeff_subs_indep_div_dep``.
This is as determined by :py:meth:`~diofant.solvers.ode.ode_sol_simplicity`.
See the
:py:meth:`~diofant.solvers.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`
and
:py:meth:`~diofant.solvers.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`
docstrings for more information on these hints. Note that there is no
``ode_1st_homogeneous_coeff_best_Integral`` hint.
Examples
========
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_best', simplify=False),
... use_unicode=False)
/ 2 \
| 3*x |
log|----- + 1|
| 2 |
\f (x) /
log(f(x)) = log(C1) - --------------
3
References
==========
* https://en.wikipedia.org/wiki/Homogeneous_differential_equation
* :cite:`TenenbaumPollard63`, pp. 59.
"""
# There are two substitutions that solve the equation, u1=y/x and u2=x/y
# They produce different integrals, so try them both and see which
# one is easier.
sol1 = ode_1st_homogeneous_coeff_subs_indep_div_dep(eq,
func, order, match)
sol2 = ode_1st_homogeneous_coeff_subs_dep_div_indep(eq,
func, order, match)
simplify = match.get('simplify', True)
if simplify:
# why is odesimp called here? Should it be at the usual spot?
constants = sol1.free_symbols.difference(eq.free_symbols)
sol1 = odesimp(
sol1, func, order, constants,
'1st_homogeneous_coeff_subs_indep_div_dep')
constants = sol2.free_symbols.difference(eq.free_symbols)
sol2 = odesimp(
sol2, func, order, constants,
'1st_homogeneous_coeff_subs_dep_div_indep')
return min([sol1, sol2], key=lambda x: ode_sol_simplicity(x, func,
trysolving=not simplify))
def ode_1st_homogeneous_coeff_subs_dep_div_indep(eq, func, order, match):
r"""
Solves a 1st order differential equation with homogeneous coefficients
using the substitution `u_1 = \frac{\text{<dependent
variable>}}{\text{<independent variable>}}`.
This is a differential equation
.. math:: P(x, y) + Q(x, y) dy/dx = 0
such that `P` and `Q` are homogeneous and of the same order. A function
`F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`.
Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See
also the docstring of :py:meth:`~diofant.solvers.ode.homogeneous_order`.
If the coefficients `P` and `Q` in the differential equation above are
homogeneous functions of the same order, then it can be shown that the
substitution `y = u_1 x` (i.e. `u_1 = y/x`) will turn the differential
equation into an equation separable in the variables `x` and `u`. If
`h(u_1)` is the function that results from making the substitution `u_1 =
f(x)/x` on `P(x, f(x))` and `g(u_2)` is the function that results from the
substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) +
Q(x, f(x)) f'(x) = 0`, then the general solution is::
>>> genform = g(f(x)/x) + h(f(x)/x)*f(x).diff(x)
>>> pprint(genform, use_unicode=False)
/f(x)\ /f(x)\ d
g|----| + h|----|*--(f(x))
\ x / \ x / dx
>>> pprint(dsolve(genform, f(x),
... hint='1st_homogeneous_coeff_subs_dep_div_indep_Integral'),
... use_unicode=False)
f(x)
----
x
/
|
| -h(u1)
log(x) = C1 + | ---------------- d(u1)
| u1*h(u1) + g(u1)
|
/
Where `u_1 h(u_1) + g(u_1) \ne 0` and `x \ne 0`.
See Also
========
diofant.solvers.ode.ode_1st_homogeneous_coeff_best
diofant.solvers.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep
Examples
========
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_subs_dep_div_indep',
... simplify=False), use_unicode=False)
/ 3 \
|3*f(x) f (x)|
log|------ + -----|
| x 3 |
\ x /
log(x) = log(C1) - -------------------
3
References
==========
* https://en.wikipedia.org/wiki/Homogeneous_differential_equation
* :cite:`TenenbaumPollard63`, pp. 59.
"""
x = func.args[0]
f = func.func
u = Dummy('u')
u1 = Dummy('u1') # u1 == f(x)/x
r = match # d+e*diff(f(x),x)
C1 = get_numbered_constants(eq, num=1)
xarg = match.get('xarg', 0)
yarg = match.get('yarg', 0)
int = Integral(
(-r[r['e']]/(r[r['d']] + u1*r[r['e']])).subs({x: 1, r['y']: u1}),
(u1, None, f(x)/x))
sol = logcombine(Eq(log(x), int + log(C1)), force=True)
sol = sol.subs({f(x): u}).subs(((u, u - yarg), (x, x - xarg), (u, f(x))))
return sol
def ode_1st_homogeneous_coeff_subs_indep_div_dep(eq, func, order, match):
r"""
Solves a 1st order differential equation with homogeneous coefficients
using the substitution `u_2 = \frac{\text{<independent
variable>}}{\text{<dependent variable>}}`.
This is a differential equation
.. math:: P(x, y) + Q(x, y) dy/dx = 0
such that `P` and `Q` are homogeneous and of the same order. A function
`F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`.
Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See
also the docstring of :py:meth:`~diofant.solvers.ode.homogeneous_order`.
If the coefficients `P` and `Q` in the differential equation above are
homogeneous functions of the same order, then it can be shown that the
substitution `x = u_2 y` (i.e. `u_2 = x/y`) will turn the differential
equation into an equation separable in the variables `y` and `u_2`. If
`h(u_2)` is the function that results from making the substitution `u_2 =
x/f(x)` on `P(x, f(x))` and `g(u_2)` is the function that results from the
substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) +
Q(x, f(x)) f'(x) = 0`, then the general solution is:
>>> genform = g(x/f(x)) + h(x/f(x))*f(x).diff(x)
>>> pprint(genform, use_unicode=False)
/ x \ / x \ d
g|----| + h|----|*--(f(x))
\f(x)/ \f(x)/ dx
>>> pprint(dsolve(genform, f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral'),
... use_unicode=False)
x
----
f(x)
/
|
| -g(u2)
| ---------------- d(u2)
| u2*g(u2) + h(u2)
|
/
<BLANKLINE>
f(x) = E *C1
Where `u_2 g(u_2) + h(u_2) \ne 0` and `f(x) \ne 0`.
See Also
========
diofant.solvers.ode.ode_1st_homogeneous_coeff_best
diofant.solvers.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep
Examples
========
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep',
... simplify=False), use_unicode=False)
/ 2 \
| 3*x |
log|----- + 1|
| 2 |
\f (x) /
log(f(x)) = log(C1) - --------------
3
References
==========
* https://en.wikipedia.org/wiki/Homogeneous_differential_equation
* :cite:`TenenbaumPollard63`, pp. 59.
"""
x = func.args[0]
f = func.func
u = Dummy('u')
u2 = Dummy('u2') # u2 == x/f(x)
r = match # d+e*diff(f(x),x)
C1 = get_numbered_constants(eq, num=1)
xarg = match.get('xarg', 0) # If xarg present take xarg, else zero
yarg = match.get('yarg', 0) # If yarg present take yarg, else zero
int = Integral(
simplify(
(-r[r['d']]/(r[r['e']] + u2*r[r['d']])).subs({x: u2, r['y']: 1})),
(u2, None, x/f(x)))
sol = logcombine(Eq(log(f(x)), int + log(C1)), force=True)
sol = sol.subs({f(x): u}).subs(((u, u - yarg), (x, x - xarg), (u, f(x))))
return sol
# XXX: Should this function maybe go somewhere else?
def homogeneous_order(eq, *symbols):
r"""
Returns the order `n` if `g` is homogeneous and ``None`` if it is not
homogeneous.
Determines if a function is homogeneous and if so of what order. A
function `f(x, y, \cdots)` is homogeneous of order `n` if `f(t x, t y,
\cdots) = t^n f(x, y, \cdots)`.
If the function is of two variables, `F(x, y)`, then `f` being homogeneous
of any order is equivalent to being able to rewrite `F(x, y)` as `G(x/y)`
or `H(y/x)`. This fact is used to solve 1st order ordinary differential
equations whose coefficients are homogeneous of the same order (see the
docstrings of
:py:meth:`~diofant.solvers.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep` and
:py:meth:`~diofant.solvers.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`).
Symbols can be functions, but every argument of the function must be a
symbol, and the arguments of the function that appear in the expression
must match those given in the list of symbols. If a declared function
appears with different arguments than given in the list of symbols,
``None`` is returned.
Examples
========
>>> homogeneous_order(f(x), f(x)) is None
True
>>> homogeneous_order(f(x, y), f(y, x), x, y) is None
True
>>> homogeneous_order(f(x), f(x), x)
1
>>> homogeneous_order(x**2*f(x)/sqrt(x**2+f(x)**2), x, f(x))
2
>>> homogeneous_order(x**2+f(x), x, f(x)) is None
True
"""
if not symbols:
raise ValueError('homogeneous_order: no symbols were given.')
symset = set(symbols)
eq = sympify(eq)
# The following are not supported
if eq.has(Order, Derivative):
return
# These are all constants
if eq.is_Number or eq.is_NumberSymbol or eq.is_number:
return Integer(0)
# Replace all functions with dummy variables
dum = numbered_symbols(prefix='d', cls=Dummy)
newsyms = set()
for i in [j for j in symset if getattr(j, 'is_Function')]:
iargs = set(i.args)
if iargs.difference(symset):
return
else:
dummyvar = next(dum)
eq = eq.subs({i: dummyvar})
symset.remove(i)
newsyms.add(dummyvar)
symset.update(newsyms)
if not eq.free_symbols & symset:
return
# assuming order of a nested function can only be equal to zero
if isinstance(eq, Function):
return None if homogeneous_order(
eq.args[0], *tuple(symset)) != 0 else Integer(0)
# make the replacement of x with x*t and see if t can be factored out
t = Dummy('t', positive=True) # It is sufficient that t > 0
eqs = separatevars(eq.subs({i: t*i for i in symset}), [t], dict=True)[t]
if eqs == 1:
return Integer(0) # there was no term with only t
i, d = eqs.as_independent(t, as_Add=False)
b, e = d.as_base_exp()
if b == t:
return e
def ode_1st_linear(eq, func, order, match):
r"""
Solves 1st order linear differential equations.
These are differential equations of the form
.. math:: dy/dx + P(x) y = Q(x)\text{.}
These kinds of differential equations can be solved in a general way. The
integrating factor `e^{\int P(x) \,dx}` will turn the equation into a
separable equation. The general solution is::
>>> P, Q = map(Function, ['P', 'Q'])
>>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x))
>>> pprint(genform, use_unicode=False)
d
P(x)*f(x) + --(f(x)) = Q(x)
dx
>>> pprint(dsolve(genform, f(x), hint='1st_linear_Integral'), use_unicode=False)
/ / \
| | |
/ | | / |
| | | | |
- | P(x) dx | | | P(x) dx |
| | | | |
/ | | / |
f(x) = E *|C1 + | E *Q(x) dx|
| | |
\ / /
Examples
========
>>> pprint(dsolve(Eq(x*diff(f(x), x) - f(x), x**2*sin(x)),
... f(x), '1st_linear'), use_unicode=False)
f(x) = x*(C1 - cos(x))
References
==========
* https://en.wikipedia.org/wiki/Linear_differential_equation#First-order_equation_with_variable_coefficients
* :cite:`TenenbaumPollard63`, pp. 92.
"""
x = func.args[0]
f = func.func
r = match # a*diff(f(x),x) + b*f(x) + c
C1 = get_numbered_constants(eq, num=1)
t = exp(Integral(r[r['b']]/r[r['a']], x))
tt = Integral(t*(-r[r['c']]/r[r['a']]), x)
f = match.get('u', f(x)) # take almost-linear u if present, else f(x)
return Eq(f, (tt + C1)/t)
def ode_Bernoulli(eq, func, order, match):
r"""
Solves Bernoulli differential equations.
These are equations of the form
.. math:: dy/dx + P(x) y = Q(x) y^n\text{, }n \ne 1`\text{.}
The substitution `w = 1/y^{1-n}` will transform an equation of this form
into one that is linear (see the docstring of
:py:meth:`~diofant.solvers.ode.ode_1st_linear`). The general solution is::
>>> P, Q = map(Function, ['P', 'Q'])
>>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)**n)
>>> pprint(genform, use_unicode=False)
d n
P(x)*f(x) + --(f(x)) = Q(x)*f (x)
dx
>>> pprint(dsolve(genform, f(x), hint='Bernoulli_Integral'),
... use_unicode=False, wrap_line=False)
1
------
-n + 1
/ / / \\
| | | ||
| / | | / ||
| | | | | ||
| -(-n + 1)* | P(x) dx | | (-n + 1)* | P(x) dx ||
| | | | | ||
| / | | / ||
f(x) = |E *|C1 + (n - 1)* | -E *Q(x) dx||
| | | ||
\ \ / //
Note that the equation is separable when `n = 1` (see the docstring of
:py:meth:`~diofant.solvers.ode.ode_separable`).
>>> pprint(dsolve(Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)), f(x),
... hint='separable_Integral'), use_unicode=False)
f(x)
/
| /
| 1 |
| - dy = C1 + | (-P(x) + Q(x)) dx
| y |
| /
/
Examples
========
>>> pprint(dsolve(Eq(x*f(x).diff(x) + f(x), log(x)*f(x)**2),
... f(x), hint='Bernoulli'), use_unicode=False)
1
f(x) = -------------------
/ log(x) 1\
x*|C1 + ------ + -|
\ x x/
References
==========
* https://en.wikipedia.org/wiki/Bernoulli_differential_equation
* :cite:`TenenbaumPollard63`, pp. 95.
"""
x = func.args[0]
f = func.func
r = match # a*diff(f(x),x) + b*f(x) + c*f(x)**n, n != 1
C1 = get_numbered_constants(eq, num=1)
t = exp((1 - r[r['n']])*Integral(r[r['b']]/r[r['a']], x))
tt = (r[r['n']] - 1)*Integral(t*r[r['c']]/r[r['a']], x)
return Eq(f(x), ((tt + C1)/t)**(1/(1 - r[r['n']])))
def ode_Riccati_special_minus2(eq, func, order, match):
r"""
The general Riccati equation has the form
.. math:: dy/dx = f(x) y^2 + g(x) y + h(x)\text{.}
While it does not have a general solution [1], the "special" form, `dy/dx
= a y^2 - b x^c`, does have solutions in many cases [2]. This routine
returns a solution for `a(dy/dx) = b y^2 + c y/x + d/x^2` that is obtained
by using a suitable change of variables to reduce it to the special form
and is valid when neither `a` nor `b` are zero and either `c` or `d` is
zero.
>>> genform = a*f(x).diff(x) - (b*f(x)**2 + c*f(x)/x + d/x**2)
>>> sol = dsolve(genform, f(x))
>>> pprint(sol, wrap_line=False, use_unicode=False)
/ / __________________ \\
| __________________ | / 2 ||
| / 2 | \/ 4*b*d - (a + c) *log(x)||
-|a + c - \/ 4*b*d - (a + c) *tan|C1 + ----------------------------||
\ \ 2*a //
f(x) = ------------------------------------------------------------------------
2*b*x
References
==========
1. https://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Riccati
2. http://eqworld.ipmnet.ru/en/solutions/ode/ode0106.pdf -
http://eqworld.ipmnet.ru/en/solutions/ode/ode0123.pdf
"""
x = func.args[0]
f = func.func
r = match # a2*diff(f(x),x) + b2*f(x) + c2*f(x)/x + d2/x**2
a2, b2, c2, d2 = (r[r[s]] for s in 'a2 b2 c2 d2'.split())
C1 = get_numbered_constants(eq, num=1)
mu = sqrt(4*d2*b2 - (a2 - c2)**2)
return Eq(f(x), (a2 - c2 - mu*tan(mu/(2*a2)*log(x) + C1))/(2*b2*x))
def ode_Liouville(eq, func, order, match):
r"""
Solves 2nd order Liouville differential equations.
The general form of a Liouville ODE is
.. math:: \frac{d^2 y}{dx^2} + g(y) \left(\!
\frac{dy}{dx}\!\right)^2 + h(x)
\frac{dy}{dx}\text{.}
The general solution is:
>>> genform = Eq(diff(f(x), x, x) + g(f(x))*diff(f(x), x)**2 +
... h(x)*diff(f(x), x), 0)
>>> pprint(genform, use_unicode=False)
2 2
/d \ d d
g(f(x))*|--(f(x))| + h(x)*--(f(x)) + ---(f(x)) = 0
\dx / dx 2
dx
>>> pprint(dsolve(genform, f(x), hint='Liouville_Integral'), use_unicode=False)
f(x)
/ /
| |
| / | /
| | | |
| - | h(x) dx | | g(y) dy
| | | |
| / | /
C1 + C2* | E dx + | E dy = 0
| |
/ /
<BLANKLINE>
Examples
========
>>> pprint(dsolve(diff(f(x), x, x) + diff(f(x), x)**2/f(x) +
... diff(f(x), x)/x, f(x), hint='Liouville'),
... use_unicode=False)
________________ ________________
[f(x) = -\/ C1 + C2*log(x) , f(x) = \/ C1 + C2*log(x) ]
References
==========
* :cite:`goldstein1973advanced`, pp. 98.
* https://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Liouville
"""
# Liouville ODE:
# f(x).diff((x, 2)) + g(f(x))*(f(x).diff((x, 2)))**2 + h(x)*f(x).diff(x)
# See Goldstein and Braun, "Advanced Methods for the Solution of
# Differential Equations", pg. 98, as well as
# https://www.maplesoft.com/support/help/view.aspx?path=odeadvisor/Liouville
x = func.args[0]
f = func.func
r = match # f(x).diff((x, 2)) + g*f(x).diff(x)**2 + h*f(x).diff(x)
y = r['y']
C1, C2 = get_numbered_constants(eq, num=2)
int = Integral(exp(Integral(r['g'], y)), (y, None, f(x)))
sol = Eq(int + C1*Integral(exp(-Integral(r['h'], x)), x) + C2, 0)
return sol
def ode_2nd_power_series_ordinary(eq, func, order, match):
r"""
Gives a power series solution to a second order homogeneous differential
equation with polynomial coefficients at an ordinary point. A homogenous
differential equation is of the form
.. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) y = 0
For simplicity it is assumed that `P(x)`, `Q(x)` and `R(x)` are polynomials,
it is sufficient that `\frac{Q(x)}{P(x)}` and `\frac{R(x)}{P(x)}` exists at
`x_{0}`. A recurrence relation is obtained by substituting `y` as `\sum_{n=0}^\infty a_{n}x^{n}`,
in the differential equation, and equating the nth term. Using this relation
various terms can be generated.
Examples
========
>>> eq = f(x).diff((x, 2)) + f(x)
>>> pprint(dsolve(eq, hint='2nd_power_series_ordinary'), use_unicode=False)
/ 4 2 \ / 2 \
|x x | | x | / 6\
f(x) = C2*|-- - -- + 1| + C1*x*|- -- + 1| + O\x /
\24 2 / \ 6 /
References
==========
* http://tutorial.math.lamar.edu/Classes/DE/SeriesSolutions.aspx
* :cite:`simmons2016differential`, pp 176 - 184.
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
n = Dummy('n', integer=True)
s = Wild('s')
k = Wild('k', exclude=[x])
x0 = match.get('x0')
terms = match.get('terms', 5)
p = match[match['a3']]
q = match[match['b3']]
r = match[match['c3']]
seriesdict = {}
recurr = Function('r')
# Generating the recurrence relation which works this way:
# for the second order term the summation begins at n = 2. The coefficients
# p is multiplied with an*(n - 1)*(n - 2)*x**n-2 and a substitution is made such that
# the exponent of x becomes n.
# For example, if p is x, then the second degree recurrence term is
# an*(n - 1)*(n - 2)*x**n-1, substituting (n - 1) as n, it transforms to
# an+1*n*(n - 1)*x**n.
# A similar process is done with the first order and zeroth order term.
coefflist = [(recurr(n), r), (n*recurr(n), q), (n*(n - 1)*recurr(n), p)]
for index, coeff in enumerate(coefflist):
if coeff[1]:
f2 = powsimp(expand((coeff[1]*(x - x0)**(n - index)).subs({x: x + x0})))
if f2.is_Add:
addargs = f2.args
else:
addargs = [f2]
for arg in addargs:
powm = arg.match(s*x**k)
term = coeff[0]*powm[s]
if not powm[k].is_Symbol:
term = term.subs({n: n - powm[k].as_independent(n)[0]})
startind = powm[k].subs({n: index})
# Seeing if the startterm can be reduced further.
# If it vanishes for n lesser than startind, it is
# equal to summation from n.
if startind:
for i in reversed(range(startind)):
if not term.subs({n: i}):
seriesdict[term] = i
else:
seriesdict[term] = i + 1
break
else:
seriesdict[term] = Integer(0)
# Stripping of terms so that the sum starts with the same number.
teq = Integer(0)
suminit = seriesdict.values()
req = Add(*seriesdict)
if any(suminit):
maxval = max(suminit)
for k, val in seriesdict.items():
if val != maxval:
for i in range(val, maxval):
teq += k.subs({n: val})
finaldict = {}
if teq:
fargs = teq.atoms(AppliedUndef)
if len(fargs) == 1:
finaldict[fargs.pop()] = 0
else:
maxf = max(fargs, key=lambda x: x.args[0])
sol = solve(teq, maxf)
sol = sol[0][maxf]
finaldict[maxf] = sol
# Finding the recurrence relation in terms of the largest term.
fargs = req.atoms(AppliedUndef)
maxf = max(fargs, key=lambda x: x.args[0])
minf = min(fargs, key=lambda x: x.args[0])
if minf.args[0].is_Symbol:
startiter = 0
else:
startiter = -minf.args[0].as_independent(n)[0]
lhs = maxf
rhs = solve(req, maxf)
rhs = rhs[0][maxf]
# Checking how many values are already present
tcounter = len([t for t in finaldict.values() if t])
for _ in range(tcounter, terms - 3): # Assuming c0 and c1 to be arbitrary
check = rhs.subs({n: startiter})
nlhs = lhs.subs({n: startiter})
nrhs = check.subs(finaldict)
finaldict[nlhs] = nrhs
startiter += 1
# Post processing
series = C0 + C1*(x - x0)
for term, v in finaldict.items():
if v:
fact = term.args[0]
series += (v.subs({recurr(0): C0, recurr(1): C1})*(x - x0)**fact)
series = collect(expand_mul(series), [C0, C1]) + Order(x**terms)
return Eq(f(x), series)
def ode_2nd_power_series_regular(eq, func, order, match):
r"""
Gives a power series solution to a second order homogeneous differential
equation with polynomial coefficients at a regular point. A second order
homogenous differential equation is of the form
.. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) y = 0
A point is said to regular singular at `x0` if `x - x0\frac{Q(x)}{P(x)}`
and `(x - x0)^{2}\frac{R(x)}{P(x)}` are analytic at `x0`. For simplicity
`P(x)`, `Q(x)` and `R(x)` are assumed to be polynomials. The algorithm for
finding the power series solutions is:
1. Try expressing `(x - x0)P(x)` and `((x - x0)^{2})Q(x)` as power series
solutions about x0. Find `p0` and `q0` which are the constants of the
power series expansions.
2. Solve the indicial equation `f(m) = m(m - 1) + m*p0 + q0`, to obtain the
roots `m1` and `m2` of the indicial equation.
3. If `m1 - m2` is a non integer there exists two series solutions. If
`m1 = m2`, there exists only one solution. If `m1 - m2` is an integer,
then the existence of one solution is confirmed. The other solution may
or may not exist.
The power series solution is of the form `x^{m}\sum_{n=0}^\infty a_{n}x^{n}`. The
coefficients are determined by the following recurrence relation.
`a_{n} = -\frac{\sum_{k=0}^{n-1} q_{n-k} + (m + k)p_{n-k}}{f(m + n)}`. For the case
in which `m1 - m2` is an integer, it can be seen from the recurrence relation
that for the lower root `m`, when `n` equals the difference of both the
roots, the denominator becomes zero. So if the numerator is not equal to zero,
a second series solution exists.
Examples
========
>>> eq = x*(f(x).diff((x, 2))) + 2*(f(x).diff(x)) + x*f(x)
>>> pprint(dsolve(eq), use_unicode=False)
/ 6 4 2 \
| x x x |
/ 4 2 \ C1*|- --- + -- - -- + 1|
| x x | \ 720 24 2 / / 6\
f(x) = C2*|--- - -- + 1| + ------------------------ + O\x /
\120 6 / x
References
==========
* :cite:`simmons2016differential`, pp 176 - 184.
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
m = Dummy('m') # for solving the indicial equation
x0 = match.get('x0')
terms = match.get('terms', 5)
p = match['p']
q = match['q']
# Generating the indicial equation
indicial = []
for term in [p, q]:
if not term.has(x):
indicial.append(term)
else:
term = term.series(n=1, x0=x0)
if isinstance(term, Order):
indicial.append(Integer(0))
else:
indicial.append(term.args[0])
p0, q0 = indicial
sollist = solve(m*(m - 1) + m*p0 + q0, m)
if sollist and all(sol[m].is_extended_real for sol in sollist):
serdict1 = {}
serdict2 = {}
if len(sollist) == 1:
# Only one series solution exists in this case.
m1 = m2 = sollist.pop()[m]
if terms-m1-1 <= 0:
return Eq(f(x), Order(terms))
serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
else:
m2 = sollist[0][m]
m1 = sollist[1][m]
# Irrespective of whether m1 - m2 is an integer or not, one
# Frobenius series solution exists.
serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
if not (m1 - m2).is_integer:
# Second frobenius series solution exists.
serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1)
else:
# Check if second frobenius series solution exists.
serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1, check=m1)
finalseries1 = C0
for k, v in serdict1.items():
power = int(k.name[1:])
finalseries1 += v*(x - x0)**power
finalseries1 = (x - x0)**m1*finalseries1
finalseries2 = Integer(0)
if serdict2:
for k, v in serdict2.items():
power = int(k.name[1:])
finalseries2 += v*(x - x0)**power
finalseries2 += C1
finalseries2 = (x - x0)**m2*finalseries2
return Eq(f(x), collect(finalseries1 + finalseries2,
[C0, C1]) + Order(x**terms))
else:
return NotImplementedError
def _frobenius(n, m, p0, q0, p, q, x0, x, c, check=None):
r"""
Returns a dict with keys as coefficients and values as their values in terms of C0
"""
n = int(n)
# In cases where m1 - m2 is not an integer
m2 = check
d = Dummy('d')
numsyms = numbered_symbols('C', start=0)
numsyms = [next(numsyms) for i in range(n + 1)]
serlist = []
for ser in [p, q]:
if x0 != 0 or not ser.is_polynomial(x) or Poly(ser, x).degree() > n:
tseries = ser.series(x=x, x0=x0, n=n + 1)
ser = tseries.removeO()
dict_ = Poly(ser, x).as_dict()
# Fill in with zeros, if coefficients are zero.
for i in range(n + 1):
if (i,) not in dict_:
dict_[(i,)] = Integer(0)
serlist.append(dict_)
pseries = serlist[0]
qseries = serlist[1]
indicial = d*(d - 1) + d*p0 + q0
frobdict = {}
for i in range(1, n + 1):
num = c*(m*pseries[(i,)] + qseries[(i,)])
for j in range(1, i):
sym = Symbol('C' + str(j))
num += frobdict[sym]*((m + j)*pseries[(i - j,)] + qseries[(i - j,)])
# Checking for cases when m1 - m2 is an integer. If num equals zero
# then a second Frobenius series solution cannot be found. If num is not zero
# then set constant as zero and proceed.
if m2 is not None and i == m2 - m:
if num:
raise NotImplementedError
frobdict[numsyms[i]] = Integer(0)
else:
frobdict[numsyms[i]] = -num/(indicial.subs({d: m+i}))
return frobdict
def _nth_linear_match(eq, func, order):
r"""
Matches a differential equation to the linear form:
.. math:: a_n(x) y^{(n)} + \cdots + a_1(x)y' + a_0(x) y + B(x) = 0
Returns a dict of order:coeff terms, where order is the order of the
derivative on each term, and coeff is the coefficient of that derivative.
The key ``-1`` holds the function `B(x)`. Returns ``None`` if the ODE is
not linear. This function assumes that ``func`` has already been checked
to be good.
Examples
========
>>> _nth_linear_match(f(x).diff((x, 3)) + 2*f(x).diff(x) +
... x*f(x).diff((x, 2)) + cos(x)*f(x).diff(x) + x - f(x) -
... sin(x), f(x), 3)
{-1: x - sin(x), 0: -1, 1: cos(x) + 2, 2: x, 3: 1}
>>> _nth_linear_match(f(x).diff((x, 3)) + 2*f(x).diff(x) +
... x*f(x).diff((x, 2)) + cos(x)*f(x).diff(x) + x - f(x) -
... sin(f(x)), f(x), 3) is None
True
"""
x = func.args[0]
one_x = {x}
terms = {i: Integer(0) for i in range(-1, order + 1)}
for i in Add.make_args(eq):
if not i.has(func):
terms[-1] += i
else:
c, f = i.as_independent(func)
if not ((isinstance(f, Derivative) and set(f.variables) == one_x)
or f == func):
return
else:
terms[len(f.args[1:])] += c
return terms
def ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear homogeneous variable-coefficient
Cauchy-Euler equidimensional ordinary differential equation.
This is an equation with form `0 = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
These equations can be solved in a general manner, by substituting
solutions of the form `f(x) = x^r`, and deriving a characteristic equation
for `r`. When there are repeated roots, we include extra terms of the
form `C_{r k} \ln^k(x) x^r`, where `C_{r k}` is an arbitrary integration
constant, `r` is a root of the characteristic equation, and `k` ranges
over the multiplicity of `r`. In the cases where the roots are complex,
solutions of the form `C_1 x^a \sin(b \log(x)) + C_2 x^a \cos(b \log(x))`
are returned, based on expansions with Eulers formula. The general
solution is the sum of the terms found. If Diofant cannot find exact roots
to the characteristic equation, a
:py:class:`~diofant.polys.rootoftools.RootOf` instance will be returned
instead.
>>> dsolve(4*x**2*f(x).diff((x, 2)) + f(x), f(x),
... hint='nth_linear_euler_eq_homogeneous')
Eq(f(x), sqrt(x)*(C1 + C2*log(x)))
Note that because this method does not involve integration, there is no
``nth_linear_euler_eq_homogeneous_Integral`` hint.
The following is for internal use:
- ``returns = 'sol'`` returns the solution to the ODE.
- ``returns = 'list'`` returns a list of linearly independent solutions,
corresponding to the fundamental solution set, for use with non
homogeneous solution methods like variation of parameters and
undetermined coefficients. Note that, though the solutions should be
linearly independent, this function does not explicitly check that. You
can do ``assert simplify(wronskian(sollist)) != 0`` to check for linear
independence. Also, ``assert len(sollist) == order`` will need to pass.
- ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>,
'list': <list of linearly independent solutions>}``.
Examples
========
>>> eq = f(x).diff((x, 2))*x**2 - 4*f(x).diff(x)*x + 6*f(x)
>>> pprint(dsolve(eq, f(x),
... hint='nth_linear_euler_eq_homogeneous'),
... use_unicode=False)
2
f(x) = x *(C1 + C2*x)
References
==========
* https://en.wikipedia.org/wiki/Cauchy%E2%80%93Euler_equation
* C. Bender & S. Orszag, "Advanced Mathematical Methods for Scientists and
Engineers", Springer 1999, pp. 12.
"""
global collectterms
collectterms = []
x = func.args[0]
f = func.func
r = match
# First, set up characteristic equation.
chareq, symbol = Integer(0), Dummy('x')
for i in r:
if not isinstance(i, str) and i >= 0:
chareq += (r[i]*diff(x**symbol, (x, i))*x**-symbol).expand()
chareq = Poly(chareq, symbol)
chareqroots = chareq.all_roots()
# A generator of constants
constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
constants.reverse()
# Create a dict root: multiplicity or charroots
charroots = defaultdict(int)
for root in chareqroots:
charroots[root] += 1
gsol = Integer(0)
# We need keep track of terms so we can run collect() at the end.
# This is necessary for constantsimp to work properly.
ln = log
for root, multiplicity in charroots.items():
for i in range(multiplicity):
if isinstance(root, RootOf):
gsol += (x**root) * constants.pop()
if multiplicity != 1:
raise NotImplementedError
collectterms = [(0, root, 0)] + collectterms
elif root.is_extended_real:
gsol += ln(x)**i*(x**root) * constants.pop()
collectterms = [(i, root, 0)] + collectterms
else:
reroot = re(root)
imroot = im(root)
gsol += ln(x)**i * (x**reroot) * (
constants.pop() * sin(abs(imroot)*ln(x))
+ constants.pop() * cos(imroot*ln(x)))
# Preserve ordering (multiplicity, real part, imaginary part)
# It will be assumed implicitly when constructing
# fundamental solution sets.
collectterms = [(i, reroot, imroot)] + collectterms
if returns == 'sol':
return Eq(f(x), gsol)
elif returns == 'both':
# HOW TO TEST THIS CODE? (dsolve does not pass 'returns' through)
# Create a list of (hopefully) linearly independent solutions
gensols = []
# Keep track of when to use sin or cos for nonzero imroot
for i, reroot, imroot in collectterms:
if imroot == 0:
gensols.append(ln(x)**i*x**reroot)
else:
sin_form = ln(x)**i*x**reroot*sin(abs(imroot)*ln(x))
if sin_form in gensols:
cos_form = ln(x)**i*x**reroot*cos(imroot*ln(x))
gensols.append(cos_form)
else:
gensols.append(sin_form)
return {'sol': Eq(f(x), gsol), 'list': gensols}
else:
raise ValueError('Unknown value for key "returns".')
def ode_nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional
ordinary differential equation using undetermined coefficients.
This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
These equations can be solved in a general manner, by substituting
solutions of the form `x = exp(t)`, and deriving a characteristic equation
of form `g(exp(t)) = b_0 f(t) + b_1 f'(t) + b_2 f''(t) \cdots` which can
be then solved by nth_linear_constant_coeff_undetermined_coefficients if
g(exp(t)) has finite number of lineary independent derivatives.
Functions that fit this requirement are finite sums functions of the form
`a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i`
is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For
example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`,
and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have
a finite number of derivatives, because they can be expanded into `\sin(a
x)` and `\cos(b x)` terms. However, Diofant currently cannot do that
expansion, so you will need to manually rewrite the expression in terms of
the above to use this method. So, for example, you will need to manually
convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method
of undetermined coefficients on it.
After replacement of x by exp(t), this method works by creating a trial function
from the expression and all of its linear independent derivatives and
substituting them into the original ODE. The coefficients for each term
will be a system of linear equations, which are be solved for and
substituted, giving the solution. If any of the trial functions are linearly
dependent on the solution to the homogeneous equation, they are multiplied
by sufficient `x` to make them linearly independent.
Examples
========
>>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x)
>>> hint = 'nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients'
>>> dsolve(eq, f(x), hint=hint).expand()
Eq(f(x), C1*x + C2*x**2 + log(x)/2 + 3/4)
"""
x = func.args[0]
f = func.func
r = match
chareq, eq, symbol = Integer(0), Integer(0), Dummy('x')
for i in r:
if not isinstance(i, str) and i >= 0:
chareq += (r[i]*diff(x**symbol, (x, i))*x**-symbol).expand()
for i in range(1, degree(Poly(chareq, symbol)) + 1):
eq += chareq.coeff(symbol**i)*diff(f(x), (x, i))
if chareq.as_coeff_add(symbol)[0]:
eq += chareq.as_coeff_add(symbol)[0]*f(x)
e, re = posify(r[-1].subs({x: exp(x)}))
eq += e.subs(re)
match = _nth_linear_match(eq, f(x), ode_order(eq, f(x)))
match['trialset'] = r['trialset']
return ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match).subs({x: log(x)}).subs({f(log(x)): f(x)}).expand()
def ode_nth_linear_euler_eq_nonhomogeneous_variation_of_parameters(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional
ordinary differential equation using variation of parameters.
This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
This method works by assuming that the particular solution takes the form
.. math:: \sum_{x=1}^{n} c_i(x) y_i(x) {a_n} {x^n} \text{,}
where `y_i` is the `i`\th solution to the homogeneous equation. The
solution is then solved using Wronskian's and Cramer's Rule. The
particular solution is given by multiplying eq given below with `a_n x^{n}`
.. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx
\right) y_i(x) \text{,}
where `W(x)` is the Wronskian of the fundamental system (the system of `n`
linearly independent solutions to the homogeneous equation), and `W_i(x)`
is the Wronskian of the fundamental system with the `i`\th column replaced
with `[0, 0, \cdots, 0, \frac{x^{- n}}{a_n} g{\left (x \right )}]`.
This method is general enough to solve any `n`\th order inhomogeneous
linear differential equation, but sometimes Diofant cannot simplify the
Wronskian well enough to integrate it. If this method hangs, try using the
``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and
simplifying the integrals manually. Also, prefer using
``nth_linear_constant_coeff_undetermined_coefficients`` when it
applies, because it doesn't use integration, making it faster and more
reliable.
Warning, using simplify=False with
'nth_linear_constant_coeff_variation_of_parameters' in
:py:meth:`~diofant.solvers.ode.dsolve` may cause it to hang, because it will
not attempt to simplify the Wronskian before integrating. It is
recommended that you only use simplify=False with
'nth_linear_constant_coeff_variation_of_parameters_Integral' for this
method, especially if the solution to the homogeneous equation has
trigonometric functions in it.
Examples
========
>>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - x**4
>>> hint = 'nth_linear_euler_eq_nonhomogeneous_variation_of_parameters'
>>> dsolve(eq, f(x), hint=hint).expand()
Eq(f(x), C1*x + C2*x**2 + x**4/6)
"""
x = func.args[0]
f = func.func
r = match
gensol = ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='both')
match.update(gensol)
r[-1] = r[-1]/r[ode_order(eq, f(x))]
sol = _solve_variation_of_parameters(eq, func, order, match)
return Eq(f(x), r['sol'].rhs + (sol.rhs - r['sol'].rhs)*r[ode_order(eq, f(x))])
def ode_almost_linear(eq, func, order, match):
r"""
Solves an almost-linear differential equation.
The general form of an almost linear differential equation is
.. math:: f(x) g(y) y + k(x) l(y) + m(x) = 0
\text{where} l'(y) = g(y)\text{.}
This can be solved by substituting `l(y) = u(y)`. Making the given
substitution reduces it to a linear differential equation of the form `u'
+ P(x) u + Q(x) = 0`.
The general solution is
>>> k, l = map(Function, ['k', 'l'])
>>> genform = Eq(f(x)*(l(y).diff(y)) + k(x)*l(y) + g(x), 0)
>>> pprint(genform, use_unicode=False)
d
f(x)*--(l(y)) + g(x) + k(x)*l(y) = 0
dy
>>> pprint(dsolve(genform, hint='almost_linear'), use_unicode=False)
/ // -y*g(x) \\
| || -------- for k(x) = 0||
-y*k(x) | || f(x) ||
-------- | || ||
f(x) | || y*k(x) ||
l(y) = E *|C1 + |< ------ ||
| || f(x) ||
| ||-E *g(x) ||
| ||-------------- otherwise ||
| || k(x) ||
\ \\ //
See Also
========
:meth:`diofant.solvers.ode.ode_1st_linear`
Examples
========
>>> d = f(x).diff(x)
>>> eq = x*d + x*f(x) + 1
>>> dsolve(eq, f(x), hint='almost_linear')
Eq(f(x), E**(-x)*(C1 - Ei(x)))
>>> pprint(dsolve(eq, f(x), hint='almost_linear'), use_unicode=False)
-x
f(x) = E *(C1 - Ei(x))
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
# Since ode_1st_linear has already been implemented, and the
# coefficients have been modified to the required form in
# classify_ode, just passing eq, func, order and match to
# ode_1st_linear will give the required output.
return ode_1st_linear(eq, func, order, match)
def _linear_coeff_match(expr, func):
r"""
Helper function to match hint ``linear_coefficients``.
Matches the expression to the form `(a_1 x + b_1 f(x) + c_1)/(a_2 x + b_2
f(x) + c_2)` where the following conditions hold:
1. `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are Rationals;
2. `c_1` or `c_2` are not equal to zero;
3. `a_2 b_1 - a_1 b_2` is not equal to zero.
Return ``xarg``, ``yarg`` where
1. ``xarg`` = `(b_2 c_1 - b_1 c_2)/(a_2 b_1 - a_1 b_2)`
2. ``yarg`` = `(a_1 c_2 - a_2 c_1)/(a_2 b_1 - a_1 b_2)`
Examples
========
>>> _linear_coeff_match(((-25*f(x) - 8*x + 62)/(4*f(x) + 11*x - 11)), f(x))
(1/9, 22/9)
>>> _linear_coeff_match(sin((-5*f(x) - 8*x + 6)/(4*f(x) + x - 1)), f(x))
(19/27, 2/27)
>>> _linear_coeff_match(sin(f(x)/x), f(x))
"""
f = func.func
x = func.args[0]
def abc(eq):
r"""
Internal function of _linear_coeff_match
that returns Rationals a, b, c
if eq is a*x + b*f(x) + c, else None.
"""
eq = _mexpand(eq)
c = eq.as_independent(x, f(x), as_Add=True)[0]
if not c.is_Rational:
return
a = eq.coeff(x)
if not a.is_Rational:
return
b = eq.coeff(f(x))
if not b.is_Rational:
return
if eq == a*x + b*f(x) + c:
return a, b, c
def match(arg):
r"""
Internal function of _linear_coeff_match that returns Rationals a1,
b1, c1, a2, b2, c2 and a2*b1 - a1*b2 of the expression (a1*x + b1*f(x)
+ c1)/(a2*x + b2*f(x) + c2) if one of c1 or c2 and a2*b1 - a1*b2 is
non-zero, else None.
"""
n, d = arg.together().as_numer_denom()
m = abc(n)
if m is not None:
a1, b1, c1 = m
m = abc(d)
if m is not None:
a2, b2, c2 = m
d = a2*b1 - a1*b2
if (c1 or c2) and d:
return a1, b1, c1, a2, b2, c2, d
m = [fi.args[0] for fi in expr.atoms(Function) if fi.func != f and
len(fi.args) == 1 and not fi.args[0].is_Function] or {expr}
m1 = match(m.pop())
if m1 and all(match(mi) == m1 for mi in m):
a1, b1, c1, a2, b2, c2, denom = m1
return (b2*c1 - b1*c2)/denom, (a1*c2 - a2*c1)/denom
def ode_linear_coefficients(eq, func, order, match):
r"""
Solves a differential equation with linear coefficients.
The general form of a differential equation with linear coefficients is
.. math:: y' + F\left(\!\frac{a_1 x + b_1 y + c_1}{a_2 x + b_2 y +
c_2}\!\right) = 0\text{,}
where `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are constants and `a_1 b_2
- a_2 b_1 \ne 0`.
This can be solved by substituting:
.. math:: x = x' + \frac{b_2 c_1 - b_1 c_2}{a_2 b_1 - a_1 b_2}
y = y' + \frac{a_1 c_2 - a_2 c_1}{a_2 b_1 - a_1
b_2}\text{.}
This substitution reduces the equation to a homogeneous differential
equation.
See Also
========
:meth:`diofant.solvers.ode.ode_1st_homogeneous_coeff_best`
:meth:`diofant.solvers.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`
:meth:`diofant.solvers.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`
Examples
========
>>> eq = (x + f(x) + 1)*f(x).diff(x) + (f(x) - 6*x + 1)
>>> dsolve(eq, hint='linear_coefficients')
[Eq(f(x), -x - sqrt(C1 + 7*x**2) - 1), Eq(f(x), -x + sqrt(C1 + 7*x**2) - 1)]
>>> pprint(dsolve(eq, hint='linear_coefficients'), use_unicode=False)
___________ ___________
/ 2 / 2
[f(x) = -x - \/ C1 + 7*x - 1, f(x) = -x + \/ C1 + 7*x - 1]
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
return ode_1st_homogeneous_coeff_best(eq, func, order, match)
def ode_separable_reduced(eq, func, order, match):
r"""
Solves a differential equation that can be reduced to the separable form.
The general form of this equation is
.. math:: y' + (y/x) H(x^n y) = 0\text{}.
This can be solved by substituting `u(y) = x^n y`. The equation then
reduces to the separable form `\frac{u'}{u (\mathrm{power} - H(u))} -
\frac{1}{x} = 0`.
The general solution is:
>>> genform = f(x).diff(x) + (f(x)/x)*g(x**n*f(x))
>>> pprint(genform, use_unicode=False)
/ n \
d f(x)*g\x *f(x)/
--(f(x)) + ---------------
dx x
>>> pprint(dsolve(genform, hint='separable_reduced'), use_unicode=False)
n
x *f(x)
/
|
| 1
| ------------ dy = C1 + log(x)
| y*(n - g(y))
|
/
See Also
========
:meth:`diofant.solvers.ode.ode_separable`
Examples
========
>>> eq = (x - x**2*f(x))*f(x).diff(x) - f(x)
>>> dsolve(eq, hint='separable_reduced')
[Eq(f(x), (-sqrt(C1*x**2 + 1) + 1)/x), Eq(f(x), (sqrt(C1*x**2 + 1) + 1)/x)]
>>> pprint(dsolve(eq, hint='separable_reduced'), use_unicode=False)
___________ ___________
/ 2 / 2
- \/ C1*x + 1 + 1 \/ C1*x + 1 + 1
[f(x) = --------------------, f(x) = ------------------]
x x
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
# Arguments are passed in a way so that they are coherent with the
# ode_separable function
x = func.args[0]
f = func.func
y = Dummy('y')
u = match['u'].subs({match['t']: y})
ycoeff = 1/(y*(match['power'] - u))
m1 = {y: 1, x: -1/x, 'coeff': 1}
m2 = {y: ycoeff, x: 1, 'coeff': 1}
r = {'m1': m1, 'm2': m2, 'y': y, 'hint': x**match['power']*f(x)}
return ode_separable(eq, func, order, r)
def ode_1st_power_series(eq, func, order, match):
r"""
The power series solution is a method which gives the Taylor series expansion
to the solution of a differential equation.
For a first order differential equation `\frac{dy}{dx} = h(x, y)`, a power
series solution exists at a point `x = x_{0}` if `h(x, y)` is analytic at `x_{0}`.
The solution is given by
.. math:: y(x) = y(x_{0}) + \sum_{n = 1}^{\infty} \frac{F_{n}(x_{0},b)(x - x_{0})^n}{n!},
where `y(x_{0}) = b` is the value of y at the initial value of `x_{0}`.
To compute the values of the `F_{n}(x_{0},b)` the following algorithm is
followed, until the required number of terms are generated.
1. `F_1 = h(x_{0}, b)`
2. `F_{n+1} = \frac{\partial F_{n}}{\partial x} + \frac{\partial F_{n}}{\partial y}F_{1}`
Examples
========
>>> eq = exp(x)*(f(x).diff(x)) - f(x)
>>> pprint(dsolve(eq, hint='1st_power_series'), use_unicode=False)
3 4 5
C1*x C1*x C1*x / 6\
f(x) = C1 + C1*x - ----- + ----- + ----- + O\x /
6 24 60
References
==========
- Travis W. Walker, Analytic power series technique for solving first-order
differential equations, pp 17, 18
"""
x = func.args[0]
y = match['y']
f = func.func
h = -match[match['d']]/match[match['e']]
point = match.get('f0')
value = match.get('f0val')
terms = match.get('terms')
# First term
F = h
if not h:
return Eq(f(x), value)
# Initialisation
series = value
if terms > 1:
hc = h.subs({x: point, y: value})
if hc.has(oo, zoo, nan):
# Derivative does not exist, not analytic
return Eq(f(x), oo)
elif hc:
series += hc*(x - point)
for factcount in range(2, terms):
Fnew = F.diff(x) + F.diff(y)*h
Fnewc = Fnew.subs({x: point, y: value})
# Same logic as above
if Fnewc.has(oo, zoo, nan):
return Eq(f(x), oo)
series += Fnewc*((x - point)**factcount)/factorial(factcount)
F = Fnew
series += Order(x**terms)
return Eq(f(x), series)
def ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='sol'):
r"""
Solves an `n`\th order linear homogeneous differential equation with
constant coefficients.
This is an equation of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = 0\text{.}
These equations can be solved in a general manner, by taking the roots of
the characteristic equation `a_n m^n + a_{n-1} m^{n-1} + \cdots + a_1 m +
a_0 = 0`. The solution will then be the sum of `C_n x^i e^{r x}` terms,
for each where `C_n` is an arbitrary constant, `r` is a root of the
characteristic equation and `i` is one of each from 0 to the multiplicity
of the root - 1 (for example, a root 3 of multiplicity 2 would create the
terms `C_1 e^{3 x} + C_2 x e^{3 x}`). The exponential is usually expanded
for complex roots using Euler's equation `e^{I x} = \cos(x) + I \sin(x)`.
Complex roots always come in conjugate pairs in polynomials with real
coefficients, so the two roots will be represented (after simplifying the
constants) as `e^{a x} \left(C_1 \cos(b x) + C_2 \sin(b x)\right)`.
If Diofant cannot find exact roots to the characteristic equation, a
:py:class:`~diofant.polys.rootoftools.RootOf` instance will be return
instead.
>>> dsolve(f(x).diff((x, 5)) + 10*f(x).diff(x) - 2*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous')
Eq(f(x), E**(x*RootOf(_x**5 + 10*_x - 2, 0))*C1 +
E**(x*RootOf(_x**5 + 10*_x - 2, 1))*C2 +
E**(x*RootOf(_x**5 + 10*_x - 2, 2))*C3 +
E**(x*RootOf(_x**5 + 10*_x - 2, 3))*C4 +
E**(x*RootOf(_x**5 + 10*_x - 2, 4))*C5)
Note that because this method does not involve integration, there is no
``nth_linear_constant_coeff_homogeneous_Integral`` hint.
The following is for internal use:
- ``returns = 'sol'`` returns the solution to the ODE.
- ``returns = 'list'`` returns a list of linearly independent solutions,
for use with non homogeneous solution methods like variation of
parameters and undetermined coefficients. Note that, though the
solutions should be linearly independent, this function does not
explicitly check that. You can do ``assert simplify(wronskian(sollist))
!= 0`` to check for linear independence. Also, ``assert len(sollist) ==
order`` will need to pass.
- ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>,
'list': <list of linearly independent solutions>}``.
Examples
========
>>> pprint(dsolve(f(x).diff((x, 4)) + 2*f(x).diff((x, 3)) -
... 2*f(x).diff((x, 2)) - 6*f(x).diff(x) + 5*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous'),
... use_unicode=False)
x -2*x
f(x) = E *(C3 + C4*x) + E *(C1*sin(x) + C2*cos(x))
References
==========
* https://en.wikipedia.org/wiki/Linear_differential_equation section:
Nonhomogeneous_equation_with_constant_coefficients
* :cite:`TenenbaumPollard63`, pp. 211.
"""
x = func.args[0]
f = func.func
r = match
# First, set up characteristic equation.
chareq, symbol = Integer(0), Dummy('x')
for i in r:
if type(i) == str or i < 0:
pass
else:
chareq += r[i]*symbol**i
chareq = Poly(chareq, symbol)
chareqroots = [RootOf(chareq, k) for k in range(chareq.degree())]
chareq_is_complex = not all(i.is_extended_real for i in chareq.all_coeffs())
# A generator of constants
constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
# Create a dict root: multiplicity or charroots
charroots = defaultdict(int)
for root in chareqroots:
charroots[root] += 1
# We need to keep track of terms so we can run collect() at the end.
# This is necessary for constantsimp to work properly.
global collectterms
collectterms = []
gensols = []
conjugate_roots = [] # used to prevent double-use of conjugate roots
for root, multiplicity in charroots.items():
for i in range(multiplicity):
if isinstance(root, RootOf):
gensols.append(exp(root*x))
if multiplicity != 1:
raise NotImplementedError
# This ordering is important
collectterms = [(0, root, 0)] + collectterms
else:
if chareq_is_complex:
gensols.append(x**i*exp(root*x))
collectterms = [(i, root, 0)] + collectterms
continue
reroot = re(root)
imroot = im(root)
if root in conjugate_roots:
collectterms = [(i, reroot, imroot)] + collectterms
continue
if imroot == 0:
gensols.append(x**i*exp(reroot*x))
collectterms = [(i, reroot, 0)] + collectterms
continue
conjugate_roots.append(conjugate(root))
gensols.append(x**i * exp(reroot*x) * sin(abs(imroot)*x))
gensols.append(x**i * exp(reroot*x) * cos(imroot*x))
# This ordering is important
collectterms = [(i, reroot, imroot)] + collectterms
if returns in ('sol' 'both'):
gsol = Add(*[i*j for (i, j) in zip(constants, gensols)])
if returns == 'sol':
return Eq(f(x), gsol)
else:
return {'sol': Eq(f(x), gsol), 'list': gensols}
else:
raise ValueError('Unknown value for key "returns".')
def ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match):
r"""
Solves an `n`\th order linear differential equation with constant
coefficients using the method of undetermined coefficients.
This method works on differential equations of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = P(x)\text{,}
where `P(x)` is a function that has a finite number of linearly
independent derivatives.
Functions that fit this requirement are finite sums functions of the form
`a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i`
is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For
example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`,
and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have
a finite number of derivatives, because they can be expanded into `\sin(a
x)` and `\cos(b x)` terms. However, Diofant currently cannot do that
expansion, so you will need to manually rewrite the expression in terms of
the above to use this method. So, for example, you will need to manually
convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method
of undetermined coefficients on it.
This method works by creating a trial function from the expression and all
of its linear independent derivatives and substituting them into the
original ODE. The coefficients for each term will be a system of linear
equations, which are be solved for and substituted, giving the solution.
If any of the trial functions are linearly dependent on the solution to
the homogeneous equation, they are multiplied by sufficient `x` to make
them linearly independent.
Examples
========
>>> pprint(dsolve(f(x).diff((x, 2)) + 2*f(x).diff(x) + f(x) -
... 4*exp(-x)*x**2 + cos(2*x), f(x),
... hint='nth_linear_constant_coeff_undetermined_coefficients'),
... use_unicode=False)
/ 4\
4*sin(2*x) 3*cos(2*x) -x | x |
f(x) = - ---------- + ---------- + E *|C1 + C2*x + --|
25 25 \ 3 /
References
==========
* https://en.wikipedia.org/wiki/Method_of_undetermined_coefficients
* :cite:`TenenbaumPollard63`, pp. 221.
"""
gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='both')
match.update(gensol)
return _solve_undetermined_coefficients(eq, func, order, match)
def _solve_undetermined_coefficients(eq, func, order, match):
r"""
Helper function for the method of undetermined coefficients.
See the
:py:meth:`~diofant.solvers.ode.ode_nth_linear_constant_coeff_undetermined_coefficients`
docstring for more information on this method.
The parameter ``match`` should be a dictionary that has the following
keys:
``list``
A list of solutions to the homogeneous equation, such as the list
returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='list')``.
``sol``
The general solution, such as the solution returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``.
``trialset``
The set of trial functions as returned by
``_undetermined_coefficients_match()['trialset']``.
"""
x = func.args[0]
f = func.func
r = match
coeffs = numbered_symbols('a', cls=Dummy)
coefflist = []
gensols = r['list']
gsol = r['sol']
trialset = r['trialset']
notneedset = set()
global collectterms
if len(gensols) != order:
raise NotImplementedError('Cannot find ' + str(order) +
' solutions to the homogeneous equation necessary to apply' +
' undetermined coefficients to ' + str(eq) +
' (number of terms != order)')
usedsin = set()
mult = 0 # The multiplicity of the root
getmult = True
for i, reroot, imroot in collectterms:
if getmult:
mult = i + 1
getmult = False
if i == 0:
getmult = True
if imroot:
# Alternate between sin and cos
if (i, reroot) in usedsin:
check = x**i*exp(reroot*x)*cos(imroot*x)
else:
check = x**i*exp(reroot*x)*sin(abs(imroot)*x)
usedsin.add((i, reroot))
else:
check = x**i*exp(reroot*x)
if check in trialset:
# If an element of the trial function is already part of the
# homogeneous solution, we need to multiply by sufficient x to
# make it linearly independent. We also don't need to bother
# checking for the coefficients on those elements, since we
# already know it will be 0.
while True:
if check*x**mult in trialset:
mult += 1
else:
break
trialset.add(check*x**mult)
notneedset.add(check)
newtrialset = trialset - notneedset
trialfunc = 0
for i in newtrialset:
c = next(coeffs)
coefflist.append(c)
trialfunc += c*i
eqs = sub_func_doit(eq, f(x), trialfunc)
coeffsdict = dict(zip(trialset, [0]*(len(trialset) + 1)))
eqs = _mexpand(eqs)
for i in Add.make_args(eqs):
s = separatevars(i, dict=True, symbols=[x])
coeffsdict[s[x]] += s['coeff']
coeffvals = solve(list(coeffsdict.values()), coefflist)
if not coeffvals:
raise NotImplementedError(
f'Could not solve `{eq}` using the '
'method of undetermined coefficients '
'(unable to solve for coefficients).')
coeffvals = coeffvals[0]
psol = trialfunc.subs(coeffvals)
return Eq(f(x), gsol.rhs + psol)
def _undetermined_coefficients_match(expr, x):
r"""
Returns a trial function match if undetermined coefficients can be applied
to ``expr``, and ``None`` otherwise.
A trial expression can be found for an expression for use with the method
of undetermined coefficients if the expression is an
additive/multiplicative combination of constants, polynomials in `x` (the
independent variable of expr), `\sin(a x + b)`, `\cos(a x + b)`, and
`e^{a x}` terms (in other words, it has a finite number of linearly
independent derivatives).
Note that you may still need to multiply each term returned here by
sufficient `x` to make it linearly independent with the solutions to the
homogeneous equation.
This is intended for internal use by ``undetermined_coefficients`` hints.
Diofant currently has no way to convert `\sin^n(x) \cos^m(y)` into a sum of
only `\sin(a x)` and `\cos(b x)` terms, so these are not implemented. So,
for example, you will need to manually convert `\sin^2(x)` into `[1 +
\cos(2 x)]/2` to properly apply the method of undetermined coefficients on
it.
Examples
========
>>> _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x)
{'test': True, 'trialset': {E**(-x), E**x, E**x*x}}
>>> _undetermined_coefficients_match(log(x), x)
{'test': False}
"""
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
expr = powsimp(expr, combine='exp') # exp(x)*exp(2*x + 1) => exp(3*x + 1)
retdict = {}
def _test_term(expr, x):
r"""
Test if ``expr`` fits the proper form for undetermined coefficients.
"""
if expr.is_Add:
return all(_test_term(i, x) for i in expr.args)
elif expr.is_Mul:
if expr.has(sin, cos):
foundtrig = False
# Make sure that there is only one trig function in the args.
# See the docstring.
for i in expr.args:
if i.has(sin, cos):
if foundtrig:
return False
else:
foundtrig = True
return all(_test_term(i, x) for i in expr.args)
elif expr.is_Function:
if expr.func in (sin, cos, exp):
return bool(expr.args[0].match(a*x + b))
else:
return False
elif expr.is_Pow and expr.base.is_Symbol and expr.exp.is_Integer and \
expr.exp >= 0:
return True
elif expr.is_Pow and expr.base.is_number:
return bool(expr.exp.match(a*x + b))
elif expr.is_Symbol or expr.is_number:
return True
else:
return False
def _get_trial_set(expr, x, exprs=set()):
r"""
Returns a set of trial terms for undetermined coefficients.
The idea behind undetermined coefficients is that the terms expression
repeat themselves after a finite number of derivatives, except for the
coefficients (they are linearly dependent). So if we collect these,
we should have the terms of our trial function.
"""
def _remove_coefficient(expr, x):
r"""
Returns the expression without a coefficient.
Similar to expr.as_independent(x)[1], except it only works
multiplicatively.
"""
term = Integer(1)
if expr.is_Mul:
for i in expr.args:
if i.has(x):
term *= i
elif expr.has(x):
term = expr
return term
expr = expand_mul(expr)
if expr.is_Add:
for term in expr.args:
if _remove_coefficient(term, x) in exprs:
pass
else:
exprs.add(_remove_coefficient(term, x))
exprs = exprs.union(_get_trial_set(term, x, exprs))
else:
term = _remove_coefficient(expr, x)
tmpset = exprs.union({term})
oldset = set()
while tmpset != oldset:
# If you get stuck in this loop, then _test_term is probably
# broken
oldset = tmpset.copy()
expr = expr.diff(x)
term = _remove_coefficient(expr, x)
if term.is_Add:
tmpset = tmpset.union(_get_trial_set(term, x, tmpset))
else:
tmpset.add(term)
exprs = tmpset
return exprs
retdict['test'] = _test_term(expr, x)
if retdict['test']:
# Try to generate a list of trial solutions that will have the
# undetermined coefficients. Note that if any of these are not linearly
# independent with any of the solutions to the homogeneous equation,
# then they will need to be multiplied by sufficient x to make them so.
# This function DOES NOT do that (it doesn't even look at the
# homogeneous equation).
retdict['trialset'] = _get_trial_set(expr, x)
return retdict
def ode_nth_linear_constant_coeff_variation_of_parameters(eq, func, order, match):
r"""
Solves an `n`\th order linear differential equation with constant
coefficients using the method of variation of parameters.
This method works on any differential equations of the form
.. math:: f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0
f(x) = P(x)\text{.}
This method works by assuming that the particular solution takes the form
.. math:: \sum_{x=1}^{n} c_i(x) y_i(x)\text{,}
where `y_i` is the `i`\th solution to the homogeneous equation. The
solution is then solved using Wronskian's and Cramer's Rule. The
particular solution is given by
.. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx
\right) y_i(x) \text{,}
where `W(x)` is the Wronskian of the fundamental system (the system of `n`
linearly independent solutions to the homogeneous equation), and `W_i(x)`
is the Wronskian of the fundamental system with the `i`\th column replaced
with `[0, 0, \cdots, 0, P(x)]`.
This method is general enough to solve any `n`\th order inhomogeneous
linear differential equation with constant coefficients, but sometimes
Diofant cannot simplify the Wronskian well enough to integrate it. If this
method hangs, try using the
``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and
simplifying the integrals manually. Also, prefer using
``nth_linear_constant_coeff_undetermined_coefficients`` when it
applies, because it doesn't use integration, making it faster and more
reliable.
Warning, using simplify=False with
'nth_linear_constant_coeff_variation_of_parameters' in
:py:meth:`~diofant.solvers.ode.dsolve` may cause it to hang, because it will
not attempt to simplify the Wronskian before integrating. It is
recommended that you only use simplify=False with
'nth_linear_constant_coeff_variation_of_parameters_Integral' for this
method, especially if the solution to the homogeneous equation has
trigonometric functions in it.
Examples
========
>>> pprint(dsolve(f(x).diff((x, 3)) - 3*f(x).diff((x, 2)) +
... 3*f(x).diff(x) - f(x) - exp(x)*log(x), f(x),
... hint='nth_linear_constant_coeff_variation_of_parameters'),
... use_unicode=False)
/ 3 \
x | 2 x *(6*log(x) - 11)|
f(x) = E *|C1 + C2*x + C3*x + ------------------|
\ 36 /
References
==========
* https://en.wikipedia.org/wiki/Variation_of_parameters
* :cite:`TenenbaumPollard63`, pp. 233.
"""
gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='both')
match.update(gensol)
return _solve_variation_of_parameters(eq, func, order, match)
def _solve_variation_of_parameters(eq, func, order, match):
r"""
Helper function for the method of variation of parameters and nonhomogeneous euler eq.
See the
:py:meth:`~diofant.solvers.ode.ode_nth_linear_constant_coeff_variation_of_parameters`
docstring for more information on this method.
The parameter ``match`` should be a dictionary that has the following
keys:
``list``
A list of solutions to the homogeneous equation, such as the list
returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='list')``.
``sol``
The general solution, such as the solution returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``.
"""
x = func.args[0]
f = func.func
r = match
psol = 0
gensols = r['list']
gsol = r['sol']
wr = wronskian(gensols, x)
if r.get('simplify', True):
# We need much better simplification for
# some ODEs. See issue sympy/sympy#4662, for example.
wr = simplify(wr)
# To reduce commonly occuring sin(x)**2 + cos(x)**2 to 1
wr = trigsimp(wr, deep=True, recursive=True)
if not wr:
# The wronskian will be 0 iff the solutions are not linearly
# independent.
raise NotImplementedError('Cannot find ' + str(order) +
' solutions to the homogeneous equation nessesary to apply ' +
'variation of parameters to ' + str(eq) + ' (Wronskian == 0)')
if len(gensols) != order:
raise NotImplementedError('Cannot find ' + str(order) +
' solutions to the homogeneous equation nessesary to apply ' +
'variation of parameters to ' +
str(eq) + ' (number of terms != order)')
negoneterm = (-1)**(order)
for i in gensols:
psol += negoneterm*Integral(wronskian([sol for sol in gensols if sol != i], x)*r[-1]/wr, x)*i/r[order]
negoneterm *= -1
if r.get('simplify', True):
psol = simplify(psol)
psol = trigsimp(psol, deep=True)
return Eq(f(x), gsol.rhs + psol)
def ode_separable(eq, func, order, match):
r"""
Solves separable 1st order differential equations.
This is any differential equation that can be written as `P(y)
\tfrac{dy}{dx} = Q(x)`. The solution can then just be found by
rearranging terms and integrating: `\int P(y) \,dy = \int Q(x) \,dx`.
This hint uses :py:meth:`diofant.simplify.simplify.separatevars` as its back
end, so if a separable equation is not caught by this solver, it is most
likely the fault of that function.
:py:meth:`~diofant.simplify.simplify.separatevars` is
smart enough to do most expansion and factoring necessary to convert a
separable equation `F(x, y)` into the proper form `P(x)\cdot{}Q(y)`. The
general solution is::
>>> a, b, c, d = map(Function, ['a', 'b', 'c', 'd'])
>>> genform = Eq(a(x)*b(f(x))*f(x).diff(x), c(x)*d(f(x)))
>>> pprint(genform, use_unicode=False)
d
a(x)*b(f(x))*--(f(x)) = c(x)*d(f(x))
dx
>>> pprint(dsolve(genform, f(x),
... hint='separable_Integral'), use_unicode=False)
f(x)
/ /
| |
| b(y) | c(x)
| ---- dy = C1 + | ---- dx
| d(y) | a(x)
| |
/ /
Examples
========
>>> pprint(dsolve(Eq(f(x)*f(x).diff(x) + x, 3*x*f(x)**2), f(x),
... hint='separable', simplify=False), use_unicode=False)
/ 2 \ 2
log\3*f (x) - 1/ x
---------------- = C1 + --
6 2
References
==========
* :cite:`TenenbaumPollard63`, pp. 52.
"""
x = func.args[0]
f = func.func
C1 = get_numbered_constants(eq, num=1)
r = match # {'m1':m1, 'm2':m2, 'y':y}
u = r.get('hint', f(x)) # get u from separable_reduced else get f(x)
return Eq(Integral(r['m2']['coeff']*r['m2'][r['y']]/r['m1'][r['y']],
(r['y'], None, u)), Integral(-r['m1']['coeff']*r['m1'][x] /
r['m2'][x], x) + C1)
def checkinfsol(eq, infinitesimals, func=None, order=None):
r"""
This function is used to check if the given infinitesimals are the
actual infinitesimals of the given first order differential equation.
This method is specific to the Lie Group Solver of ODEs.
As of now, it simply checks, by substituting the infinitesimals in the
partial differential equation.
.. math:: \frac{\partial \eta}{\partial x} + \left(\frac{\partial \eta}{\partial y}
- \frac{\partial \xi}{\partial x}\right)*h
- \frac{\partial \xi}{\partial y}*h^{2}
- \xi\frac{\partial h}{\partial x} - \eta\frac{\partial h}{\partial y} = 0
where `\eta`, and `\xi` are the infinitesimals and `h(x,y) = \frac{dy}{dx}`
The infinitesimals should be given in the form of a list of dicts
``[{xi(x, y): inf, eta(x, y): inf}]``, corresponding to the
output of the function infinitesimals. It returns a list
of values of the form ``[(True/False, sol)]`` where ``sol`` is the value
obtained after substituting the infinitesimals in the PDE. If it
is ``True``, then ``sol`` would be 0.
"""
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
if not func:
eq, func = _preprocess(eq)
variables = func.args
if len(variables) != 1:
raise ValueError("ODE's have only one independent variable")
x = variables[0]
if not order:
order = ode_order(eq, func)
if order != 1:
raise NotImplementedError('Lie groups solver has been implemented '
'only for first order differential equations')
df = func.diff(x)
a = Wild('a', exclude=[df])
b = Wild('b', exclude=[df])
match = collect(expand(eq), df).match(a*df + b)
if match:
h = -simplify(match[b]/match[a])
else:
try:
sol = solve(eq, df)
except NotImplementedError as exc:
raise NotImplementedError('Infinitesimals for the '
'first order ODE could '
'not be found') from exc
else:
h = sol[0][df] # Find infinitesimals for one solution
y = Dummy('y')
h = h.subs({func: y})
xi = Function('xi')(x, y)
eta = Function('eta')(x, y)
dxi = Function('xi')(x, func)
deta = Function('eta')(x, func)
pde = (eta.diff(x) + (eta.diff(y) - xi.diff(x))*h -
(xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)))
soltup = []
for sol in infinitesimals:
tsol = {xi: sol[dxi].subs({func: y}),
eta: sol[deta].subs({func: y})}
sol = simplify(pde.subs(tsol).doit())
if sol:
soltup.append((False, sol.subs({y: func})))
else:
soltup.append((True, 0))
return soltup
def ode_lie_group(eq, func, order, match):
r"""
This hint implements the Lie group method of solving first order differential
equations. The aim is to convert the given differential equation from the
given coordinate given system into another coordinate system where it becomes
invariant under the one-parameter Lie group of translations. The converted ODE is
quadrature and can be solved easily. It makes use of the
:py:meth:`diofant.solvers.ode.infinitesimals` function which returns the
infinitesimals of the transformation.
The coordinates `r` and `s` can be found by solving the following Partial
Differential Equations.
.. math :: \xi\frac{\partial r}{\partial x} + \eta\frac{\partial r}{\partial y}
= 0
.. math :: \xi\frac{\partial s}{\partial x} + \eta\frac{\partial s}{\partial y}
= 1
The differential equation becomes separable in the new coordinate system
.. math :: \frac{ds}{dr} = \frac{\frac{\partial s}{\partial x} +
h(x, y)\frac{\partial s}{\partial y}}{
\frac{\partial r}{\partial x} + h(x, y)\frac{\partial r}{\partial y}}
After finding the solution by integration, it is then converted back to the original
coordinate system by subsituting `r` and `s` in terms of `x` and `y` again.
Examples
========
>>> pprint(dsolve(f(x).diff(x) + 2*x*f(x) - x*exp(-x**2), f(x),
... hint='lie_group'), use_unicode=False)
2 / 2\
-x | x |
f(x) = E *|C1 + --|
\ 2 /
References
==========
* Solving differential equations by Symmetry Groups,
John Starrett, pp. 1-14.
"""
heuristics = lie_heuristics
inf = {}
f = func.func
x = func.args[0]
df = func.diff(x)
xi = Function('xi')
eta = Function('eta')
xis = match.pop('xi')
etas = match.pop('eta')
if match:
h = -simplify(match[match['d']]/match[match['e']])
y = match['y']
else:
try:
sol = solve(eq, df)
except NotImplementedError as exc:
raise NotImplementedError('Unable to solve the differential '
'equation ' + str(eq) +
' by the lie group method') from exc
else:
if len(sol) > 1:
return [dsolve(df - _[df], func) for _ in sol]
y = Dummy('y')
h = sol[0][df].subs({func: y})
if xis is not None and etas is not None:
inf = [{xi(x, f(x)): sympify(xis), eta(x, f(x)): sympify(etas)}]
if not checkinfsol(eq, inf, func=f(x), order=1)[0][0]:
raise ValueError('The given infinitesimals xi and eta'
' are not the infinitesimals to the given equation')
heuristics = ['user_defined']
match = {'h': h, 'y': y}
# This is done so that if:
# a] solve raises a NotImplementedError.
# b] any heuristic raises a ValueError
# another heuristic can be used.
for heuristic in heuristics:
if heuristic != 'user_defined':
try:
inf = infinitesimals(eq, hint=heuristic, func=func,
order=1, match=match)
except ValueError:
continue
for infsim in inf:
xiinf = (infsim[xi(x, func)]).subs({func: y})
etainf = (infsim[eta(x, func)]).subs({func: y})
# This condition creates recursion while using pdsolve.
# Since the first step while solving a PDE of form
# a*(f(x, y).diff(x)) + b*(f(x, y).diff(y)) + c = 0
# is to solve the ODE dy/dx = b/a
if simplify(etainf/xiinf) == h:
continue
rpde = f(x, y).diff(x)*xiinf + f(x, y).diff(y)*etainf
r = pdsolve(rpde, func=f(x, y)).rhs
s = pdsolve(rpde - 1, func=f(x, y)).rhs
newcoord = [_lie_group_remove(coord) for coord in [r, s]]
r = Dummy('r')
s = Dummy('s')
C1 = Symbol('C1')
rcoord = newcoord[0]
scoord = newcoord[-1]
try:
sol = solve([r - rcoord, s - scoord], x, y)
except NotImplementedError:
continue
else:
sol = sol[0]
xsub = sol[x]
ysub = sol[y]
num = simplify(scoord.diff(x) + scoord.diff(y)*h)
denom = simplify(rcoord.diff(x) + rcoord.diff(y)*h)
if num and denom:
diffeq = simplify((num/denom).subs({x: xsub, y: ysub}))
sep = separatevars(diffeq, symbols=[r, s], dict=True)
if sep:
# Trying to separate, r and s coordinates
deq = integrate((1/sep[s]), s) + C1 - integrate(sep['coeff']*sep[r], r)
# Substituting and reverting back to original coordinates
deq = deq.subs({r: rcoord, s: scoord})
try:
sdeq = solve(deq, y)
except NotImplementedError:
continue
else:
if len(sdeq) == 1:
return Eq(f(x), sdeq[0][y])
else:
return [Eq(f(x), sol[y]) for sol in sdeq]
elif denom: # (ds/dr) is zero which means s is constant
return Eq(f(x), solve(scoord - C1, y)[0][y])
else:
raise NotImplementedError
raise NotImplementedError(f'The given ODE {eq!s}'
' cannot be solved by the lie group method')
def _lie_group_remove(coords):
r"""
This function is strictly meant for internal use by the Lie group ODE solving
method. It replaces arbitrary functions returned by pdsolve with either 0 or 1 or the
args of the arbitrary function.
The algorithm used is:
1] If coords is an instance of an Undefined Function, then the args are returned
2] If the arbitrary function is present in an Add object, it is replaced by zero.
3] If the arbitrary function is present in an Mul object, it is replaced by one.
4] If coords has no Undefined Function, it is returned as it is.
Examples
========
>>> eq = x**2*y
>>> _lie_group_remove(eq)
x**2*y
>>> eq = f(x**2*y)
>>> _lie_group_remove(eq)
x**2*y
>>> eq = y**2*x + f(x**3)
>>> _lie_group_remove(eq)
x*y**2
>>> eq = (f(x**3) + y)*x**4
>>> _lie_group_remove(eq)
x**4*y
"""
if isinstance(coords, AppliedUndef):
return coords.args[0]
elif coords.is_Add:
subfunc = coords.atoms(AppliedUndef)
if subfunc:
for func in subfunc:
coords = coords.subs({func: 0})
return coords
elif coords.is_Pow:
base, expr = coords.as_base_exp()
base = _lie_group_remove(base)
expr = _lie_group_remove(expr)
return base**expr
elif coords.is_Mul:
mulargs = []
coordargs = coords.args
for arg in coordargs:
if not isinstance(coords, AppliedUndef):
mulargs.append(_lie_group_remove(arg))
return Mul(*mulargs)
return coords
def infinitesimals(eq, func=None, order=None, hint='default', match=None):
r"""
The infinitesimal functions of an ordinary differential equation, `\xi(x,y)`
and `\eta(x,y)`, are the infinitesimals of the Lie group of point transformations
for which the differential equation is invariant. So, the ODE `y'=f(x,y)`
would admit a Lie group `x^*=X(x,y;\varepsilon)=x+\varepsilon\xi(x,y)`,
`y^*=Y(x,y;\varepsilon)=y+\varepsilon\eta(x,y)` such that `(y^*)'=f(x^*, y^*)`.
A change of coordinates, to `r(x,y)` and `s(x,y)`, can be performed so this Lie group
becomes the translation group, `r^*=r` and `s^*=s+\varepsilon`.
They are tangents to the coordinate curves of the new system.
Consider the transformation `(x, y) \to (X, Y)` such that the
differential equation remains invariant. `\xi` and `\eta` are the tangents to
the transformed coordinates `X` and `Y`, at `\varepsilon=0`.
.. math:: \left(\frac{\partial X(x,y;\varepsilon)}{\partial\varepsilon
}\right)|_{\varepsilon=0} = \xi,
\left(\frac{\partial Y(x,y;\varepsilon)}{\partial\varepsilon
}\right)|_{\varepsilon=0} = \eta,
The infinitesimals can be found by solving the following PDE:
>>> xi, eta = map(Function, ['xi', 'eta'])
>>> h = h(x, y) # dy/dx = h
>>> eta = eta(x, y)
>>> xi = xi(x, y)
>>> genform = Eq(eta.diff(x) + (eta.diff(y) - xi.diff(x))*h -
... (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)), 0)
>>> pprint(genform, use_unicode=False)
d 2 d /d d
- eta(x, y)*--(h(x, y)) - h (x, y)*--(xi(x, y)) + h(x, y)*|--(eta(x, y)) - --(
dy dy \dy dx
<BLANKLINE>
\ d d
xi(x, y))| - xi(x, y)*--(h(x, y)) + --(eta(x, y)) = 0
/ dx dx
Solving the above mentioned PDE is not trivial, and can be solved only by
making intelligent assumptions for `\xi` and `\eta` (heuristics). Once an
infinitesimal is found, the attempt to find more heuristics stops. This is done to
optimise the speed of solving the differential equation. If a list of all the
infinitesimals is needed, ``hint`` should be flagged as ``all``, which gives
the complete list of infinitesimals. If the infinitesimals for a particular
heuristic needs to be found, it can be passed as a flag to ``hint``.
Examples
========
>>> eta = Function('eta')
>>> xi = Function('xi')
>>> eq = f(x).diff(x) - x**2*f(x)
>>> infinitesimals(eq)
[{eta(x, f(x)): E**(x**3/3), xi(x, f(x)): 0}]
References
==========
- Solving differential equations by Symmetry Groups,
John Starrett, pp. 1 - pp. 14
"""
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
if not func:
eq, func = _preprocess(eq)
variables = func.args
if len(variables) != 1:
raise ValueError("ODE's have only one independent variable")
x = variables[0]
if not order:
order = ode_order(eq, func)
if order != 1:
raise NotImplementedError('Infinitesimals for only '
"first order ODE's have been implemented")
df = func.diff(x)
# Matching differential equation of the form a*df + b
a = Wild('a', exclude=[df])
b = Wild('b', exclude=[df])
if match: # Used by lie_group hint
h = match['h']
y = match['y']
else:
match = collect(expand(eq), df).match(a*df + b)
if match:
h = -simplify(match[b]/match[a])
else:
try:
sol = solve(eq, df)
except NotImplementedError as exc:
raise NotImplementedError('Infinitesimals for the '
'first order ODE could not '
'be found') from exc
else:
h = sol[0][df] # Find infinitesimals for one solution
y = Dummy('y')
h = h.subs({func: y})
u = Dummy('u')
hx = h.diff(x)
hy = h.diff(y)
hinv = ((1/h).subs([(x, u), (y, x)])).subs({u: y}) # Inverse ODE
match = {'h': h, 'func': func, 'hx': hx, 'hy': hy, 'y': y, 'hinv': hinv}
if hint == 'all':
xieta = []
for heuristic in lie_heuristics:
function = globals()['lie_heuristic_' + heuristic]
inflist = function(match, comp=True)
if inflist:
xieta.extend([inf for inf in inflist if inf not in xieta])
if xieta:
return xieta
else:
raise NotImplementedError('Infinitesimals could not be found for '
'the given ODE')
elif hint == 'default':
for heuristic in lie_heuristics:
function = globals()['lie_heuristic_' + heuristic]
xieta = function(match, comp=False)
if xieta:
return xieta
raise NotImplementedError('Infinitesimals could not be found for'
' the given ODE')
elif hint not in lie_heuristics:
raise ValueError('Heuristic not recognized: ' + hint)
else:
function = globals()['lie_heuristic_' + hint]
xieta = function(match, comp=True)
if xieta:
return xieta
else:
raise ValueError('Infinitesimals could not be found using the'
' given heuristic')
def lie_heuristic_abaco1_simple(match, comp):
r"""
The first heuristic uses the following four sets of
assumptions on `\xi` and `\eta`
.. math:: \xi = 0, \eta = f(x)
.. math:: \xi = 0, \eta = f(y)
.. math:: \xi = f(x), \eta = 0
.. math:: \xi = f(y), \eta = 0
The success of this heuristic is determined by algebraic factorisation.
For the first assumption `\xi = 0` and `\eta` to be a function of `x`, the PDE
.. math:: \frac{\partial \eta}{\partial x} + (\frac{\partial \eta}{\partial y}
- \frac{\partial \xi}{\partial x})*h
- \frac{\partial \xi}{\partial y}*h^{2}
- \xi*\frac{\partial h}{\partial x} - \eta*\frac{\partial h}{\partial y} = 0
reduces to `f'(x) - f\frac{\partial h}{\partial y} = 0`
If `\frac{\partial h}{\partial y}` is a function of `x`, then this can usually
be integrated easily. A similar idea is applied to the other 3 assumptions as well.
References
==========
- E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
Solving of First Order ODEs Using Symmetry Methods, pp. 8
"""
xieta = []
y = match['y']
h = match['h']
func = match['func']
x = func.args[0]
hx = match['hx']
hy = match['hy']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
hysym = hy.free_symbols
if y not in hysym:
try:
fx = exp(integrate(hy, x))
except NotImplementedError:
pass
else:
inf = {xi: Integer(0), eta: fx}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = hy/h
facsym = factor.free_symbols
if x not in facsym:
try:
fy = exp(integrate(factor, y))
except NotImplementedError:
pass
else:
inf = {xi: Integer(0), eta: fy.subs({y: func})}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = -hx/h
facsym = factor.free_symbols
if y not in facsym:
try:
fx = exp(integrate(factor, x))
except NotImplementedError:
pass
else:
inf = {xi: fx, eta: Integer(0)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = -hx/(h**2)
facsym = factor.free_symbols
if x not in facsym:
try:
fy = exp(integrate(factor, y))
except NotImplementedError:
pass
else:
inf = {xi: fy.subs({y: func}), eta: Integer(0)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_abaco1_product(match, comp):
r"""
The second heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = 0, \xi = f(x)*g(y)
.. math:: \eta = f(x)*g(y), \xi = 0
The first assumption of this heuristic holds good if
`\frac{1}{h^{2}}\frac{\partial^2}{\partial x \partial y}\log(h)` is
separable in `x` and `y`, then the separated factors containing `x`
is `f(x)`, and `g(y)` is obtained by
.. math:: e^{\int f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)\,dy}
provided `f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)` is a function
of `y` only.
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
satisifes. After obtaining `f(x)` and `g(y)`, the coordinates are again
interchanged, to get `\eta` as `f(x)*g(y)`
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 7 - pp. 8
"""
xieta = []
y = match['y']
hinv = match['hinv']
func = match['func']
x = func.args[0]
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
u1 = Dummy('u1')
inf = separatevars(((log(hinv).diff(y)).diff(x))/hinv**2, dict=True, symbols=[x, y])
if inf and inf['coeff']:
fx = inf[x]
gy = simplify(fx*((1/(fx*hinv)).diff(x)))
gysyms = gy.free_symbols
if x not in gysyms:
gy = exp(integrate(gy, y))
etaval = fx*gy
etaval = (etaval.subs([(x, u1), (y, x)])).subs({u1: y})
inf = {eta: etaval.subs({y: func}), xi: Integer(0)}
if not comp:
return [inf]
elif inf not in xieta:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_bivariate(match, comp):
r"""
The third heuristic assumes the infinitesimals `\xi` and `\eta`
to be bi-variate polynomials in `x` and `y`. The assumption made here
for the logic below is that `h` is a rational function in `x` and `y`
though that may not be necessary for the infinitesimals to be
bivariate polynomials. The coefficients of the infinitesimals
are found out by substituting them in the PDE and grouping similar terms
that are polynomials and since they form a linear system, solve and check
for non trivial solutions. The degree of the assumed bivariates
are increased till a certain maximum value.
References
==========
- Lie Groups and Differential Equations
pp. 327 - pp. 329
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
if h.is_rational_function():
# The maximum degree that the infinitesimals can take is
# calculated by this technique.
etax, etay, etad, xix, xiy, xid = symbols('etax etay etad xix xiy xid')
ipde = etax + (etay - xix)*h - xiy*h**2 - xid*hx - etad*hy
num, _ = cancel(ipde).as_numer_denom()
deg = Poly(num, x, y).total_degree()
deta = Function('deta')(x, y)
dxi = Function('dxi')(x, y)
ipde = (deta.diff(x) + (deta.diff(y) - dxi.diff(x))*h - (dxi.diff(y))*h**2
- dxi*hx - deta*hy)
xieq = Symbol('xi0')
etaeq = Symbol('eta0')
for i in range(deg + 1): # pragma: no branch
if i:
xieq += Add(*[
Symbol('xi_' + str(power) + '_' + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
etaeq += Add(*[
Symbol('eta_' + str(power) + '_' + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
pden, _ = (ipde.subs({dxi: xieq, deta: etaeq}).doit()).as_numer_denom()
pden = expand(pden)
# If the individual terms are monomials, the coefficients
# are grouped
polyy = Poly(pden, x, y).as_dict()
symset = xieq.free_symbols.union(etaeq.free_symbols) - {x, y}
soldict = solve(polyy.values(), *symset)
soldict = soldict[0]
if any(x for x in soldict.values()):
xired = xieq.subs(soldict)
etared = etaeq.subs(soldict)
# Scaling is done by substituting one for the parameters
# This can be any number except zero.
dict_ = {sym: 1 for sym in symset}
inf = {eta: etared.subs(dict_).subs({y: func}),
xi: xired.subs(dict_).subs({y: func})}
return [inf]
def lie_heuristic_chi(match, comp):
r"""
The aim of the fourth heuristic is to find the function `\chi(x, y)`
that satisifies the PDE `\frac{d\chi}{dx} + h\frac{d\chi}{dx}
- \frac{\partial h}{\partial y}\chi = 0`.
This assumes `\chi` to be a bivariate polynomial in `x` and `y`. By intuition,
`h` should be a rational function in `x` and `y`. The method used here is
to substitute a general binomial for `\chi` up to a certain maximum degree
is reached. The coefficients of the polynomials, are calculated by by collecting
terms of the same order in `x` and `y`.
After finding `\chi`, the next step is to use `\eta = \xi*h + \chi`, to
determine `\xi` and `\eta`. This can be done by dividing `\chi` by `h`
which would give `-\xi` as the quotient and `\eta` as the remainder.
References
==========
- E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
Solving of First Order ODEs Using Symmetry Methods, pp. 8
"""
h = match['h']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
if h.is_rational_function():
schi, schix, schiy = symbols('schi, schix, schiy')
cpde = schix + h*schiy - hy*schi
num, _ = cancel(cpde).as_numer_denom()
deg = Poly(num, x, y).total_degree()
chi = Function('chi')(x, y)
chix = chi.diff(x)
chiy = chi.diff(y)
cpde = chix + h*chiy - hy*chi
chieq = Symbol('chi')
for i in range(1, deg + 1): # pragma: no cover
chieq += Add(*[
Symbol('chi_' + str(power) + '_' + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
cnum, _ = cancel(cpde.subs({chi: chieq}).doit()).as_numer_denom()
cnum = expand(cnum)
cpoly = Poly(cnum, x, y).as_dict()
solsyms = chieq.free_symbols - {x, y}
soldict = solve(cpoly.values(), *solsyms)
soldict = soldict[0]
if any(x for x in soldict.values()):
chieq = chieq.subs(soldict)
dict_ = {sym: 1 for sym in solsyms}
chieq = chieq.subs(dict_)
# After finding chi, the main aim is to find out
# eta, xi by the equation eta = xi*h + chi
# One method to set xi, would be rearranging it to
# (eta/h) - xi = (chi/h). This would mean dividing
# chi by h would give -xi as the quotient and eta
# as the remainder. Thanks to Sean Vig for suggesting
# this method.
xic, etac = div(chieq, h)
inf = {eta: etac.subs({y: func}), xi: -xic.subs({y: func})}
return [inf]
def lie_heuristic_function_sum(match, comp):
r"""
This heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = 0, \xi = f(x) + g(y)
.. math:: \eta = f(x) + g(y), \xi = 0
The first assumption of this heuristic holds good if
.. math:: \frac{\partial}{\partial y}[(h\frac{\partial^{2}}{
\partial x^{2}}(h^{-1}))^{-1}]
is separable in `x` and `y`,
1. The separated factors containing `y` is `\frac{\partial g}{\partial y}`.
From this `g(y)` can be determined.
2. The separated factors containing `x` is `f''(x)`.
3. `h\frac{\partial^{2}}{\partial x^{2}}(h^{-1})` equals
`\frac{f''(x)}{f(x) + g(y)}`. From this `f(x)` can be determined.
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first
assumption satisifes. After obtaining `f(x)` and `g(y)`, the coordinates
are again interchanged, to get `\eta` as `f(x) + g(y)`.
For both assumptions, the constant factors are separated among `g(y)`
and `f''(x)`, such that `f''(x)` obtained from 3] is the same as that
obtained from 2]. If not possible, then this heuristic fails.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 7 - pp. 8
"""
xieta = []
h = match['h']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
for odefac in [h, hinv]:
factor = odefac*((1/odefac).diff((x, 2)))
sep = separatevars((1/factor).diff(y), dict=True, symbols=[x, y])
if sep and sep['coeff'] and sep[x].has(x) and sep[y].has(y):
k = Dummy('k')
try:
gy = k*integrate(sep[y], y)
except NotImplementedError:
pass
else:
fdd = 1/(k*sep[x]*sep['coeff'])
fx = simplify(fdd/factor - gy)
check = simplify(fx.diff((x, 2)) - fdd)
if fx:
if not check:
fx = fx.subs({k: 1})
gy = (gy/k)
else:
raise NotImplementedError
if odefac == hinv: # Inverse ODE
fx = fx.subs({x: y})
gy = gy.subs({y: x})
etaval = factor_terms(fx + gy)
if etaval.is_Mul:
etaval = Mul(*[arg for arg in etaval.args if arg.has(x, y)])
if odefac == hinv: # Inverse ODE
inf = {eta: etaval.subs({y: func}), xi: Integer(0)}
else:
inf = {xi: etaval.subs({y: func}), eta: Integer(0)}
if not comp:
return [inf]
else:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_abaco2_similar(match, comp):
r"""
This heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = g(x), \xi = f(x)
.. math:: \eta = f(y), \xi = g(y)
For the first assumption,
1. First `\frac{\frac{\partial h}{\partial y}}{\frac{\partial^{2} h}{
\partial yy}}` is calculated. Let us say this value is A
2. If this is constant, then `h` is matched to the form `A(x) + B(x)e^{
\frac{y}{C}}` then, `\frac{e^{\int \frac{A(x)}{C} \,dx}}{B(x)}` gives `f(x)`
and `A(x)*f(x)` gives `g(x)`
3. Otherwise `\frac{\frac{\partial A}{\partial X}}{\frac{\partial A}{
\partial Y}} = \gamma` is calculated. If
a] `\gamma` is a function of `x` alone
b] `\frac{\gamma\frac{\partial h}{\partial y} - \gamma'(x) - \frac{
\partial h}{\partial x}}{h + \gamma} = G` is a function of `x` alone.
then, `e^{\int G \,dx}` gives `f(x)` and `-\gamma*f(x)` gives `g(x)`
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
satisifes. After obtaining `f(x)` and `g(x)`, the coordinates are again
interchanged, to get `\xi` as `f(x^*)` and `\eta` as `g(y^*)`
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
factor = cancel(h.diff(y)/h.diff((y, 2)))
factorx = factor.diff(x)
factory = factor.diff(y)
if not factor.has(x) and not factor.has(y):
A = Wild('A', exclude=[y])
B = Wild('B', exclude=[y])
C = Wild('C', exclude=[x, y])
match = h.match(A + B*exp(y/C))
try:
tau = exp(-integrate(match[A]/match[C], x))/match[B]
except NotImplementedError:
pass
else:
gx = match[A]*tau
return [{xi: tau, eta: gx}]
else:
gamma = cancel(factorx/factory)
if not gamma.has(y):
tauint = cancel((gamma*hy - gamma.diff(x) - hx)/(h + gamma))
if not tauint.has(y):
try:
tau = exp(integrate(tauint, x))
except NotImplementedError:
pass
else:
gx = -tau*gamma
return [{xi: tau, eta: gx}]
factor = cancel(hinv.diff(y)/hinv.diff((y, 2)))
factorx = factor.diff(x)
factory = factor.diff(y)
if not factor.has(x) and not factor.has(y):
A = Wild('A', exclude=[y])
B = Wild('B', exclude=[y])
C = Wild('C', exclude=[x, y])
match = hinv.match(A + B*exp(y/C))
try:
tau = exp(-integrate(match[A]/match[C], x))/match[B]
except NotImplementedError:
pass
else:
gx = match[A]*tau
return [{eta: tau.subs({x: func}), xi: gx.subs({x: func})}]
else:
gamma = cancel(factorx/factory)
if not gamma.has(y):
tauint = cancel((gamma*hinv.diff(y) - gamma.diff(x) - hinv.diff(x))/(
hinv + gamma))
if not tauint.has(y):
try:
tau = exp(integrate(tauint, x))
except NotImplementedError:
pass
else:
gx = -tau*gamma
return [{eta: tau.subs({x: func}), xi: gx.subs({x: func})}]
def lie_heuristic_abaco2_unique_unknown(match, comp):
r"""
This heuristic assumes the presence of unknown functions or known functions
with non-integer powers.
1. A list of all functions and non-integer powers containing x and y
2. Loop over each element `f` in the list, find `\frac{\frac{\partial f}{\partial x}}{
\frac{\partial f}{\partial x}} = R`
If it is separable in `x` and `y`, let `X` be the factors containing `x`. Then
a] Check if `\xi = X` and `\eta = -\frac{X}{R}` satisfy the PDE. If yes, then return
`\xi` and `\eta`
b] Check if `\xi = \frac{-R}{X}` and `\eta = -\frac{1}{X}` satisfy the PDE.
If yes, then return `\xi` and `\eta`
If not, then check if
a] `\xi = -R,\eta = 1`
b] `\xi = 1, \eta = -\frac{1}{R}`
are solutions.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
funclist = []
for atom in h.atoms(Pow):
base, exp = atom.as_base_exp()
if base.has(x) and base.has(y):
if not exp.is_Integer:
funclist.append(atom)
for function in h.atoms(AppliedUndef):
syms = function.free_symbols
if x in syms and y in syms:
funclist.append(function)
for f in funclist:
frac = cancel(f.diff(y)/f.diff(x))
sep = separatevars(frac, dict=True, symbols=[x, y])
if sep and sep['coeff']:
xitry1 = sep[x]
etatry1 = -1/(sep[y]*sep['coeff'])
pde1 = etatry1.diff(y)*h - xitry1.diff(x)*h - xitry1*hx - etatry1*hy
if not simplify(pde1):
return [{xi: xitry1, eta: etatry1.subs({y: func})}]
xitry2 = 1/etatry1
etatry2 = 1/xitry1
pde2 = etatry2.diff(x) - (xitry2.diff(y))*h**2 - xitry2*hx - etatry2*hy
if not simplify(expand(pde2)):
return [{xi: xitry2.subs({y: func}), eta: etatry2}]
else:
etatry = -1/frac
pde = etatry.diff(x) + etatry.diff(y)*h - hx - etatry*hy
if not simplify(pde):
return [{xi: Integer(1), eta: etatry.subs({y: func})}]
xitry = -frac
pde = -xitry.diff(x)*h - xitry.diff(y)*h**2 - xitry*hx - hy
if not simplify(expand(pde)):
return [{xi: xitry.subs({y: func}), eta: Integer(1)}]
def lie_heuristic_linear(match, comp):
r"""
This heuristic assumes
1. `\xi = ax + by + c` and
2. `\eta = fx + gy + h`
After substituting the following assumptions in the determining PDE, it
reduces to
.. math:: f + (g - a)h - bh^{2} - (ax + by + c)\frac{\partial h}{\partial x}
- (fx + gy + c)\frac{\partial h}{\partial y}
Solving the reduced PDE obtained, using the method of characteristics, becomes
impractical. The method followed is grouping similar terms and solving the system
of linear equations obtained. The difference between the bivariate heuristic is that
`h` need not be a rational function in this case.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
coeffdict = defaultdict(int)
symbols = numbered_symbols('c', cls=Dummy)
symlist = [next(symbols) for _ in islice(symbols, 6)]
C0, C1, C2, C3, C4, C5 = symlist
pde = C3 + (C4 - C0)*h - (C0*x + C1*y + C2)*hx - (C3*x + C4*y + C5)*hy - C1*h**2
pde, _ = pde.as_numer_denom()
pde = powsimp(expand(pde))
if pde.is_Add:
terms = pde.args
for term in terms:
if term.is_Mul:
rem = Mul(*[m for m in term.args if not m.has(x, y)])
xypart = term/rem
coeffdict[xypart] += rem
else:
coeffdict[term] += 1
sollist = coeffdict.values()
soldict = solve(sollist, symlist)
if soldict:
soldict = soldict[0]
subval = soldict.values()
if any(t for t in subval):
onedict = dict(zip(symlist, [1]*6))
xival = C0*x + C1*func + C2
etaval = C3*x + C4*func + C5
xival = xival.subs(soldict)
etaval = etaval.subs(soldict)
xival = xival.subs(onedict)
etaval = etaval.subs(onedict)
return [{xi: xival, eta: etaval}]
def sysode_linear_2eq_order1(match_):
x = match_['func'][0].func
y = match_['func'][1].func
func = match_['func']
fc = match_['func_coeff']
eq = match_['eq']
r = {}
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i, func[i], 1]
eq[i] = eqs
# for equations Eq(a1*diff(x(t),t), a*x(t) + b*y(t) + k1)
# and Eq(a2*diff(x(t),t), c*x(t) + d*y(t) + k2)
r['a'] = -fc[0, x(t), 0]/fc[0, x(t), 1]
r['c'] = -fc[1, x(t), 0]/fc[1, y(t), 1]
r['b'] = -fc[0, y(t), 0]/fc[0, x(t), 1]
r['d'] = -fc[1, y(t), 0]/fc[1, y(t), 1]
if match_['type_of_equation'] == 'type3':
sol = _linear_2eq_order1_type3(x, y, t, r, eq)
if match_['type_of_equation'] == 'type4':
sol = _linear_2eq_order1_type4(x, y, t, r, eq)
if match_['type_of_equation'] == 'type5':
sol = _linear_2eq_order1_type5(x, y, t, r, eq)
if match_['type_of_equation'] == 'type6':
sol = _linear_2eq_order1_type6(x, y, t, r, eq)
if match_['type_of_equation'] == 'type7':
sol = _linear_2eq_order1_type7(x, y, t, r, eq)
return sol
def _linear_2eq_order1_type3(x, y, t, r, eq):
r"""
The equations of this type of ode are
.. math:: x' = f(t) x + g(t) y
.. math:: y' = g(t) x + f(t) y
The solution of such equations is given by
.. math:: x = e^{F} (C_1 e^{G} + C_2 e^{-G}) , y = e^{F} (C_1 e^{G} - C_2 e^{-G})
where `C_1` and `C_2` are arbitrary constants, and
.. math:: F = \int f(t) \,dt , G = \int g(t) \,dt
"""
C1, C2 = get_numbered_constants(eq, num=2)
F = Integral(r['a'], t)
G = Integral(r['b'], t)
sol1 = exp(F)*(C1*exp(G) + C2*exp(-G))
sol2 = exp(F)*(C1*exp(G) - C2*exp(-G))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order1_type4(x, y, t, r, eq):
r"""
The equations of this type of ode are .
.. math:: x' = f(t) x + g(t) y
.. math:: y' = -g(t) x + f(t) y
The solution is given by
.. math:: x = F (C_1 \cos(G) + C_2 \sin(G)), y = F (-C_1 \sin(G) + C_2 \cos(G))
where `C_1` and `C_2` are arbitrary constants, and
.. math:: F = \int f(t) \,dt , G = \int g(t) \,dt
"""
C1, C2 = get_numbered_constants(eq, num=2)
assert r['b'] == -r['c']
F = exp(Integral(r['a'], t))
G = Integral(r['b'], t)
sol1 = F*(C1*cos(G) + C2*sin(G))
sol2 = F*(-C1*sin(G) + C2*cos(G))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order1_type5(x, y, t, r, eq):
r"""The equations of this type of ode are
.. math:: x' = f(t) x + g(t) y
.. math:: y' = a g(t) x + [f(t) + b g(t)] y
The transformation of
.. math:: x = e^{\int f(t) \,dt} u , y = e^{\int f(t) \,dt} v , T = \int g(t) \,dt
leads to a system of constant coefficient linear differential equations
.. math:: u'(T) = v , v'(T) = au + bv
"""
u, v = symbols('u, v', cls=Function)
T = Symbol('T')
if not cancel(r['c']/r['b']).has(t):
p = cancel(r['c']/r['b'])
q = cancel((r['d']-r['a'])/r['b'])
eq = (Eq(diff(u(T), T), v(T)), Eq(diff(v(T), T), p*u(T)+q*v(T)))
sol = dsolve(eq)
sol1 = exp(Integral(r['a'], t))*sol[0].rhs.subs({T: Integral(r['b'], t)})
sol2 = exp(Integral(r['a'], t))*sol[1].rhs.subs({T: Integral(r['b'], t)})
else:
raise NotImplementedError
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order1_type6(x, y, t, r, eq):
r"""
The equations of this type of ode are .
.. math:: x' = f(t) x + g(t) y
.. math:: y' = a [f(t) + a h(t)] x + a [g(t) - h(t)] y
This is solved by first multiplying the first equation by `-a` and adding
it to the second equation to obtain
.. math:: y' - a x' = -a h(t) (y - a x)
Setting `U = y - ax` and integrating the equation we arrive at
.. math:: y - ax = C_1 e^{-a \int h(t) \,dt}
and on substituting the value of y in first equation give rise to first order ODEs. After solving for
`x`, we can obtain `y` by substituting the value of `x` in second equation.
"""
C1 = get_numbered_constants(eq, num=1)
p = 0
q = 0
p1 = cancel(r['c']/cancel(r['c']/r['d']).as_numer_denom()[0])
p2 = cancel(r['a']/cancel(r['a']/r['b']).as_numer_denom()[0])
for n, i in enumerate([p1, p2]):
for j in Mul.make_args(collect_const(i)):
if not j.has(t):
q = j
else:
raise NotImplementedError
if q != 0 and n == 0:
if cancel((r['c']/j - r['a'])/(r['b'] - r['d']/j)) == j:
p = 1
s = j
break
if q != 0 and n == 1:
if cancel((r['a']/j - r['c'])/(r['d'] - r['b']/j)) == j:
p = 2
s = j
break
if p == 1:
equ = diff(x(t), t) - r['a']*x(t) - r['b']*(s*x(t) + C1*exp(-s*Integral(r['b'] - r['d']/s, t)))
hint1 = classify_ode(equ)[1]
sol1 = dsolve(equ, hint=hint1+'_Integral').rhs
sol2 = s*sol1 + C1*exp(-s*Integral(r['b'] - r['d']/s, t))
elif p == 2:
equ = diff(y(t), t) - r['c']*y(t) - r['d']*s*y(t) + C1*exp(-s*Integral(r['d'] - r['b']/s, t))
hint1 = classify_ode(equ)[1]
sol2 = dsolve(equ, hint=hint1+'_Integral').rhs
sol1 = s*sol2 + C1*exp(-s*Integral(r['d'] - r['b']/s, t))
else:
raise NotImplementedError
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order1_type7(x, y, t, r, eq):
r"""
The equations of this type of ode are .
.. math:: x' = f(t) x + g(t) y
.. math:: y' = h(t) x + p(t) y
Differentiating the first equation and substituting the value of `y`
from second equation will give a second-order linear equation
.. math:: g x'' - (fg + gp + g') x' + (fgp - g^{2} h + f g' - f' g) x = 0
This above equation can be easily integrated if following conditions are satisfied.
1. `fgp - g^{2} h + f g' - f' g = 0`
2. `fgp - g^{2} h + f g' - f' g = ag, fg + gp + g' = bg`
If first condition is satisfied then it is solved by current dsolve solver and in second case it becomes
a constant coefficient differential equation which is also solved by current solver.
Otherwise if the above condition fails then,
a particular solution is assumed as `x = x_0(t)` and `y = y_0(t)`
Then the general solution is expressed as
.. math:: x = C_1 x_0(t) + C_2 x_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt
.. math:: y = C_1 y_0(t) + C_2 [\frac{F(t) P(t)}{x_0(t)} + y_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt]
where C1 and C2 are arbitrary constants and
.. math:: F(t) = e^{\int f(t) \,dt} , P(t) = e^{\int p(t) \,dt}
"""
C1, C2 = get_numbered_constants(eq, num=2)
e1 = r['a']*r['b']*r['c'] - r['b']**2*r['c'] + r['a']*diff(r['b'], t) - diff(r['a'], t)*r['b']
e2 = r['a']*r['c']*r['d'] - r['b']*r['c']**2 + diff(r['c'], t)*r['d'] - r['c']*diff(r['d'], t)
m1 = r['a']*r['b'] + r['b']*r['d'] + diff(r['b'], t)
m2 = r['a']*r['c'] + r['c']*r['d'] + diff(r['c'], t)
if e1.equals(0):
sol1 = dsolve(r['b']*diff(x(t), t, t) - m1*diff(x(t), t)).rhs
sol2 = dsolve(diff(y(t), t) - r['c']*sol1 - r['d']*y(t)).rhs
elif e2 == 0:
sol2 = dsolve(r['c']*diff(y(t), t, t) - m2*diff(y(t), t)).rhs
sol1 = dsolve(diff(x(t), t) - r['a']*x(t) - r['b']*sol2).rhs
elif not (e1/r['b']).has(t) and not (m1/r['b']).has(t):
sol1 = dsolve(diff(x(t), t, t) - (m1/r['b'])*diff(x(t), t) - (e1/r['b'])*x(t)).rhs
sol2 = dsolve(diff(y(t), t) - r['c']*sol1 - r['d']*y(t)).rhs
elif not (e2/r['c']).has(t) and not (m2/r['c']).has(t):
sol2 = dsolve(diff(y(t), t, t) - (m2/r['c'])*diff(y(t), t) - (e2/r['c'])*y(t)).rhs
sol1 = dsolve(diff(x(t), t) - r['a']*x(t) - r['b']*sol2).rhs
else:
x0, y0 = symbols('x0, y0', cls=Function) # x0 and y0 being particular solutions
F = exp(Integral(r['a'], t))
P = exp(Integral(r['d'], t))
sol1 = C1*x0(t) + C2*x0(t)*Integral(r['b']*F*P/x0(t)**2, t)
sol2 = C1*y0(t) + C2*(F*P/x0(t) + y0(t)*Integral(r['b']*F*P/x0(t)**2, t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def sysode_linear_2eq_order2(match_):
x = match_['func'][0].func
y = match_['func'][1].func
func = match_['func']
fc = match_['func_coeff']
eq = match_['eq']
r = {}
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
for i in range(2):
eqs = []
for terms in Add.make_args(eq[i]):
eqs.append(terms/fc[i, func[i], 2])
eq[i] = Add(*eqs)
# for equations Eq(diff(x(t),t,t), a1*diff(x(t),t)+b1*diff(y(t),t)+c1*x(t)+d1*y(t)+e1)
# and Eq(a2*diff(y(t),t,t), a2*diff(x(t),t)+b2*diff(y(t),t)+c2*x(t)+d2*y(t)+e2)
r['a1'] = -fc[0, x(t), 1]/fc[0, x(t), 2]
r['a2'] = -fc[1, x(t), 1]/fc[1, y(t), 2]
r['b1'] = -fc[0, y(t), 1]/fc[0, x(t), 2]
r['b2'] = -fc[1, y(t), 1]/fc[1, y(t), 2]
r['c1'] = -fc[0, x(t), 0]/fc[0, x(t), 2]
r['c2'] = -fc[1, x(t), 0]/fc[1, y(t), 2]
r['d1'] = -fc[0, y(t), 0]/fc[0, x(t), 2]
r['d2'] = -fc[1, y(t), 0]/fc[1, y(t), 2]
const = [Integer(0), Integer(0)]
for i in range(2):
for j in Add.make_args(eq[i]):
if not (j.has(x(t)) or j.has(y(t))):
const[i] += j
r['e1'] = -const[0]
r['e2'] = -const[1]
if match_['type_of_equation'] == 'type1':
sol = _linear_2eq_order2_type1(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type2':
gsol = _linear_2eq_order2_type1(x, y, t, r, eq)
psol = _linear_2eq_order2_type2(x, y, t, r, eq)
sol = [Eq(x(t), gsol[0].rhs+psol[0]), Eq(y(t), gsol[1].rhs+psol[1])]
elif match_['type_of_equation'] == 'type3':
sol = _linear_2eq_order2_type3(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type5':
sol = _linear_2eq_order2_type5(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type6':
sol = _linear_2eq_order2_type6(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type7':
sol = _linear_2eq_order2_type7(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type8':
sol = _linear_2eq_order2_type8(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type9':
sol = _linear_2eq_order2_type9(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type11':
sol = _linear_2eq_order2_type11(x, y, t, r, eq)
else:
raise NotImplementedError
return sol
def _linear_2eq_order2_type1(x, y, t, r, eq):
r"""
System of two constant-coefficient second-order linear homogeneous differential equations
.. math:: x'' = ax + by
.. math:: y'' = cx + dy
The characteristic equation for above equations
.. math:: \lambda^4 - (a + d) \lambda^2 + ad - bc = 0
whose discriminant is `D = (a - d)^2 + 4bc \neq 0`
1. When `ad - bc \neq 0`
1.1. If `D \neq 0`. The characteristic equation has four distinct roots, `\lambda_1, \lambda_2, \lambda_3, \lambda_4`.
The general solution of the system is
.. math:: x = C_1 b e^{\lambda_1 t} + C_2 b e^{\lambda_2 t} + C_3 b e^{\lambda_3 t} + C_4 b e^{\lambda_4 t}
.. math:: y = C_1 (\lambda_1^{2} - a) e^{\lambda_1 t} + C_2 (\lambda_2^{2} - a) e^{\lambda_2 t} + C_3 (\lambda_3^{2} - a) e^{\lambda_3 t} + C_4 (\lambda_4^{2} - a) e^{\lambda_4 t}
where `C_1,..., C_4` are arbitrary constants.
1.2. If `D = 0` and `a \neq d`:
.. math:: x = 2 C_1 (bt + \frac{2bk}{a - d}) e^{\frac{kt}{2}} + 2 C_2 (bt + \frac{2bk}{a - d}) e^{\frac{-kt}{2}} + 2b C_3 t e^{\frac{kt}{2}} + 2b C_4 t e^{\frac{-kt}{2}}
.. math:: y = C_1 (d - a) t e^{\frac{kt}{2}} + C_2 (d - a) t e^{\frac{-kt}{2}} + C_3 [(d - a) t + 2k] e^{\frac{kt}{2}} + C_4 [(d - a) t - 2k] e^{\frac{-kt}{2}}
where `C_1,..., C_4` are arbitrary constants and `k = \sqrt{2 (a + d)}`
1.3. If `D = 0` and `a = d \neq 0` and `b = 0`:
.. math:: x = 2 \sqrt{a} C_1 e^{\sqrt{a} t} + 2 \sqrt{a} C_2 e^{-\sqrt{a} t}
.. math:: y = c C_1 t e^{\sqrt{a} t} - c C_2 t e^{-\sqrt{a} t} + C_3 e^{\sqrt{a} t} + C_4 e^{-\sqrt{a} t}
1.4. If `D = 0` and `a = d \neq 0` and `c = 0`:
.. math:: x = b C_1 t e^{\sqrt{a} t} - b C_2 t e^{-\sqrt{a} t} + C_3 e^{\sqrt{a} t} + C_4 e^{-\sqrt{a} t}
.. math:: y = 2 \sqrt{a} C_1 e^{\sqrt{a} t} + 2 \sqrt{a} C_2 e^{-\sqrt{a} t}
2. When `ad - bc = 0` and `a^2 + b^2 > 0`. Then the original system becomes
.. math:: x'' = ax + by
.. math:: y'' = k (ax + by)
2.1. If `a + bk \neq 0`:
.. math:: x = C_1 e^{t \sqrt{a + bk}} + C_2 e^{-t \sqrt{a + bk}} + C_3 bt + C_4 b
.. math:: y = C_1 k e^{t \sqrt{a + bk}} + C_2 k e^{-t \sqrt{a + bk}} - C_3 at - C_4 a
2.2. If `a + bk = 0`:
.. math:: x = C_1 b t^3 + C_2 b t^2 + C_3 t + C_4
.. math:: y = kx + 6 C_1 t + 2 C_2
"""
r['a'] = r['c1']
r['b'] = r['d1']
r['c'] = r['c2']
r['d'] = r['d2']
l = Symbol('l')
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
chara_eq = l**4 - (r['a']+r['d'])*l**2 + r['a']*r['d'] - r['b']*r['c']
l1, l2, l3, l4 = Poly(chara_eq, l).all_roots()
D = (r['a'] - r['d'])**2 + 4*r['b']*r['c']
if (r['a']*r['d'] - r['b']*r['c']) != 0:
if D != 0:
gsol1 = C1*r['b']*exp(l1*t) + C2*r['b']*exp(l2*t) + C3*r['b']*exp(l3*t) \
+ C4*r['b']*exp(l4*t)
gsol2 = C1*(l1**2-r['a'])*exp(l1*t) + C2*(l2**2-r['a'])*exp(l2*t) + \
C3*(l3**2-r['a'])*exp(l3*t) + C4*(l4**2-r['a'])*exp(l4*t)
else:
if r['a'] != r['d']:
k = sqrt(2*(r['a']+r['d']))
gsol1 = 2*C1*(r['b']*t+2*r['b']*k/(r['a']-r['d']))*exp(k*t/2) + \
2*C2*(r['b']*t-2*r['b']*k/(r['a']-r['d']))*exp(-k*t/2) + \
2*r['b']*C3*t*exp(k*t/2) + 2*r['b']*C4*t*exp(-k*t/2)
gsol2 = C1*(r['d']-r['a'])*t*exp(k*t/2) + C2*(r['d']-r['a'])*t*exp(-k*t/2) + \
C3*((r['d']-r['a'])*t+2*k)*exp(k*t/2) + C4*((r['d']-r['a'])*t-2*k)*exp(-k*t/2)
elif r['a'] == r['d'] != 0 and r['b'] == 0:
sa = sqrt(r['a'])
gsol1 = 2*sa*C1*exp(sa*t) + 2*sa*C2*exp(-sa*t)
gsol2 = r['c']*C1*t*exp(sa*t)-r['c']*C2*t*exp(-sa*t)+C3*exp(sa*t)+C4*exp(-sa*t)
else:
assert r['a'] == r['d'] != 0 and r['c'] == 0
sa = sqrt(r['a'])
gsol1 = r['b']*C1*t*exp(sa*t)-r['b']*C2*t*exp(-sa*t)+C3*exp(sa*t)+C4*exp(-sa*t)
gsol2 = 2*sa*C1*exp(sa*t) + 2*sa*C2*exp(-sa*t)
elif (r['a']*r['d'] - r['b']*r['c']) == 0 and (r['a']**2 + r['b']**2) > 0:
k = r['c']/r['a']
if r['a'] + r['b']*k != 0:
mid = sqrt(r['a'] + r['b']*k)
gsol1 = C1*exp(mid*t) + C2*exp(-mid*t) + C3*r['b']*t + C4*r['b']
gsol2 = C1*k*exp(mid*t) + C2*k*exp(-mid*t) - C3*r['a']*t - C4*r['a']
else:
gsol1 = C1*r['b']*t**3 + C2*r['b']*t**2 + C3*t + C4
gsol2 = k*gsol1 + 6*C1*t + 2*C2
else:
raise NotImplementedError
return [Eq(x(t), gsol1), Eq(y(t), gsol2)]
def _linear_2eq_order2_type2(x, y, t, r, eq):
r"""
The equations in this type are
.. math:: x'' = a_1 x + b_1 y + c_1
.. math:: y'' = a_2 x + b_2 y + c_2
The general solution of this system is given by the sum of its particular solution
and the general solution of the homogeneous system. The general solution is given
by the linear system of 2 equation of order 2 and type 1
1. If `a_1 b_2 - a_2 b_1 \neq 0`. A particular solution will be `x = x_0` and `y = y_0`
where the constants `x_0` and `y_0` are determined by solving the linear algebraic system
.. math:: a_1 x_0 + b_1 y_0 + c_1 = 0, a_2 x_0 + b_2 y_0 + c_2 = 0
2. If `a_1 b_2 - a_2 b_1 = 0` and `a_1^2 + b_1^2 > 0`. In this case, the system in question becomes
.. math:: x'' = ax + by + c_1, y'' = k (ax + by) + c_2
2.1. If `\sigma = a + bk \neq 0`, the particular solution will be
.. math:: x = \frac{1}{2} b \sigma^{-1} (c_1 k - c_2) t^2 - \sigma^{-2} (a c_1 + b c_2)
.. math:: y = kx + \frac{1}{2} (c_2 - c_1 k) t^2
2.2. If `\sigma = a + bk = 0`, the particular solution will be
.. math:: x = \frac{1}{24} b (c_2 - c_1 k) t^4 + \frac{1}{2} c_1 t^2
.. math:: y = kx + \frac{1}{2} (c_2 - c_1 k) t^2
"""
x0, y0 = symbols('x0, y0')
if r['c1']*r['d2'] - r['c2']*r['d1'] != 0:
sol = solve((r['c1']*x0+r['d1']*y0+r['e1'],
r['c2']*x0+r['d2']*y0+r['e2']), x0, y0)
sol = sol[0]
psol = [sol[x0], sol[y0]]
elif r['c1']*r['d2'] - r['c2']*r['d1'] == 0 and (r['c1']**2 + r['d1']**2) > 0:
k = r['c2']/r['c1']
sig = r['c1'] + r['d1']*k
if sig != 0:
psol1 = r['d1']*sig**-1*(r['e1']*k-r['e2'])*t**2/2 - \
sig**-2*(r['c1']*r['e1']+r['d1']*r['e2'])
psol2 = k*psol1 + (r['e2'] - r['e1']*k)*t**2/2
psol = [psol1, psol2]
else:
psol1 = r['d1']*(r['e2']-r['e1']*k)*t**4/24 + r['e1']*t**2/2
psol2 = k*psol1 + (r['e2']-r['e1']*k)*t**2/2
psol = [psol1, psol2]
else:
raise NotImplementedError
return psol
def _linear_2eq_order2_type3(x, y, t, r, eq):
r"""
These type of equation is used for describing the horizontal motion of a pendulum
taking into account the Earth rotation.
The solution is given with `a^2 + 4b > 0`:
.. math:: x = C_1 \cos(\alpha t) + C_2 \sin(\alpha t) + C_3 \cos(\beta t) + C_4 \sin(\beta t)
.. math:: y = -C_1 \sin(\alpha t) + C_2 \cos(\alpha t) - C_3 \sin(\beta t) + C_4 \cos(\beta t)
where `C_1,...,C_4` and
.. math:: \alpha = \frac{1}{2} a + \frac{1}{2} \sqrt{a^2 + 4b}, \beta = \frac{1}{2} a - \frac{1}{2} \sqrt{a^2 + 4b}
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
assert r['b1']**2 - 4*r['c1'] > 0
r['a'] = r['b1']
r['b'] = -r['c1']
alpha = r['a']/2 + sqrt(r['a']**2 + 4*r['b'])/2
beta = r['a']/2 - sqrt(r['a']**2 + 4*r['b'])/2
sol1 = C1*cos(alpha*t) + C2*sin(alpha*t) + C3*cos(beta*t) + C4*sin(beta*t)
sol2 = -C1*sin(alpha*t) + C2*cos(alpha*t) - C3*sin(beta*t) + C4*cos(beta*t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type5(x, y, t, r, eq):
r"""
The equation which come under this category are
.. math:: x'' = a (t y' - y)
.. math:: y'' = b (t x' - x)
The transformation
.. math:: u = t x' - x, b = t y' - y
leads to the first-order system
.. math:: u' = atv, v' = btu
The general solution of this system is given by
If `ab > 0`:
.. math:: u = C_1 a e^{\frac{1}{2} \sqrt{ab} t^2} + C_2 a e^{-\frac{1}{2} \sqrt{ab} t^2}
.. math:: v = C_1 \sqrt{ab} e^{\frac{1}{2} \sqrt{ab} t^2} - C_2 \sqrt{ab} e^{-\frac{1}{2} \sqrt{ab} t^2}
If `ab < 0`:
.. math:: u = C_1 a \cos(\frac{1}{2} \sqrt{\left|ab\right|} t^2) + C_2 a \sin(-\frac{1}{2} \sqrt{\left|ab\right|} t^2)
.. math:: v = C_1 \sqrt{\left|ab\right|} \sin(\frac{1}{2} \sqrt{\left|ab\right|} t^2) + C_2 \sqrt{\left|ab\right|} \cos(-\frac{1}{2} \sqrt{\left|ab\right|} t^2)
where `C_1` and `C_2` are arbitrary constants. On substituting the value of `u` and `v`
in above equations and integrating the resulting expressions, the general solution will become
.. math:: x = C_3 t + t \int \frac{u}{t^2} \,dt, y = C_4 t + t \int \frac{u}{t^2} \,dt
where `C_3` and `C_4` are arbitrary constants.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
r['a'] = -r['d1']
r['b'] = -r['c2']
mul = sqrt(abs(r['a']*r['b']))
if r['a']*r['b'] > 0:
u = C1*r['a']*exp(mul*t**2/2) + C2*r['a']*exp(-mul*t**2/2)
v = C1*mul*exp(mul*t**2/2) - C2*mul*exp(-mul*t**2/2)
else:
u = C1*r['a']*cos(mul*t**2/2) + C2*r['a']*sin(mul*t**2/2)
v = -C1*mul*sin(mul*t**2/2) + C2*mul*cos(mul*t**2/2)
sol1 = C3*t + t*Integral(u/t**2, t)
sol2 = C4*t + t*Integral(v/t**2, t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type6(x, y, t, r, eq):
r"""
The equations are
.. math:: x'' = f(t) (a_1 x + b_1 y)
.. math:: y'' = f(t) (a_2 x + b_2 y)
If `k_1` and `k_2` are roots of the quadratic equation
.. math:: k^2 - (a_1 + b_2) k + a_1 b_2 - a_2 b_1 = 0
Then by multiplying appropriate constants and adding together original equations
we obtain two independent equations:
.. math:: z_1'' = k_1 f(t) z_1, z_1 = a_2 x + (k_1 - a_1) y
.. math:: z_2'' = k_2 f(t) z_2, z_2 = a_2 x + (k_2 - a_1) y
Solving the equations will give the values of `x` and `y` after obtaining the value
of `z_1` and `z_2` by solving the differential equation and substituting the result.
"""
k = Symbol('k')
z = Function('z')
num, den = cancel((r['c1']*x(t) + r['d1']*y(t)) /
(r['c2']*x(t) + r['d2']*y(t))).as_numer_denom()
f = r['c1']/num.coeff(x(t))
a1 = num.coeff(x(t))
b1 = num.coeff(y(t))
a2 = den.coeff(x(t))
b2 = den.coeff(y(t))
chareq = k**2 - (a1 + b2)*k + a1*b2 - a2*b1
k1, k2 = Poly(chareq, k).all_roots()
z1 = dsolve(diff(z(t), t, t) - k1*f*z(t)).rhs
z2 = dsolve(diff(z(t), t, t) - k2*f*z(t)).rhs
sol1 = (k1*z2 - k2*z1 + a1*(z1 - z2))/(a2*(k1-k2))
sol2 = (z1 - z2)/(k1 - k2)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type7(x, y, t, r, eq):
r"""
The equations are given as
.. math:: x'' = f(t) (a_1 x' + b_1 y')
.. math:: y'' = f(t) (a_2 x' + b_2 y')
If `k_1` and 'k_2` are roots of the quadratic equation
.. math:: k^2 - (a_1 + b_2) k + a_1 b_2 - a_2 b_1 = 0
Then the system can be reduced by adding together the two equations multiplied
by appropriate constants give following two independent equations:
.. math:: z_1'' = k_1 f(t) z_1', z_1 = a_2 x + (k_1 - a_1) y
.. math:: z_2'' = k_2 f(t) z_2', z_2 = a_2 x + (k_2 - a_1) y
Integrating these and returning to the original variables, one arrives at a linear
algebraic system for the unknowns `x` and `y`:
.. math:: a_2 x + (k_1 - a_1) y = C_1 \int e^{k_1 F(t)} \,dt + C_2
.. math:: a_2 x + (k_2 - a_1) y = C_3 \int e^{k_2 F(t)} \,dt + C_4
where `C_1,...,C_4` are arbitrary constants and `F(t) = \int f(t) \,dt`
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
k = Symbol('k')
num, den = cancel((r['a1']*x(t) + r['b1']*y(t)) /
(r['a2']*x(t) + r['b2']*y(t))).as_numer_denom()
f = r['a1']/num.coeff(x(t))
a1 = num.coeff(x(t))
b1 = num.coeff(y(t))
a2 = den.coeff(x(t))
b2 = den.coeff(y(t))
chareq = k**2 - (a1 + b2)*k + a1*b2 - a2*b1
k1, k2 = Poly(chareq, k).all_roots()
F = Integral(f, t)
z1 = C1*Integral(exp(k1*F), t) + C2
z2 = C3*Integral(exp(k2*F), t) + C4
sol1 = (k1*z2 - k2*z1 + a1*(z1 - z2))/(a2*(k1-k2))
sol2 = (z1 - z2)/(k1 - k2)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type8(x, y, t, r, eq):
r"""
The equation of this category are
.. math:: x'' = a f(t) (t y' - y)
.. math:: y'' = b f(t) (t x' - x)
The transformation
.. math:: u = t x' - x, v = t y' - y
leads to the system of first-order equations
.. math:: u' = a t f(t) v, v' = b t f(t) u
The general solution of this system has the form
If `ab > 0`:
.. math:: u = C_1 a e^{\sqrt{ab} \int t f(t) \,dt} + C_2 a e^{-\sqrt{ab} \int t f(t) \,dt}
.. math:: v = C_1 \sqrt{ab} e^{\sqrt{ab} \int t f(t) \,dt} - C_2 \sqrt{ab} e^{-\sqrt{ab} \int t f(t) \,dt}
If `ab < 0`:
.. math:: u = C_1 a \cos(\sqrt{\left|ab\right|} \int t f(t) \,dt) + C_2 a \sin(-\sqrt{\left|ab\right|} \int t f(t) \,dt)
.. math:: v = C_1 \sqrt{\left|ab\right|} \sin(\sqrt{\left|ab\right|} \int t f(t) \,dt) + C_2 \sqrt{\left|ab\right|} \cos(-\sqrt{\left|ab\right|} \int t f(t) \,dt)
where `C_1` and `C_2` are arbitrary constants. On substituting the value of `u` and `v`
in above equations and integrating the resulting expressions, the general solution will become
.. math:: x = C_3 t + t \int \frac{u}{t^2} \,dt, y = C_4 t + t \int \frac{u}{t^2} \,dt
where `C_3` and `C_4` are arbitrary constants.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
num, den = cancel(r['d1']/r['c2']).as_numer_denom()
f = -r['d1']/num
a = num
b = den
mul = sqrt(abs(a*b))
Igral = Integral(t*f, t)
if a*b > 0:
u = C1*a*exp(mul*Igral) + C2*a*exp(-mul*Igral)
v = C1*mul*exp(mul*Igral) - C2*mul*exp(-mul*Igral)
else:
u = C1*a*cos(mul*Igral) + C2*a*sin(mul*Igral)
v = -C1*mul*sin(mul*Igral) + C2*mul*cos(mul*Igral)
sol1 = C3*t + t*Integral(u/t**2, t)
sol2 = C4*t + t*Integral(v/t**2, t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type9(x, y, t, r, eq):
r"""
.. math:: t^2 x'' + a_1 t x' + b_1 t y' + c_1 x + d_1 y = 0
.. math:: t^2 y'' + a_2 t x' + b_2 t y' + c_2 x + d_2 y = 0
These system of equations are euler type.
The substitution of `t = \sigma e^{\tau} (\sigma \neq 0)` leads to the system of constant
coefficient linear differential equations
.. math:: x'' + (a_1 - 1) x' + b_1 y' + c_1 x + d_1 y = 0
.. math:: y'' + a_2 x' + (b_2 - 1) y' + c_2 x + d_2 y = 0
The general solution of the homogeneous system of differential equations is determined
by a linear combination of linearly independent particular solutions determined by
the method of undetermined coefficients in the form of exponentials
.. math:: x = A e^{\lambda t}, y = B e^{\lambda t}
On substituting these expressions into the original system and collecting the
coefficients of the unknown `A` and `B`, one obtains
.. math:: (\lambda^{2} + (a_1 - 1) \lambda + c_1) A + (b_1 \lambda + d_1) B = 0
.. math:: (a_2 \lambda + c_2) A + (\lambda^{2} + (b_2 - 1) \lambda + d_2) B = 0
The determinant of this system must vanish for nontrivial solutions A, B to exist.
This requirement results in the following characteristic equation for `\lambda`
.. math:: (\lambda^2 + (a_1 - 1) \lambda + c_1) (\lambda^2 + (b_2 - 1) \lambda + d_2) - (b_1 \lambda + d_1) (a_2 \lambda + c_2) = 0
If all roots `k_1,...,k_4` of this equation are distinct, the general solution of the original
system of the differential equations has the form
.. math:: x = C_1 (b_1 \lambda_1 + d_1) e^{\lambda_1 t} - C_2 (b_1 \lambda_2 + d_1) e^{\lambda_2 t} - C_3 (b_1 \lambda_3 + d_1) e^{\lambda_3 t} - C_4 (b_1 \lambda_4 + d_1) e^{\lambda_4 t}
.. math:: y = C_1 (\lambda_1^{2} + (a_1 - 1) \lambda_1 + c_1) e^{\lambda_1 t} + C_2 (\lambda_2^{2} + (a_1 - 1) \lambda_2 + c_1) e^{\lambda_2 t} + C_3 (\lambda_3^{2} + (a_1 - 1) \lambda_3 + c_1) e^{\lambda_3 t} + C_4 (\lambda_4^{2} + (a_1 - 1) \lambda_4 + c_1) e^{\lambda_4 t}
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
k = Symbol('k')
a1 = -r['a1']*t
a2 = -r['a2']*t
b1 = -r['b1']*t
b2 = -r['b2']*t
c1 = -r['c1']*t**2
c2 = -r['c2']*t**2
d1 = -r['d1']*t**2
d2 = -r['d2']*t**2
eq = (k**2+(a1-1)*k+c1)*(k**2+(b2-1)*k+d2)-(b1*k+d1)*(a2*k+c2)
[k1, k2, k3, k4] = roots_quartic(Poly(eq))
sol1 = -C1*(b1*k1+d1)*exp(k1*log(t)) - C2*(b1*k2+d1)*exp(k2*log(t)) - \
C3*(b1*k3+d1)*exp(k3*log(t)) - C4*(b1*k4+d1)*exp(k4*log(t))
a1_ = (a1-1)
sol2 = C1*(k1**2+a1_*k1+c1)*exp(k1*log(t)) + C2*(k2**2+a1_*k2+c1)*exp(k2*log(t)) \
+ C3*(k3**2+a1_*k3+c1)*exp(k3*log(t)) + C4*(k4**2+a1_*k4+c1)*exp(k4*log(t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type11(x, y, t, r, eq):
r"""
The equations which comes under this type are
.. math:: x'' = f(t) (t x' - x) + g(t) (t y' - y)
.. math:: y'' = h(t) (t x' - x) + p(t) (t y' - y)
The transformation
.. math:: u = t x' - x, v = t y' - y
leads to the linear system of first-order equations
.. math:: u' = t f(t) u + t g(t) v, v' = t h(t) u + t p(t) v
On substituting the value of `u` and `v` in transformed equation gives value of `x` and `y` as
.. math:: x = C_3 t + t \int \frac{u}{t^2} \,dt , y = C_4 t + t \int \frac{v}{t^2} \,dt.
where `C_3` and `C_4` are arbitrary constants.
"""
*_, C3, C4 = get_numbered_constants(eq, num=4)
u, v = symbols('u, v', cls=Function)
f = -r['c1']
g = -r['d1']
h = -r['c2']
p = -r['d2']
[msol1, msol2] = dsolve([Eq(diff(u(t), t), t*f*u(t) + t*g*v(t)), Eq(diff(v(t), t), t*h*u(t) + t*p*v(t))])
sol1 = C3*t + t*Integral(msol1.rhs/t**2, t)
sol2 = C4*t + t*Integral(msol2.rhs/t**2, t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def sysode_linear_3eq_order1(match_):
x = match_['func'][0].func
y = match_['func'][1].func
z = match_['func'][2].func
func = match_['func']
fc = match_['func_coeff']
eq = match_['eq']
r = {}
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
for i in range(3):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i, func[i], 1]
eq[i] = eqs
# for equations:
# Eq(g1*diff(x(t),t), a1*x(t)+b1*y(t)+c1*z(t)+d1),
# Eq(g2*diff(y(t),t), a2*x(t)+b2*y(t)+c2*z(t)+d2), and
# Eq(g3*diff(z(t),t), a3*x(t)+b3*y(t)+c3*z(t)+d3)
r['a1'] = -fc[0, x(t), 0]/fc[0, x(t), 1]
r['a2'] = -fc[1, x(t), 0]/fc[1, y(t), 1]
r['a3'] = -fc[2, x(t), 0]/fc[2, z(t), 1]
r['b1'] = -fc[0, y(t), 0]/fc[0, x(t), 1]
r['b2'] = -fc[1, y(t), 0]/fc[1, y(t), 1]
r['b3'] = -fc[2, y(t), 0]/fc[2, z(t), 1]
r['c1'] = -fc[0, z(t), 0]/fc[0, x(t), 1]
r['c2'] = -fc[1, z(t), 0]/fc[1, y(t), 1]
r['c3'] = -fc[2, z(t), 0]/fc[2, z(t), 1]
for i in range(3):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t), z(t)):
raise NotImplementedError('Only homogeneous problems are supported, non-homogenous are not supported currently.')
if match_['type_of_equation'] == 'type4':
sol = _linear_3eq_order1_type4(x, y, z, t, r, eq)
else:
raise NotImplementedError
return sol
def _linear_3eq_order1_type4(x, y, z, t, r, eq):
r"""
Equations:
.. math:: x' = (a_1 f(t) + g(t)) x + a_2 f(t) y + a_3 f(t) z
.. math:: y' = b_1 f(t) x + (b_2 f(t) + g(t)) y + b_3 f(t) z
.. math:: z' = c_1 f(t) x + c_2 f(t) y + (c_3 f(t) + g(t)) z
The transformation
.. math:: x = e^{\int g(t) \,dt} u, y = e^{\int g(t) \,dt} v, z = e^{\int g(t) \,dt} w, \tau = \int f(t) \,dt
leads to the system of constant coefficient linear differential equations
.. math:: u' = a_1 u + a_2 v + a_3 w
.. math:: v' = b_1 u + b_2 v + b_3 w
.. math:: w' = c_1 u + c_2 v + c_3 w
These system of equations are solved by homogeneous linear system of constant
coefficients of `n` equations of first order. Then substituting the value of
`u, v` and `w` in transformed equation gives value of `x, y` and `z`.
"""
u, v, w = symbols('u, v, w', cls=Function)
a2, a3 = cancel(r['b1']/r['c1']).as_numer_denom()
f = cancel(r['b1']/a2)
b1 = cancel(r['a2']/f)
b3 = cancel(r['c2']/f)
c1 = cancel(r['a3']/f)
c2 = cancel(r['b3']/f)
a1, g = div(r['a1'], f)
b2 = div(r['b2'], f)[0]
c3 = div(r['c3'], f)[0]
trans_eq = (diff(u(t), t) - a1*u(t) - a2*v(t) - a3*w(t), diff(v(t), t) - b1*u(t) -
b2*v(t) - b3*w(t), diff(w(t), t) - c1*u(t) - c2*v(t) - c3*w(t))
sol = dsolve(trans_eq)
sol1 = exp(Integral(g, t))*((sol[0].rhs).subs({t: Integral(f, t)}))
sol2 = exp(Integral(g, t))*((sol[1].rhs).subs({t: Integral(f, t)}))
sol3 = exp(Integral(g, t))*((sol[2].rhs).subs({t: Integral(f, t)}))
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def sysode_linear_neq_order1(match_):
r"""System of n first-order constant-coefficient linear differential equations
.. math ::
M x' = L x + f(t)
Notes
=====
Mass-matrix assumed to be invertible and provided general solution uses
the Jordan canonical form for `A = M^{-1} L`.
References
==========
* :cite:`hairer2014solving`, pp. 73-76.
"""
func = match_['func']
fc = match_['func_coeff']
eq = match_['eq']
n = match_['no_of_equation']
t = func[0].args[0]
force = [Integer(0)]*n
for i in range(n):
for j in Add.make_args(eq[i]):
if not j.has(*func):
force[i] += j
M = Matrix(n, n, lambda i, j: +fc[i, func[j], 1])
L = Matrix(n, n, lambda i, j: -fc[i, func[j], 0])
Minv = M.inv()
A = Minv*L
JJ, T = A.jordan_cells()
expm = Matrix(BlockDiagMatrix(*[(J*t).exp() for J in JJ]))
q = T*expm*Matrix(get_numbered_constants(eq, num=n))
force = Minv*Matrix(force)
if not force.is_zero:
Tinv = simplify(T.inv())
q -= T*expm*(expm.subs({t: -t})*Tinv*force).integrate(t)
return [Eq(func[i], q[i]) for i in range(n)]
def sysode_nonlinear_2eq_order1(match_):
func = match_['func']
eq = match_['eq']
fc = match_['func_coeff']
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
if match_['type_of_equation'] == 'type5':
sol = _nonlinear_2eq_order1_type5(func, t, eq)
return sol
x = func[0].func
y = func[1].func
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i, func[i], 1]
eq[i] = eqs
if match_['type_of_equation'] == 'type1':
sol = _nonlinear_2eq_order1_type1(x, y, t, eq)
elif match_['type_of_equation'] == 'type2':
sol = _nonlinear_2eq_order1_type2(x, y, t, eq)
elif match_['type_of_equation'] == 'type3':
sol = _nonlinear_2eq_order1_type3(x, y, t, eq)
elif match_['type_of_equation'] == 'type4':
sol = _nonlinear_2eq_order1_type4(x, y, t, eq)
else:
raise NotImplementedError
return sol
def _nonlinear_2eq_order1_type1(x, y, t, eq):
r"""
Equations:
.. math:: x' = x^n F(x,y)
.. math:: y' = g(y) F(x,y)
Solution:
.. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2
where
if `n \neq 1`
.. math:: \varphi = [C_1 + (1-n) \int \frac{1}{g(y)} \,dy]^{\frac{1}{1-n}}
if `n = 1`
.. math:: \varphi = C_1 e^{\int \frac{1}{g(y)} \,dy}
where `C_1` and `C_2` are arbitrary constants.
"""
C1, C2 = get_numbered_constants(eq, num=2)
n = Wild('n', exclude=[x(t), y(t)])
f = Wild('f')
u, v, phi = symbols('u, v, phi', function=True)
r = eq[0].match(diff(x(t), t) - x(t)**n*f)
g = ((diff(y(t), t) - eq[1])/r[f]).subs({y(t): v})
F = r[f].subs({x(t): u, y(t): v})
n = r[n]
if n != 1:
phi = (C1 + (1-n)*Integral(1/g, v))**(1/(1-n))
else:
phi = C1*exp(Integral(1/g, v))
phi = phi.doit()
sol2 = solve(Integral(1/(g*F.subs({u: phi})), v).doit() - t - C2, v)
sol = []
for sols in sol2:
sol.append(Eq(x(t), phi.subs(sols)))
sol.append(Eq(y(t), sols[v]))
return sol
def _nonlinear_2eq_order1_type2(x, y, t, eq):
r"""
Equations:
.. math:: x' = e^{\lambda x} F(x,y)
.. math:: y' = g(y) F(x,y)
Solution:
.. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2
where
if `\lambda \neq 0`
.. math:: \varphi = -\frac{1}{\lambda} log(C_1 - \lambda \int \frac{1}{g(y)} \,dy)
if `\lambda = 0`
.. math:: \varphi = C_1 + \int \frac{1}{g(y)} \,dy
where `C_1` and `C_2` are arbitrary constants.
"""
C1, C2 = get_numbered_constants(eq, num=2)
n = Wild('n', exclude=[x(t), y(t)])
f = Wild('f')
u, v, phi = symbols('u, v, phi', function=True)
r = eq[0].match(diff(x(t), t) - exp(n*x(t))*f)
g = ((diff(y(t), t) - eq[1])/r[f]).subs({y(t): v})
F = r[f].subs({x(t): u, y(t): v})
n = r[n]
if n:
phi = -1/n*log(C1 - n*Integral(1/g, v))
else:
phi = C1 + Integral(1/g, v)
phi = phi.doit()
sol2 = solve(Integral(1/(g*F.subs({u: phi})), v).doit() - t - C2, v)
sol = []
for sols in sol2:
sol.append(Eq(x(t), phi.subs(sols)))
sol.append(Eq(y(t), sols[v]))
return sol
def _nonlinear_2eq_order1_type3(x, y, t, eq):
r"""
Autonomous system of general form
.. math:: x' = F(x,y)
.. math:: y' = G(x,y)
Assuming `y = y(x, C_1)` where `C_1` is an arbitrary constant is the general
solution of the first-order equation
.. math:: F(x,y) y'_x = G(x,y)
Then the general solution of the original system of equations has the form
.. math:: \int \frac{1}{F(x,y(x,C_1))} \,dx = t + C_1
"""
_, C2, *_ = get_numbered_constants(eq, num=4)
v = Function('v')
u = Symbol('u')
f = Wild('f')
g = Wild('g')
r1 = eq[0].match(diff(x(t), t) - f)
r2 = eq[1].match(diff(y(t), t) - g)
F = r1[f].subs({x(t): u, y(t): v(u)})
G = r2[g].subs({x(t): u, y(t): v(u)})
sol2r = dsolve(Eq(diff(v(u), u), G/F))
for sol2s in sol2r:
sol1 = solve(Integral(1/F.subs({v(u): sol2s.rhs}), u).doit() - t - C2, u)
sol = []
for sols in sol1:
sol.append(Eq(x(t), sols[u]))
sol.append(Eq(y(t), (sol2s.rhs).subs(sols)))
return sol
def _nonlinear_2eq_order1_type4(x, y, t, eq):
r"""
Equation:
.. math:: x' = f_1(x) g_1(y) \phi(x,y,t)
.. math:: y' = f_2(x) g_2(y) \phi(x,y,t)
First integral:
.. math:: \int \frac{f_2(x)}{f_1(x)} \,dx - \int \frac{g_1(y)}{g_2(y)} \,dy = C
where `C` is an arbitrary constant.
On solving the first integral for `x` (resp., `y` ) and on substituting the
resulting expression into either equation of the original solution, one
arrives at a firs-order equation for determining `y` (resp., `x` ).
"""
C1 = get_numbered_constants(eq, num=1)
u, v = symbols('u, v')
U, V = symbols('U, V', cls=Function)
f = Wild('f')
g = Wild('g')
f1 = Wild('f1', exclude=[v, t])
f2 = Wild('f2', exclude=[v, t])
g1 = Wild('g1', exclude=[u, t])
g2 = Wild('g2', exclude=[u, t])
r1 = eq[0].match(diff(x(t), t) - f)
r2 = eq[1].match(diff(y(t), t) - g)
num, den = ((r1[f].subs({x(t): u, y(t): v})) /
(r2[g].subs({x(t): u, y(t): v}))).as_numer_denom()
R1 = num.match(f1*g1)
R2 = den.match(f2*g2)
phi = (r1[f].subs({x(t): u, y(t): v}))/num
F1 = R1[f1]
F2 = R2[f2]
G1 = R1[g1]
G2 = R2[g2]
sol1r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2, v).doit() - C1, u)
sol2r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2, v).doit() - C1, v)
sol = []
for sols in sol1r:
sol.append(Eq(y(t), dsolve(diff(V(t), t) - F2.subs(sols).subs({v: V(t)})*G2.subs({v: V(t)})*phi.subs(sols).subs({v: V(t)})).rhs))
for sols in sol2r:
sol.append(Eq(x(t), dsolve(diff(U(t), t) - F1.subs({u: U(t)})*G1.subs(sols).subs({u: U(t)})*phi.subs(sols).subs({u: U(t)})).rhs))
return set(sol)
def _nonlinear_2eq_order1_type5(func, t, eq):
r"""
Clairaut system of ODEs
.. math:: x = t x' + F(x',y')
.. math:: y = t y' + G(x',y')
The following are solutions of the system
`(i)` straight lines:
.. math:: x = C_1 t + F(C_1, C_2), y = C_2 t + G(C_1, C_2)
where `C_1` and `C_2` are arbitrary constants;
`(ii)` envelopes of the above lines;
`(iii)` continuously differentiable lines made up from segments of the lines
`(i)` and `(ii)`.
"""
C1, C2 = get_numbered_constants(eq, num=2)
x = func[0].func
y = func[1].func
x1 = diff(x(t), t)
y1 = diff(y(t), t)
f = Wild('f')
g = Wild('g')
r1 = eq[0].match(t*diff(x(t), t) - x(t) + f)
r2 = eq[1].match(t*diff(y(t), t) - y(t) + g)
if not (r1 and r2):
r1 = eq[0].match(diff(x(t), t) - x(t)/t + f/t)
r2 = eq[1].match(diff(y(t), t) - y(t)/t + g/t)
if not (r1 and r2):
r1 = (-eq[0]).match(t*diff(x(t), t) - x(t) + f)
r2 = (-eq[1]).match(t*diff(y(t), t) - y(t) + g)
return {Eq(x(t), C1*t + r1[f].subs({x1: C1, y1: C2})), Eq(y(t), C2*t + r2[g].subs({x1: C1, y1: C2}))}
def sysode_nonlinear_3eq_order1(match_):
x = match_['func'][0].func
y = match_['func'][1].func
z = match_['func'][2].func
eq = match_['eq']
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
if match_['type_of_equation'] == 'type1':
sol = _nonlinear_3eq_order1_type1(x, y, z, t, eq)
if match_['type_of_equation'] == 'type2':
sol = _nonlinear_3eq_order1_type2(x, y, z, t, eq)
return sol
def _nonlinear_3eq_order1_type1(x, y, z, t, eq):
r"""
Equations:
.. math:: a x' = (b - c) y z, \enspace b y' = (c - a) z x, \enspace c z' = (a - b) x y
First Integrals:
.. math:: a x^{2} + b y^{2} + c z^{2} = C_1
.. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2
where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and
`z` and on substituting the resulting expressions into the first equation of the
system, we arrives at a separable first-order equation on `x`. Similarly doing that
for other two equations, we will arrive at first order equation on `y` and `z` too.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0401.pdf
"""
C1, C2 = get_numbered_constants(eq, num=2)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
r = (diff(x(t), t) - eq[0]).match(p*y(t)*z(t))
r.update((diff(y(t), t) - eq[1]).match(q*z(t)*x(t)))
r.update((diff(z(t), t) - eq[2]).match(s*x(t)*y(t)))
n1, d1 = r[p].as_numer_denom()
n2, d2 = r[q].as_numer_denom()
n3, d3 = r[s].as_numer_denom()
val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, d3*u-d3*v-n3*w], [u, v])[0]
vals = [val[v], val[u]]
c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1])
b = vals[0].subs({w: c})
a = vals[1].subs({w: c})
y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b)))
z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c)))
z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c)))
x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a)))
x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a)))
y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b)))
sol1 = dsolve(a*diff(x(t), t) - (b-c)*y_x*z_x, hint='separable_Integral')
sol2 = dsolve(b*diff(y(t), t) - (c-a)*z_y*x_y, hint='separable_Integral')
sol3 = dsolve(c*diff(z(t), t) - (a-b)*x_z*y_z, hint='separable_Integral')
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _nonlinear_3eq_order1_type2(x, y, z, t, eq):
r"""
Equations:
.. math:: a x' = (b - c) y z f(x, y, z, t)
.. math:: b y' = (c - a) z x f(x, y, z, t)
.. math:: c z' = (a - b) x y f(x, y, z, t)
First Integrals:
.. math:: a x^{2} + b y^{2} + c z^{2} = C_1
.. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2
where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and
`z` and on substituting the resulting expressions into the first equation of the
system, we arrives at a first-order differential equations on `x`. Similarly doing
that for other two equations we will arrive at first order equation on `y` and `z`.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0402.pdf
"""
C1, C2 = get_numbered_constants(eq, num=2)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
f = Wild('f')
r1 = (diff(x(t), t) - eq[0]).match(y(t)*z(t)*f)
r = collect_const(r1[f]).match(p*f)
r.update(((diff(y(t), t) - eq[1])/r[f]).match(q*z(t)*x(t)))
r.update(((diff(z(t), t) - eq[2])/r[f]).match(s*x(t)*y(t)))
n1, d1 = r[p].as_numer_denom()
n2, d2 = r[q].as_numer_denom()
n3, d3 = r[s].as_numer_denom()
val = solve([n1*u - d1*v + d1*w, d2*u + n2*v - d2*w, -d3*u + d3*v + n3*w], [u, v])[0]
vals = [val[v], val[u]]
c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1])
a = vals[0].subs({w: c})
b = vals[1].subs({w: c})
y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b)))
z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c)))
z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c)))
x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a)))
x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a)))
y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b)))
sol1 = dsolve(a*diff(x(t), t) - (b - c)*y_x*z_x*r[f], hint='separable_Integral')
sol2 = dsolve(b*diff(y(t), t) - (c - a)*z_y*x_y*r[f], hint='separable_Integral')
sol3 = dsolve(c*diff(z(t), t) - (a - b)*x_z*y_z*r[f], hint='separable_Integral')
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
| bsd-3-clause | e6533d1ef6b0070bbf8af2975e360a56 | 38.250796 | 386 | 0.535444 | 3.169011 | false | false | false | false |
diofant/diofant | diofant/tests/simplify/test_cse.py | 1 | 14074 | import itertools
import pytest
from diofant import (Add, Eq, Function, Idx, ImmutableDenseMatrix,
ImmutableSparseMatrix, IndexedBase, Matrix, MatrixSymbol,
MutableDenseMatrix, MutableSparseMatrix, O, Piecewise,
Pow, Rational, RootOf, Subs, Symbol, Tuple, cos, cse, exp,
meijerg, sin, sqrt, symbols, sympify, true)
from diofant.abc import a, b, w, x, y, z
from diofant.simplify import cse_main, cse_opts
from diofant.simplify.cse_opts import sub_post, sub_pre
__all__ = ()
x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12 = symbols('x:13')
def test_numbered_symbols():
ns = cse_main.numbered_symbols(prefix='y')
assert list(itertools.islice(
ns, 0, 10)) == [Symbol(f'y{i}') for i in range(10)]
ns = cse_main.numbered_symbols(prefix='y')
assert list(itertools.islice(
ns, 10, 20)) == [Symbol(f'y{i}') for i in range(10, 20)]
ns = cse_main.numbered_symbols()
assert list(itertools.islice(
ns, 0, 10)) == [Symbol(f'x{i}') for i in range(10)]
# Dummy "optimization" functions for testing.
def opt1(expr):
return expr + y
def opt2(expr):
return expr*z
def test_preprocess_for_cse():
assert cse_main.preprocess_for_cse(x, [(opt1, None)]) == x + y
assert cse_main.preprocess_for_cse(x, [(None, opt1)]) == x
assert cse_main.preprocess_for_cse(x, [(None, None)]) == x
assert cse_main.preprocess_for_cse(x, [(opt1, opt2)]) == x + y
assert cse_main.preprocess_for_cse(
x, [(opt1, None), (opt2, None)]) == (x + y)*z
def test_postprocess_for_cse():
assert cse_main.postprocess_for_cse(x, [(opt1, None)]) == x
assert cse_main.postprocess_for_cse(x, [(None, opt1)]) == x + y
assert cse_main.postprocess_for_cse(x, [(None, None)]) == x
assert cse_main.postprocess_for_cse(x, [(opt1, opt2)]) == x*z
# Note the reverse order of application.
assert cse_main.postprocess_for_cse(
x, [(None, opt1), (None, opt2)]) == x*z + y
def test_cse_single():
# Simple substitution.
e = Add(Pow(x + y, 2), sqrt(x + y))
substs, reduced = cse([e])
assert substs == [(x0, x + y)]
assert reduced == [sqrt(x0) + x0**2]
assert cse([e], order='none') == cse([e])
def test_cse_single2():
# Simple substitution, test for being able to pass the expression directly
e = Add(Pow(x + y, 2), sqrt(x + y))
substs, reduced = cse(e)
assert substs == [(x0, x + y)]
assert reduced == [sqrt(x0) + x0**2]
substs, reduced = cse(Matrix([[1]]))
assert isinstance(reduced[0], Matrix)
def test_cse_not_possible():
# No substitution possible.
e = Add(x, y)
substs, reduced = cse([e])
assert not substs
assert reduced == [x + y]
# issue sympy/sympy#6329
eq = (meijerg((1, 2), (y, 4), (5,), [], x) +
meijerg((1, 3), (y, 4), (5,), [], x))
assert cse(eq) == ([], [eq])
def test_nested_substitution():
# Substitution within a substitution.
e = Add(Pow(w*x + y, 2), sqrt(w*x + y))
substs, reduced = cse([e])
assert substs == [(x0, w*x + y)]
assert reduced == [sqrt(x0) + x0**2]
def test_subtraction_opt():
# Make sure subtraction is optimized.
e = (x - y)*(z - y) + exp((x - y)*(z - y))
substs, reduced = cse(
[e], optimizations=[(cse_opts.sub_pre, cse_opts.sub_post)])
assert substs == [(x0, (x - y)*(y - z))]
assert reduced == [-x0 + exp(-x0)]
e = -(x - y)*(z - y) + exp(-(x - y)*(z - y))
substs, reduced = cse(
[e], optimizations=[(cse_opts.sub_pre, cse_opts.sub_post)])
assert substs == [(x0, (x - y)*(y - z))]
assert reduced == [x0 + exp(x0)]
# issue sympy/sympy#4077
n = -1 + 1/x
e = n/x/(-n)**2 - 1/n/x
assert cse(e, optimizations=[(cse_opts.sub_pre, cse_opts.sub_post)]) == \
([], [0])
def test_multiple_expressions():
e1 = (x + y)*z
e2 = (x + y)*w
substs, reduced = cse([e1, e2])
assert substs == [(x0, x + y)]
assert reduced == [x0*z, x0*w]
l = [w*x*y + z, w*y]
substs, reduced = cse(l)
rsubsts, _ = cse(reversed(l))
assert substs == rsubsts
assert reduced == [z + x*x0, x0]
l = [w*x*y, w*x*y + z, w*y]
substs, reduced = cse(l)
rsubsts, _ = cse(reversed(l))
assert substs == rsubsts
assert reduced == [x1, x1 + z, x0]
l = [(x - z)*(y - z), x - z, y - z]
substs, reduced = cse(l)
rsubsts, _ = cse(reversed(l))
assert substs == [(x0, -z), (x1, x + x0), (x2, x0 + y)]
assert rsubsts == [(x0, -z), (x1, x0 + y), (x2, x + x0)]
assert reduced == [x1*x2, x1, x2]
l = [w*y + w + x + y + z, w*x*y]
assert cse(l) == ([(x0, w*y)], [w + x + x0 + y + z, x*x0])
assert cse([x + y, x + y + z]) == ([(x0, x + y)], [x0, z + x0])
assert cse([x + y, x + z]) == ([], [x + y, x + z])
assert cse([x*y, z + x*y, x*y*z + 3]) == \
([(x0, x*y)], [x0, z + x0, 3 + x0*z])
def test_non_commutative_cse():
A, B, C = symbols('A B C', commutative=False)
l = [A*B*C, A*C]
assert cse(l) == ([], l)
@pytest.mark.xfail
def test_non_commutative_cse_mul():
x0 = symbols('x0', commutative=False)
A, B, C = symbols('A B C', commutative=False)
l = [A*B*C, A*B]
assert cse(l) == ([(x0, A*B)], [x0*C, x0])
# Test if CSE of non-commutative Mul terms is disabled
def test_bypass_non_commutatives():
A, B, C = symbols('A B C', commutative=False)
l = [A*B*C, A*C]
assert cse(l) == ([], l)
l = [A*B*C, A*B]
assert cse(l) == ([], l)
l = [B*C, A*B*C]
assert cse(l) == ([], l)
def test_non_commutative_order():
A, B, C = symbols('A B C', commutative=False)
x0 = symbols('x0', commutative=False)
l = [B+C, A*(B+C)]
assert cse(l) == ([(x0, B+C)], [x0, A*x0])
l = [(A - B)**2 + A - B]
assert cse(l) == ([(x0, A - B)], [x0**2 + x0])
@pytest.mark.xfail
def test_powers():
assert cse(x*y**2 + x*y) == ([(x0, x*y)], [x0*y + x0])
def test_basic_optimization():
# issue sympy/sympy#4498
assert cse(w/(x - y) + z/(y - x), optimizations='basic') == \
([], [(w - z)/(x - y)])
def test_sympyissue_4020():
assert cse(x**5 + x**4 + x**3 + x**2, optimizations='basic') \
== ([(x0, x**2)], [x0*(x**3 + x + x0 + 1)])
def test_sympyissue_4203():
assert cse(sin(x**x)/x**x) == ([(x0, x**x)], [sin(x0)/x0])
def test_sympyissue_6263():
e = Eq(x*(-x + 1) + x*(x - 1), 0)
assert cse(e, optimizations='basic') == ([], [True])
def test_dont_cse_tuples():
f = Function('f')
g = Function('g')
name_val, (expr,) = cse(Subs(f(x, y), (x, 0), (y, 1)) +
Subs(g(x, y), (x, 0), (y, 1)))
assert not name_val
assert expr == (Subs(f(x, y), (x, 0), (y, 1))
+ Subs(g(x, y), (x, 0), (y, 1)))
name_val, (expr,) = cse(Subs(f(x, y), (x, 0), (y, x + y)) +
Subs(g(x, y), (x, 0), (y, x + y)))
assert name_val == [(x0, x + y)]
assert expr == Subs(f(x, y), (x, 0), (y, x0)) + Subs(g(x, y), (x, 0), (y, x0))
def test_pow_invpow():
assert cse(1/x**2 + x**2) == \
([(x0, x**2)], [x0 + 1/x0])
assert cse(x**2 + (1 + 1/x**2)/x**2) == \
([(x0, x**2), (x1, 1/x0)], [x0 + x1*(x1 + 1)])
assert cse(1/x**2 + (1 + 1/x**2)*x**2) == \
([(x0, x**2), (x1, 1/x0)], [x0*(x1 + 1) + x1])
assert cse(cos(1/x**2) + sin(1/x**2)) == \
([(x0, x**(-2))], [sin(x0) + cos(x0)])
assert cse(cos(x**2) + sin(x**2)) == \
([(x0, x**2)], [sin(x0) + cos(x0)])
assert cse(y/(2 + x**2) + z/x**2/y) == \
([(x0, x**2)], [y/(x0 + 2) + z/(x0*y)])
assert cse(exp(x**2) + x**2*cos(1/x**2)) == \
([(x0, x**2)], [x0*cos(1/x0) + exp(x0)])
assert cse((1 + 1/x**2)/x**2) == \
([(x0, x**(-2))], [x0*(x0 + 1)])
assert cse(x**(2*y) + x**(-2*y)) == \
([(x0, x**(2*y))], [x0 + 1/x0])
def test_postprocess():
eq = (x + 1 + exp((x + 1)/(y + 1)) + cos(y + 1))
assert cse([eq, Eq(x, z + 1), z - 2, (z + 1)*(x + 1)],
postprocess=cse_main.cse_separate) == \
[[(x1, y + 1), (x2, z + 1), (x, x2), (x0, x + 1)],
[x0 + exp(x0/x1) + cos(x1), z - 2, x0*x2]]
def test_sympyissue_4499():
# previously, this gave 16 constants
B = Function('B')
G = Function('G')
t = Tuple(*
(a, a + Rational(1, 2), 2*a, b, 2*a - b + 1, (sqrt(z)/2)**(-2*a + 1)*B(2*a -
b, sqrt(z))*B(b - 1, sqrt(z))*G(b)*G(2*a - b + 1),
sqrt(z)*(sqrt(z)/2)**(-2*a + 1)*B(b, sqrt(z))*B(2*a - b,
sqrt(z))*G(b)*G(2*a - b + 1), sqrt(z)*(sqrt(z)/2)**(-2*a + 1)*B(b - 1,
sqrt(z))*B(2*a - b + 1, sqrt(z))*G(b)*G(2*a - b + 1),
(sqrt(z)/2)**(-2*a + 1)*B(b, sqrt(z))*B(2*a - b + 1,
sqrt(z))*G(b)*G(2*a - b + 1), 1, 0, Rational(1, 2), z/2, -b + 1, -2*a + b,
-2*a))
c = cse(t)
ans = (
[(x0, 2*a), (x1, -b), (x2, x1 + 1), (x3, x0 + x2), (x4, sqrt(z)), (x5,
B(x0 + x1, x4)), (x6, G(b)), (x7, G(x3)), (x8, -x0), (x9,
(x4/2)**(x8 + 1)), (x10, x6*x7*x9*B(b - 1, x4)), (x11, x6*x7*x9*B(b,
x4)), (x12, B(x3, x4))], [(a, a + Rational(1, 2), x0, b, x3, x10*x5,
x11*x4*x5, x10*x12*x4, x11*x12, 1, 0, Rational(1, 2), z/2, x2, b + x8, x8)])
assert ans == c
def test_sympyissue_6169():
r = RootOf(x**6 - 4*x**5 - 2, 1)
assert cse(r) == ([], [r])
# and a check that the right thing is done with the new
# mechanism
assert sub_post(sub_pre((-x - y)*z - x - y)) == -z*(x + y) - x - y
def test_cse_Indexed():
len_y = 5
y = IndexedBase('y', shape=(len_y,))
x = IndexedBase('x', shape=(len_y,))
i = Idx('i', len_y-1)
expr1 = (y[i+1]-y[i])/(x[i+1]-x[i])
expr2 = 1/(x[i+1]-x[i])
replacements, _ = cse([expr1, expr2])
assert len(replacements) > 0
@pytest.mark.xfail
def test_cse_MatrixSymbol():
A = MatrixSymbol('A', 3, 3)
y = MatrixSymbol('y', 3, 1)
expr1 = (A.T*A).inverse() * A * y
expr2 = (A.T*A) * A * y
replacements, _ = cse([expr1, expr2])
assert len(replacements) > 0
def test_Piecewise():
f = Piecewise((-z + x*y, Eq(y, 0)), (-z - x*y, True))
ans = cse(f)
actual_ans = ([(x0, -z), (x1, x*y)], [Piecewise((x0+x1, Eq(y, 0)), (x0 - x1, True))])
assert ans == actual_ans
def test_ignore_order_terms():
eq = exp(x).series(x, 0, 3) + sin(y + x**3) - 1
assert cse(eq) == ([], [sin(x**3 + y) + x + x**2/2 + O(x**3)])
def test_name_conflict():
z1 = x0 + y
z2 = x2 + x3
l = [cos(z1) + z1, cos(z2) + z2, x0 + x2]
substs, reduced = cse(l)
assert [e.subs(reversed(substs)) for e in reduced] == l
def test_name_conflict_cust_symbols():
z1 = x0 + y
z2 = x2 + x3
l = [cos(z1) + z1, cos(z2) + z2, x0 + x2]
substs, reduced = cse(l, symbols('x:10'))
assert [e.subs(reversed(substs)) for e in reduced] == l
def test_symbols_exhausted_error():
l = cos(x+y)+x+y+cos(w+y)+sin(w+y)
sym = [x, y, z]
with pytest.raises(ValueError):
cse(l, symbols=sym)
def test_sympyissue_7840():
# daveknippers' example
C393 = sympify(
'Piecewise((C391 - 1.65, C390 < 0.5), (Piecewise((C391 - 1.65, \
C391 > 2.35), (C392, True)), True))'
)
C391 = sympify(
'Piecewise((2.05*C390**(-1.03), C390 < 0.5), (2.5*C390**(-0.625), True))'
)
C393 = C393.subs({'C391': C391})
# simple substitution
sub = {}
sub['C390'] = 0.703451854
sub['C392'] = 1.01417794
ss_answer = C393.subs(sub)
# cse
substitutions, new_eqn = cse(C393)
for pair in substitutions:
sub[pair[0].name] = pair[1].subs(sub)
cse_answer = new_eqn[0].subs(sub)
# both methods should be the same
assert ss_answer == cse_answer
# GitRay's example
expr = Piecewise((Symbol('ON'), Eq(Symbol('mode'), Symbol('ON'))),
(Piecewise((Piecewise((Symbol('OFF'), Symbol('x') < Symbol('threshold')),
(Symbol('ON'), true)), Eq(Symbol('mode'), Symbol('AUTO'))),
(Symbol('OFF'), true)), true))
substitutions, new_eqn = cse(expr)
# this Piecewise should be exactly the same
assert new_eqn[0] == expr
# there should not be any replacements
assert len(substitutions) < 1
def test_matrices():
# issue sympy/sympy#8891
for cls in (MutableDenseMatrix, MutableSparseMatrix,
ImmutableDenseMatrix, ImmutableSparseMatrix):
m = cls(2, 2, [x + y, 0, 0, 0])
res = cse([x + y, m])
ans = ([(x0, x + y)], [x0, cls([[x0, 0], [0, 0]])])
assert res == ans
assert isinstance(res[1][-1], cls)
def test_cse_ignore():
exprs = [exp(y)*(3*y + 3*sqrt(x+1)), exp(y)*(5*y + 5*sqrt(x+1))]
subst1, _ = cse(exprs)
assert any(y in sub.free_symbols for _, sub in subst1), 'cse failed to identify any term with y'
subst2, _ = cse(exprs, ignore=(y,)) # y is not allowed in substitutions
assert not any(y in sub.free_symbols for _, sub in subst2), 'Sub-expressions containing y must be ignored'
assert any(sub - sqrt(x + 1) == 0 for _, sub in subst2), 'cse failed to identify sqrt(x + 1) as sub-expression'
| bsd-3-clause | b3de8add718da2f43e294d7e2b3bdcfc | 34.450882 | 298 | 0.473 | 2.662505 | false | true | false | false |
diofant/diofant | diofant/simplify/ratsimp.py | 1 | 7308 | from itertools import combinations_with_replacement
from ..core import Add, Dummy, Rational, symbols
from ..polys import (ComputationFailed, Poly, cancel, parallel_poly_from_expr,
reduced)
from ..polys.monomials import Monomial
def ratsimp(expr):
"""
Put an expression over a common denominator, cancel and reduce.
Examples
========
>>> ratsimp(1/x + 1/y)
(x + y)/(x*y)
"""
f, g = cancel(expr).as_numer_denom()
try:
Q, r = reduced(f, [g], field=True, expand=False)
except ComputationFailed:
return f/g
return Add(*Q) + cancel(r/g)
def ratsimpmodprime(expr, G, *gens, **args):
"""
Simplifies a rational expression ``expr`` modulo the prime ideal
generated by ``G``. ``G`` should be a Gröbner basis of the
ideal.
>>> eq = (x + y**5 + y)/(x - y)
>>> ratsimpmodprime(eq, [x*y**5 - x - y], x, y, order='lex')
(x**2 + x*y + x + y)/(x**2 - x*y)
If ``polynomial`` is False, the algorithm computes a rational
simplification which minimizes the sum of the total degrees of
the numerator and the denominator.
If ``polynomial`` is True, this function just brings numerator and
denominator into a canonical form. This is much faster, but has
potentially worse results.
References
==========
M. Monagan, R. Pearce, Rational Simplification Modulo a Polynomial
Ideal,
http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.163.6984
(specifically, the second algorithm)
"""
from ..matrices import Matrix, zeros
from ..solvers.solvers import minsolve_linear_system
quick = args.pop('quick', True)
polynomial = args.pop('polynomial', False)
# usual preparation of polynomials:
num, denom = cancel(expr).as_numer_denom()
polys, opt = parallel_poly_from_expr([num, denom] + G, *gens, **args)
domain = opt.domain
opt.domain = domain.field
# compute only once
leading_monomials = [g.LM(opt.order) for g in polys[2:]]
tested = set()
def staircase(n):
"""
Compute all monomials with degree less than ``n`` that are
not divisible by any element of ``leading_monomials``.
"""
if n == 0:
return [1]
S = []
for mi in combinations_with_replacement(range(len(opt.gens)), n):
m = [0]*len(opt.gens)
for i in mi:
m[i] += 1
if all(not lmg.divides(m) for lmg in leading_monomials):
S.append(m)
return [Monomial(s).as_expr(*opt.gens) for s in S] + staircase(n - 1)
def _ratsimpmodprime(a, b, allsol, N=0, D=0):
r"""
Computes a rational simplification of ``a/b`` which minimizes
the sum of the total degrees of the numerator and the denominator.
The algorithm proceeds by looking at ``a * d - b * c`` modulo
the ideal generated by ``G`` for some ``c`` and ``d`` with degree
less than ``a`` and ``b`` respectively.
The coefficients of ``c`` and ``d`` are indeterminates and thus
the coefficients of the normalform of ``a * d - b * c`` are
linear polynomials in these indeterminates.
If these linear polynomials, considered as system of
equations, have a nontrivial solution, then `\frac{a}{b}
\equiv \frac{c}{d}` modulo the ideal generated by ``G``. So,
by construction, the degree of ``c`` and ``d`` is less than
the degree of ``a`` and ``b``, so a simpler representation
has been found.
After a simpler representation has been found, the algorithm
tries to reduce the degree of the numerator and denominator
and returns the result afterwards.
As an extension, if quick=False, we look at all possible degrees such
that the total degree is less than *or equal to* the best current
solution. We retain a list of all solutions of minimal degree, and try
to find the best one at the end.
"""
c, d = a, b
steps = 0
maxdeg = a.total_degree() + b.total_degree()
if quick:
bound = maxdeg - 1
else:
bound = maxdeg
while N + D <= bound:
if (N, D) in tested:
break
tested.add((N, D))
M1 = staircase(N)
M2 = staircase(D)
Cs = symbols(f'c:{len(M1):d}', cls=Dummy)
Ds = symbols(f'd:{len(M2):d}', cls=Dummy)
ng = Cs + Ds
c_hat = Poly(
sum(Cs[i] * M1[i] for i in range(len(M1))), *(opt.gens + ng))
d_hat = Poly(
sum(Ds[i] * M2[i] for i in range(len(M2))), *(opt.gens + ng))
r = reduced(a * d_hat - b * c_hat, G, *(opt.gens + ng),
order=opt.order, polys=True)[1]
S = Poly(r, gens=opt.gens).coeffs()
Sv = Cs + Ds
Sm = zeros(len(S), len(Sv) + 1)
Sm[:, :-1] = Matrix([[a.diff(b) for b in Sv] for a in S])
sol = minsolve_linear_system(Sm, *Sv, quick=True)
if sol and not all(s == 0 for s in sol.values()):
c = c_hat.subs(sol)
d = d_hat.subs(sol)
# The "free" variables occuring before as parameters
# might still be in the substituted c, d, so set them
# to the value chosen before:
c = c.subs(dict(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))
d = d.subs(dict(zip(Cs + Ds, [1] * (len(Cs) + len(Ds)))))
c = Poly(c, *opt.gens)
d = Poly(d, *opt.gens)
if d == 0:
raise ValueError('Ideal not prime?')
allsol.append((c_hat, d_hat, S, Cs + Ds))
if N + D != maxdeg:
allsol = [allsol[-1]]
break
steps += 1
N += 1
D += 1
if steps > 0:
c, d, allsol = _ratsimpmodprime(c, d, allsol, N, D - steps)
c, d, allsol = _ratsimpmodprime(c, d, allsol, N - steps, D)
return c, d, allsol
# preprocessing. this improves performance a bit when deg(num)
# and deg(denom) are large:
num = reduced(num, G, *opt.gens, order=opt.order)[1]
denom = reduced(denom, G, *opt.gens, order=opt.order)[1]
if polynomial:
return (num/denom).cancel()
c, d, allsol = _ratsimpmodprime(
Poly(num, *opt.gens, domain=opt.domain), Poly(denom, *opt.gens, domain=opt.domain), [])
if not quick and allsol:
# Looking for best minimal solution.
newsol = []
for c_hat, d_hat, S, ng in allsol:
Sm = zeros(len(S), len(ng) + 1)
Sm[:, :-1] = Matrix([[a.diff(b) for b in ng] for a in S])
sol = minsolve_linear_system(Sm, *ng)
newsol.append((c_hat.subs(sol), d_hat.subs(sol)))
c, d = min(newsol, key=lambda x: len(x[0].terms()) + len(x[1].terms()))
if not domain.is_Field:
cn, c = c.clear_denoms(convert=True)
dn, d = d.clear_denoms(convert=True)
else:
cn, dn = 1, 1
cf, c, d = cancel((c, d), *opt.gens, order=opt.order) # canonicalize signs
r = cf*Rational(cn, dn)
return (c*r.denominator)/(d*r.numerator)
| bsd-3-clause | a52adff774fafb34165994f44ad349ba | 33.305164 | 95 | 0.54742 | 3.486164 | false | false | false | false |
diofant/diofant | diofant/matrices/expressions/matadd.py | 1 | 3298 | import functools
import operator
from ...core import Add, Expr
from ...core.logic import _fuzzy_group
from ...core.strategies import (condition, do_one, exhaust, flatten, glom,
rm_id, sort, unpack)
from ...core.sympify import sympify
from ...functions import adjoint
from ...utilities import default_sort_key, sift
from ..matrices import MatrixBase, ShapeError
from .matexpr import MatrixExpr, ZeroMatrix
from .transpose import transpose
class MatAdd(MatrixExpr):
"""A Sum of Matrix Expressions
MatAdd inherits from and operates like Diofant Add
>>> A = MatrixSymbol('A', 5, 5)
>>> B = MatrixSymbol('B', 5, 5)
>>> C = MatrixSymbol('C', 5, 5)
>>> MatAdd(A, B, C)
A + B + C
"""
is_MatAdd = True
def _eval_is_commutative(self):
return _fuzzy_group((a.is_commutative for a in self.args),
quick_exit=True)
def __new__(cls, *args, **kwargs):
args = list(map(sympify, args))
check = kwargs.get('check', True)
obj = Expr.__new__(cls, *args)
if check:
validate(*args)
return obj
@property
def shape(self):
return self.args[0].shape
def _entry(self, i, j):
return Add(*[arg._entry(i, j) for arg in self.args])
def _eval_transpose(self):
return MatAdd(*[transpose(arg) for arg in self.args]).doit()
def _eval_adjoint(self):
return MatAdd(*[adjoint(arg) for arg in self.args]).doit()
def _eval_trace(self):
from .trace import trace
return Add(*[trace(arg) for arg in self.args]).doit()
def doit(self, **kwargs):
deep = kwargs.get('deep', True)
if deep:
args = [arg.doit(**kwargs) for arg in self.args]
else:
args = self.args
return canonicalize(MatAdd(*args))
def validate(*args):
if not all(arg.is_Matrix for arg in args):
raise TypeError('Mix of Matrix and Scalar symbols')
A = args[0]
for B in args[1:]:
if A.shape != B.shape:
raise ShapeError(f'Matrices {A} and {B} are not aligned')
def factor_of(arg):
return arg.as_coeff_mmul()[0]
def matrix_of(arg):
return unpack(arg.as_coeff_mmul()[1])
def combine(cnt, mat):
if cnt == 1:
return mat
else:
return cnt * mat
def merge_explicit(matadd):
"""Merge explicit MatrixBase arguments
>>> A = MatrixSymbol('A', 2, 2)
>>> B = eye(2)
>>> C = Matrix([[1, 2], [3, 4]])
>>> X = MatAdd(A, B, C)
>>> pprint(X, use_unicode=False)
[1 0] [1 2]
A + [ ] + [ ]
[0 1] [3 4]
>>> pprint(merge_explicit(X), use_unicode=False)
[2 2]
A + [ ]
[3 5]
"""
groups = sift(matadd.args, lambda arg: isinstance(arg, MatrixBase))
if len(groups[True]) > 1:
return MatAdd(*(groups[False] + [functools.reduce(operator.add, groups[True])]))
else:
return matadd
rules = (rm_id(lambda x: x == 0 or isinstance(x, ZeroMatrix)),
unpack,
flatten,
glom(matrix_of, factor_of, combine),
merge_explicit,
sort(default_sort_key))
canonicalize = exhaust(condition(lambda x: isinstance(x, MatAdd),
do_one(rules)))
| bsd-3-clause | 016f41fffb4fe2d9f4ed898f5f890884 | 25.384 | 88 | 0.565797 | 3.475237 | false | false | false | false |
diofant/diofant | diofant/solvers/polysys.py | 1 | 7387 | """Solvers of systems of polynomial equations."""
import collections
from ..core import expand_mul
from ..domains import EX
from ..matrices import Matrix
from ..polys import (ComputationFailed, PolificationFailed, groebner,
parallel_poly_from_expr)
from ..polys.solvers import solve_lin_sys
from ..simplify.simplify import simplify
from ..utilities import default_sort_key, numbered_symbols
from .utils import checksol
__all__ = ('solve_linear_system', 'solve_poly_system',
'solve_surd_system')
def solve_linear_system(system, *symbols, **flags):
r"""Solve system of linear equations.
Both under- and overdetermined systems are supported. The possible
number of solutions is zero, one or infinite.
Parameters
==========
system : Matrix
Nx(M+1) matrix, which means it has to be in augmented
form. This matrix will not be modified.
\*symbols : list
List of M Symbol's
Returns
=======
solution: dict or None
Respectively, this procedure will return None or
a dictionary with solutions. In the case of underdetermined
systems, all arbitrary parameters are skipped. This may
cause a situation in which an empty dictionary is returned.
In that case, all symbols can be assigned arbitrary values.
Examples
========
Solve the following system::
x + 4 y == 2
-2 x + y == 14
>>> system = Matrix(((1, 4, 2), (-2, 1, 14)))
>>> solve_linear_system(system, x, y)
{x: -6, y: 2}
A degenerate system returns an empty dictionary.
>>> system = Matrix(((0, 0, 0), (0, 0, 0)))
>>> solve_linear_system(system, x, y)
{}
See Also
========
diofant.matrices.matrices.MatrixBase.rref
"""
eqs = system*Matrix(symbols + (-1,))
polys, _ = parallel_poly_from_expr([expand_mul(e) for e in eqs],
*symbols, field=True)
domain = polys[0].rep.ring
polys = [_.rep for _ in polys]
res = solve_lin_sys(polys, domain)
if res is None:
return
for k in list(res):
s = domain.symbols[domain.index(k)]
res[s] = domain.to_expr(res[k])
del res[k]
if flags.get('simplify', True):
res[s] = simplify(res[s])
return res
def solve_poly_system(eqs, *gens, **args):
"""
Solve a system of polynomial equations.
Polynomial system may have finite number of solutions or
infinitely many (positive-dimensional systems).
References
==========
* :cite:`Cox2015ideals`, p. 98
Examples
========
>>> solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y)
[{x: 0, y: 0}, {x: 2, y: -sqrt(2)}, {x: 2, y: sqrt(2)}]
>>> solve_poly_system([x*y], x, y)
[{x: 0}, {y: 0}]
"""
try:
args['extension'] = False
polys, opt = parallel_poly_from_expr(eqs, *gens, **args)
polys = [p.to_exact() for p in polys]
except PolificationFailed as exc:
raise ComputationFailed('solve_poly_system', len(eqs), exc) from exc
def _solve_reduced_system(system, gens):
"""Recursively solves reduced polynomial systems."""
basis = groebner(system, *gens, polys=True, extension=False)
dim = basis.dimension
solutions = []
if dim is None:
return []
elif dim > 0:
max_iset = max(basis.independent_sets, key=len)
new_gens = [g for g in gens if g not in max_iset]
# After removing variables from the maximal set of independent
# variables for the given ideal - the new ideal is of dimension
# zero with the independent variables as parameters in the
# coefficient domain.
solutions.extend(_solve_reduced_system(system, new_gens))
# Now we should examine cases when leading coefficient of
# some polynomial in the system is zero.
for p in basis.polys:
lc = p.as_poly(*new_gens).LC(order=basis.order)
for special in _solve_reduced_system(system + [lc], gens):
# This heuristics wipe out some redundant special
# solutions, which already there in solutions after
# solving the system with new set of generators.
if all(any((_.subs(s) - _).subs(special).simplify()
for _ in gens) for s in solutions):
solutions.insert(0, special)
else:
# By the elimination property, the last polynomial should
# be univariate in the last variable.
f = basis[-1]
gen = gens[-1]
zeros = {k.doit() for k in f.exclude().all_roots()}
if len(basis) == 1:
return [{gen: zero} for zero in zeros]
new_basis = [b.set_domain(EX) for b in basis[:-1]]
# Now substitute zeros for the last variable and
# solve recursively new obtained zero-dimensional systems.
for zero in zeros:
new_system = []
new_gens = gens[:-1]
for b in new_basis:
eq = b.eval(gen, zero)
if not eq.is_zero:
new_system.append(eq)
for solution in _solve_reduced_system(new_system, new_gens):
solution[gen] = zero
solutions.append(solution)
return solutions
result = _solve_reduced_system(polys, opt.gens)
if not opt.domain.is_Exact:
result = [{k: r[k].evalf(opt.domain.dps) for k in r} for r in result]
return sorted(result, key=default_sort_key)
def solve_surd_system(eqs, *gens, **args):
"""
Solve a system of algebraic equations.
Examples
========
>>> solve_surd_system([x + sqrt(x + 1) - 2])
[{x: -sqrt(13)/2 + 5/2}]
"""
eqs = list(eqs)
if not gens:
gens = set().union(*[_.free_symbols for _ in eqs])
gens = sorted(gens, key=default_sort_key)
else:
gens = list(gens)
aux = numbered_symbols('a')
neqs = len(eqs)
orig_eqs = eqs[:]
ngens = len(gens)
bases = collections.defaultdict(dict)
def q_surd(e):
return e.is_Pow and e.exp.is_Rational and not e.exp.is_Integer
def tr_surd(e):
n, d = e.exp.as_numer_denom()
for v2, d2 in sorted(bases.get(e.base, {}).items(),
key=lambda _: -_[1]):
if not d2 % d:
return v2**(d2 // d)
v = next(aux)
bases[e.base][v] = d
gens.append(v)
eqs.append(v**d - e.base)
return v**n
for i in range(neqs):
eqs[i] = eqs[i].replace(q_surd, tr_surd)
denoms = []
for i, e in enumerate(eqs):
eqs[i], d = e.as_numer_denom()
if not d.is_constant(*gens):
denoms.insert(0, d)
weaksols = solve_poly_system(eqs, *gens, **args)
for i in range(len(weaksols) - 1, -1, -1):
if any(checksol(_, weaksols[i], warn=True) for _ in denoms):
del weaksols[i]
elif any(checksol(_, weaksols[i], warn=True) is False for _ in orig_eqs):
del weaksols[i]
else:
for g in gens[ngens:]:
del weaksols[i][g]
return weaksols
| bsd-3-clause | 8ba7be4c000fe2c8da0476b44f36cdae | 28.78629 | 81 | 0.553946 | 3.684289 | false | false | false | false |
diofant/diofant | diofant/sets/fancysets.py | 1 | 13184 | """Special sets."""
from ..core import Basic, Expr, Integer, Lambda, Rational, S, oo
from ..core.compatibility import as_int
from ..core.singleton import Singleton
from ..core.sympify import converter, sympify
from ..logic import false, true
from ..utilities.iterables import cantor_product
from .sets import EmptySet, FiniteSet, Intersection, Interval, Set
class Naturals(Set, metaclass=Singleton):
"""The set of natural numbers.
Represents the natural numbers (or counting numbers) which are all
positive integers starting from 1. This set is also available as
the Singleton, S.Naturals.
Examples
========
>>> 5 in S.Naturals
True
>>> iterable = iter(S.Naturals)
>>> next(iterable)
1
>>> next(iterable)
2
>>> next(iterable)
3
>>> S.Naturals.intersection(Interval(0, 10))
Range(1, 11, 1)
See Also
========
Naturals0 : non-negative integers
Integers : also includes negative integers
"""
is_iterable = True
inf = Integer(1)
sup = oo
def _intersection(self, other):
if other.is_Interval:
return Intersection(
S.Integers, other, Interval(self.inf, oo, False, True))
def _contains(self, other):
if not isinstance(other, Expr):
return false
elif other.is_positive and other.is_integer:
return true
elif other.is_integer is False or other.is_positive is False:
return false
def __iter__(self):
i = self.inf
while True:
yield i
i = i + 1
@property
def boundary(self):
return self
class Naturals0(Naturals):
"""The set of natural numbers, starting from 0.
Represents the whole numbers which are all the non-negative
integers, inclusive of zero.
See Also
========
Naturals : positive integers
Integers : also includes the negative integers
"""
inf = Integer(0)
def _contains(self, other):
if not isinstance(other, Expr):
return false
elif other.is_integer and other.is_nonnegative:
return true
elif other.is_integer is False or other.is_nonnegative is False:
return false
class Integers(Set, metaclass=Singleton):
"""The set of all integers.
Represents all integers: positive, negative and zero. This set
is also available as the Singleton, S.Integers.
Examples
========
>>> 5 in S.Naturals
True
>>> iterable = iter(S.Integers)
>>> next(iterable)
0
>>> next(iterable)
1
>>> next(iterable)
-1
>>> next(iterable)
2
>>> S.Integers.intersection(Interval(-4, 4))
Range(-4, 5, 1)
See Also
========
Naturals0 : non-negative integers
Integers : positive and negative integers and zero
"""
is_iterable = True
def _intersection(self, other):
from ..functions import ceiling, floor
if other is Interval(-oo, oo, True, True) or other is S.Reals:
return self
elif other.is_Interval:
s = Range(ceiling(other.left), floor(other.right) + 1)
return s.intersection(other) # take out endpoints if open interval
def _contains(self, other):
if not isinstance(other, Expr):
return false
elif other.is_integer:
return true
elif other.is_integer is False:
return false
def __iter__(self):
yield Integer(0)
i = Integer(1)
while True:
yield i
yield -i
i = i + 1
@property
def inf(self):
return -oo
@property
def sup(self):
return oo
@property
def boundary(self):
return self
def _eval_imageset(self, f):
from ..core import Wild
expr = f.expr
if len(f.variables) > 1:
return
n = f.variables[0]
a = Wild('a')
b = Wild('b')
match = expr.match(a*n + b)
if match[a].is_negative:
expr = -expr
match = expr.match(a*n + b)
if match[a] == 1 and match[b].is_integer:
expr = expr - match[b]
return ImageSet(Lambda(n, expr), S.Integers)
class Rationals(Set, metaclass=Singleton):
"""The set of all rationals."""
def _contains(self, other):
if other.is_rational:
return true
elif other.is_rational is False:
return false
@property
def inf(self):
return -oo
@property
def sup(self):
return oo
@property
def boundary(self):
return self
def __iter__(self):
seen = []
for n, d in cantor_product(S.Integers, S.Naturals): # pragma: no branch
r = Rational(n, d)
if r not in seen:
seen.append(r)
yield r
class Reals(Interval, metaclass=Singleton):
"""The set of all reals."""
def __new__(cls, start=-oo, end=oo, left_open=False, right_open=False):
return super().__new__(cls, left_open=True, right_open=True)
def __eq__(self, other):
return other == Interval(-oo, oo, True, True)
def __hash__(self):
return hash(Interval(-oo, oo, True, True))
class ExtendedReals(Interval, metaclass=Singleton):
"""The set of all extended reals."""
def __new__(cls, start=-oo, end=oo, left_open=False, right_open=False):
return super().__new__(cls)
def __eq__(self, other):
return other == Interval(-oo, oo)
def __hash__(self):
return hash(Interval(-oo, oo))
class ImageSet(Set):
"""Image of a set under a mathematical function.
Examples
========
>>> squares = ImageSet(Lambda(x, x**2), S.Naturals)
>>> 4 in squares
True
>>> 5 in squares
False
>>> FiniteSet(0, 1, 2, 3, 4, 5, 6, 7, 9, 10).intersection(squares)
{1, 4, 9}
>>> square_iterable = iter(squares)
>>> for i in range(4):
... next(square_iterable)
1
4
9
16
If you want to get value for `x` = 2, 1/2 etc. (Please check whether the
`x` value is in `base_set` or not before passing it as args)
>>> squares.lamda(2)
4
>>> squares.lamda(Rational(1, 2))
1/4
"""
def __new__(cls, lamda, base_set):
return Basic.__new__(cls, lamda, base_set)
lamda = property(lambda self: self.args[0])
base_set = property(lambda self: self.args[1])
def __iter__(self):
already_seen = set()
for i in self.base_set:
val = self.lamda(i)
if val in already_seen:
continue
already_seen.add(val)
yield val
def _contains(self, other):
from ..solvers import solve
L = self.lamda
if len(self.lamda.variables) > 1:
return # pragma: no cover
solns = solve(L.expr - other, L.variables[0])
for soln in solns:
if soln[L.variables[0]] in self.base_set:
return true
return false
@property
def is_iterable(self):
return self.base_set.is_iterable
def _intersection(self, other):
from ..core import Dummy, expand_complex
from ..solvers.diophantine import diophantine
from .sets import imageset
if self.base_set is S.Integers:
if isinstance(other, ImageSet) and other.base_set is S.Integers:
f, g = self.lamda.expr, other.lamda.expr
n, m = self.lamda.variables[0], other.lamda.variables[0]
# Diophantine sorts the solutions according to the alphabetic
# order of the variable names, since the result should not depend
# on the variable name, they are replaced by the dummy variables
# below
a, b = Dummy('a'), Dummy('b')
f, g = f.subs({n: a}), g.subs({m: b})
solns_set = diophantine(f - g)
if solns_set == set():
return EmptySet()
solns = list(diophantine(f - g))
if len(solns) == 1:
t = list(solns[0][0].free_symbols)[0]
else:
return # pragma: no cover
# since 'a' < 'b'
return imageset(Lambda(t, f.subs({a: solns[0][0]})), S.Integers)
if other == S.Reals:
if len(self.lamda.variables) > 1 or self.base_set is not S.Integers:
return # pragma: no cover
f = self.lamda.expr
n = self.lamda.variables[0]
n_ = Dummy(n.name, integer=True)
f_ = f.subs({n: n_})
re, im = map(expand_complex, f_.as_real_imag())
sols = list(diophantine(im, n_))
if all(s[0].has(n_) is False for s in sols):
s = FiniteSet(*[s[0] for s in sols])
elif len(sols) == 1 and sols[0][0].has(n_):
s = imageset(Lambda(n_, sols[0][0]), S.Integers)
else:
return # pragma: no cover
return imageset(Lambda(n_, re), self.base_set.intersection(s))
class Range(Set):
"""Represents a range of integers.
Examples
========
>>> list(Range(5))
[0, 1, 2, 3, 4]
>>> list(Range(10, 15))
[10, 11, 12, 13, 14]
>>> list(Range(10, 20, 2))
[10, 12, 14, 16, 18]
>>> list(Range(20, 10, -2))
[12, 14, 16, 18, 20]
"""
is_iterable = True
def __new__(cls, *args):
from ..functions import ceiling
if len(args) == 1 and isinstance(args[0], range):
args = args[0].start, args[0].stop, args[0].step
# expand range
slc = slice(*args)
start, stop, step = slc.start or 0, slc.stop, slc.step or 1
try:
start, stop, step = (w if w in [-oo, oo] else Integer(as_int(w))
for w in (start, stop, step))
except ValueError as exc:
raise ValueError('Inputs to Range must be Integer Valued\n' +
'Use ImageSets of Ranges for other cases') from exc
if not step.is_finite:
raise ValueError('Infinite step is not allowed')
if start == stop:
return S.EmptySet
n = ceiling((stop - start)/step)
if n <= 0:
return S.EmptySet
# normalize args: regardless of how they are entered they will show
# canonically as Range(inf, sup, step) with step > 0
if n.is_finite:
start, stop = sorted((start, start + (n - 1)*step))
else:
start, stop = sorted((start, stop - step))
step = abs(step)
return Basic.__new__(cls, start, stop + step, step)
start = property(lambda self: self.args[0])
stop = property(lambda self: self.args[1])
step = property(lambda self: self.args[2])
def _intersection(self, other):
from ..functions import Max, Min, ceiling, floor
if other.is_Interval:
osup = other.sup
oinf = other.inf
# if other is [0, 10) we can only go up to 9
if osup.is_integer and other.right_open:
osup -= 1
if oinf.is_integer and other.left_open:
oinf += 1
# Take the most restrictive of the bounds set by the two sets
# round inwards
inf = ceiling(Max(self.inf, oinf))
sup = floor(Min(self.sup, osup))
# if we are off the sequence, get back on
if inf.is_finite and self.inf.is_finite:
off = (inf - self.inf) % self.step
else:
off = Integer(0)
if off:
inf += self.step - off
return Range(inf, sup + 1, self.step)
if other == S.Naturals:
return self._intersection(Interval(1, oo, False, True))
if other == S.Integers:
return self
def _contains(self, other):
if (((self.start - other)/self.step).is_integer or
((self.stop - other)/self.step).is_integer):
return sympify(self.inf <= other <= self.sup, strict=True)
else:
return false
def __iter__(self):
if self.start == -oo:
i = self.stop - self.step
step = -self.step
else:
i = self.start
step = self.step
while self.start <= i < self.stop:
yield i
i += step
def __len__(self):
return int((self.stop - self.start)//self.step)
def __bool__(self):
return True
def _ith_element(self, i):
return self.start + i*self.step
@property
def _last_element(self):
if self.stop is oo:
return oo
elif self.start == -oo:
return self.stop - self.step
else:
return self._ith_element(len(self) - 1)
@property
def inf(self):
return self.start
@property
def sup(self):
return self.stop - self.step
@property
def boundary(self):
return self
converter[range] = Range
| bsd-3-clause | 485d96d86896421b1545e57121ae1cdf | 25.527163 | 81 | 0.539669 | 3.803808 | false | false | false | false |
diofant/diofant | diofant/functions/elementary/integers.py | 1 | 6922 | from mpmath.libmp.libmpf import prec_to_dps
from ...core import (Add, Function, Ge, Gt, I, Integer, Le, Lt,
PrecisionExhausted)
from ...logic import false, true
###############################################################################
# ####################### FLOOR and CEILING FUNCTIONS ####################### #
###############################################################################
class RoundFunction(Function):
"""The base class for rounding functions."""
@classmethod
def eval(cls, arg):
from .complexes import im
if arg.is_integer:
return arg
if isinstance(arg, cls):
return arg
if arg.is_imaginary or (I*arg).is_extended_real:
i = im(arg)
if not i.has(I):
return cls(i)*I
return cls(arg, evaluate=False)
v = cls._eval_number(arg)
if v is not None:
return v
# Integral, numerical, symbolic part
ipart = npart = spart = Integer(0)
# Extract integral (or complex integral) terms
terms = Add.make_args(arg)
for t in terms:
if t.is_integer or (t.is_imaginary and im(t).is_integer):
ipart += t
elif t.free_symbols:
spart += t
else:
npart += t
if not (npart or spart):
return ipart
# Evaluate npart numerically if independent of spart
if npart and (not spart or npart.is_extended_real and
(spart.is_imaginary or (I*spart).is_extended_real) or
npart.is_imaginary and spart.is_extended_real):
npart_int = None
try:
from ...core.evalf import DEFAULT_MAXPREC as TARGET
prec = 10
r, i = Integer(0), Integer(0)
npart_re, npart_im = npart.as_real_imag()
while prec < TARGET:
dps = prec_to_dps(prec)
r, i = npart_re.evalf(dps), npart_im.evalf(dps)
if ((not r or int(2**prec*abs(r)) > 2**prec*abs(int(r))) and
(not i or int(2**prec*abs(i)) > 2**prec*abs(int(i)))):
npart_int = cls(r) + cls(i)*I
break
prec += 10
else:
raise PrecisionExhausted
except PrecisionExhausted:
npart_int = cls(r) + cls(i)*I
if not npart.equals(npart_int):
npart_int = None
if npart_int is not None:
ipart += npart_int
npart = Integer(0)
spart += npart
if not spart:
return ipart
elif spart.is_imaginary or (I*spart).is_extended_real:
return ipart + cls(im(spart), evaluate=False)*I
else:
return ipart + cls(spart, evaluate=False)
def _eval_is_finite(self):
return self.args[0].is_finite
def _eval_is_extended_real(self):
if self.args[0].is_extended_real:
return True
def _eval_is_integer(self):
if self.args[0].is_real:
return True
class floor(RoundFunction):
"""
Floor is a univariate function which returns the largest integer
value not greater than its argument. However this implementation
generalizes floor to complex numbers.
Examples
========
>>> floor(17)
17
>>> floor(Rational(23, 10))
2
>>> floor(2*E)
5
>>> floor(-Float(0.567))
-1
>>> floor(-I/2)
-I
See Also
========
diofant.functions.elementary.integers.ceiling
References
==========
* "Concrete mathematics" by Graham, pp. 87
* https://mathworld.wolfram.com/FloorFunction.html
"""
_dir = -1
@classmethod
def _eval_number(cls, arg):
if arg.is_Number:
if arg.is_Rational:
return Integer(arg.numerator // arg.denominator)
elif arg.is_Float:
return Integer(int(arg.floor()))
else:
return arg
elif isinstance(arg, (floor, ceiling)):
return arg
if arg.is_NumberSymbol:
return arg.approximation_interval(Integer)[0]
def _eval_nseries(self, x, n, logx):
r = self.subs({x: 0})
args = self.args[0]
args0 = args.subs({x: 0})
if args0 == r:
direction = (args - args0).as_leading_term(x).as_coeff_exponent(x)[0]
if direction.is_positive:
return r
else:
return r - 1
else:
return r
def __le__(self, other):
if self.args[0] == other and other.is_extended_real:
return true
return Le(self, other, evaluate=False)
def __gt__(self, other):
if self.args[0] == other and other.is_extended_real:
return false
return Gt(self, other, evaluate=False)
def _eval_as_leading_term(self, x):
return self
class ceiling(RoundFunction):
"""
Ceiling is a univariate function which returns the smallest integer
value not less than its argument. Ceiling function is generalized
in this implementation to complex numbers.
Examples
========
>>> ceiling(17)
17
>>> ceiling(Rational(23, 10))
3
>>> ceiling(2*E)
6
>>> ceiling(-Float(0.567))
0
>>> ceiling(I/2)
I
See Also
========
diofant.functions.elementary.integers.floor
References
==========
* "Concrete mathematics" by Graham, pp. 87
* https://mathworld.wolfram.com/CeilingFunction.html
"""
_dir = 1
@classmethod
def _eval_number(cls, arg):
if arg.is_Number:
if arg.is_Rational:
return -Integer(-arg.numerator // arg.denominator)
elif arg.is_Float:
return Integer(int(arg.ceiling()))
else:
return arg
elif isinstance(arg, (ceiling, floor)):
return arg
if arg.is_NumberSymbol:
return arg.approximation_interval(Integer)[1]
def _eval_nseries(self, x, n, logx):
r = self.subs({x: 0})
args = self.args[0]
args0 = args.subs({x: 0})
if args0 == r:
direction = (args - args0).as_leading_term(x).as_coeff_exponent(x)[0]
if direction.is_positive:
return r + 1
else:
return r
else:
return r
def __lt__(self, other):
if self.args[0] == other and other.is_extended_real:
return false
return Lt(self, other, evaluate=False)
def __ge__(self, other):
if self.args[0] == other and other.is_extended_real:
return true
return Ge(self, other, evaluate=False)
| bsd-3-clause | 7c685fb121816e326c3dcd7a96109b3e | 27.253061 | 82 | 0.505779 | 3.95317 | false | false | false | false |
diofant/diofant | diofant/tests/polys/test_modulargcd.py | 1 | 2048 | """Tests for modular GCD algorithms."""
from diofant import QQ, ZZ, ring, sqrt
from diofant.polys.modulargcd import (_chinese_remainder_reconstruction,
_func_field_modgcd_m, _to_ANP_poly,
_to_ZZ_poly)
__all__ = ()
def test_chinese_remainder():
R, x, y = ring('x y', ZZ)
p, q = 3, 5
hp = x**3*y - x**2 - 1
hq = -x**3*y - 2*x*y**2 + 2
hpq = _chinese_remainder_reconstruction(hp, hq, p, q)
assert hpq.trunc_ground(p) == hp
assert hpq.trunc_ground(q) == hq
_, z = ring('z', R)
p, q = 3, 7
hp = (x*y + 1)*z**2 + x
hq = (x**2 - 3*y)*z + 2
hpq = _chinese_remainder_reconstruction(hp, hq, p, q)
assert hpq.trunc_ground(p) == hp
assert hpq.trunc_ground(q) == hq
def test_to_ZZ_ANP_poly():
A = QQ.algebraic_field(sqrt(2))
R, x = ring('x', A)
f = x*(sqrt(2) + 1)
T, x_, z_ = ring('x_ z_', ZZ)
f_ = x_*z_ + x_
assert _to_ZZ_poly(f, T) == f_
assert _to_ANP_poly(f_, R) == f
R, x, t, s = ring('x t s', A)
f = x*t**2 + x*s + sqrt(2)
D, t_, s_ = ring('t_ s_', ZZ)
T, x_, z_ = ring('x_ z_', D)
f_ = (t_**2 + s_)*x_ + z_
assert _to_ZZ_poly(f, T) == f_
assert _to_ANP_poly(f_, R) == f
def test_modgcd_func_field():
D, t = ring('t', ZZ)
_, x, z = ring('x z', D)
minpoly = (z**2*t**2 + z**2*t - 1).drop(0)
f, g = x + 1, x - 1
assert _func_field_modgcd_m(f, g, minpoly) == 1
# First example from Monagan2004algebraic.
m = z**2 - t
f = 3*t*x**2 - (2*t**2 - 3*t)*x*z + 15*x + 15*z - 2*t**3
g = 3*t*x**2*z + 15*x*z + (-2*t**3 + 3*t)*x - 2*t**2*z + 15
assert _func_field_modgcd_m(f, g, m.drop(0)) == 3*t*x - 2*t**2*z + 15
g = 3*t*x - 2*t**2*z + 15
a = x + z
b = x*z + 1
assert _func_field_modgcd_m(a*g, b*g, m.drop(0)) == g % m
assert _func_field_modgcd_m(a*g**2, b*g**2, m.drop(0)) == g**2 % m
# issue diofant/diofant#850
assert _func_field_modgcd_m(a*g**3, b*g**3, m.drop(0)) == g**3 % m
| bsd-3-clause | 24ec899adcd7d6ba664e789078e53238 | 23.97561 | 73 | 0.47168 | 2.283166 | false | false | false | false |
diofant/diofant | diofant/vector/scalar.py | 2 | 1659 | from ..core import Expr, Integer, Symbol, sympify
from ..printing.pretty.stringpict import prettyForm
class BaseScalar(Expr):
"""
A coordinate symbol/base scalar.
Ideally, users should not instantiate this class.
"""
is_commutative = True
def __new__(cls, name, index, system, pretty_str, latex_str):
from .coordsysrect import CoordSysCartesian
index = sympify(index, strict=True)
system = sympify(system, strict=True)
obj = super().__new__(cls, Symbol(str(name)), index, system,
Symbol(str(pretty_str)), Symbol(str(latex_str)))
if not isinstance(system, CoordSysCartesian):
raise TypeError('system should be a CoordSysCartesian')
if index not in range(3):
raise ValueError('Invalid index specified.')
# The _id is used for equating purposes, and for hashing
obj._id = (index, system)
obj.name = obj._name = str(name)
obj._pretty_form = str(pretty_str)
obj._latex_form = str(latex_str)
obj._system = system
return obj
_diff_wrt = True
def _eval_derivative(self, s):
assert self != s # == case handled in Symbol._eval_derivative
return Integer(0)
def _latex(self, printer=None):
return self._latex_form
def _pretty(self, printer=None):
return prettyForm(self._pretty_form)
@property
def system(self):
return self._system
def __str__(self, printer=None):
return self._name
@property
def free_symbols(self):
return {self}
__repr__ = __str__
_diofantstr = __str__
| bsd-3-clause | 4d9815941d2cd5dd8681b3b4b2713f29 | 27.118644 | 78 | 0.602773 | 3.978417 | false | false | false | false |
kjung/scikit-learn | examples/feature_selection/plot_select_from_model_boston.py | 142 | 1527 | """
===================================================
Feature selection using SelectFromModel and LassoCV
===================================================
Use SelectFromModel meta-transformer along with Lasso to select the best
couple of features from the Boston dataset.
"""
# Author: Manoj Kumar <mks542@nyu.edu>
# License: BSD 3 clause
print(__doc__)
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_boston
from sklearn.feature_selection import SelectFromModel
from sklearn.linear_model import LassoCV
# Load the boston dataset.
boston = load_boston()
X, y = boston['data'], boston['target']
# We use the base estimator LassoCV since the L1 norm promotes sparsity of features.
clf = LassoCV()
# Set a minimum threshold of 0.25
sfm = SelectFromModel(clf, threshold=0.25)
sfm.fit(X, y)
n_features = sfm.transform(X).shape[1]
# Reset the threshold till the number of features equals two.
# Note that the attribute can be set directly instead of repeatedly
# fitting the metatransformer.
while n_features > 2:
sfm.threshold += 0.1
X_transform = sfm.transform(X)
n_features = X_transform.shape[1]
# Plot the selected two features from X.
plt.title(
"Features selected from Boston using SelectFromModel with "
"threshold %0.3f." % sfm.threshold)
feature1 = X_transform[:, 0]
feature2 = X_transform[:, 1]
plt.plot(feature1, feature2, 'r.')
plt.xlabel("Feature number 1")
plt.ylabel("Feature number 2")
plt.ylim([np.min(feature2), np.max(feature2)])
plt.show()
| bsd-3-clause | 052d7530d893e75dda8da3ea3e8762af | 28.941176 | 84 | 0.691552 | 3.542923 | false | false | false | false |
kjung/scikit-learn | examples/svm/plot_rbf_parameters.py | 43 | 8096 | '''
==================
RBF SVM parameters
==================
This example illustrates the effect of the parameters ``gamma`` and ``C`` of
the Radial Basis Function (RBF) kernel SVM.
Intuitively, the ``gamma`` parameter defines how far the influence of a single
training example reaches, with low values meaning 'far' and high values meaning
'close'. The ``gamma`` parameters can be seen as the inverse of the radius of
influence of samples selected by the model as support vectors.
The ``C`` parameter trades off misclassification of training examples against
simplicity of the decision surface. A low ``C`` makes the decision surface
smooth, while a high ``C`` aims at classifying all training examples correctly
by giving the model freedom to select more samples as support vectors.
The first plot is a visualization of the decision function for a variety of
parameter values on a simplified classification problem involving only 2 input
features and 2 possible target classes (binary classification). Note that this
kind of plot is not possible to do for problems with more features or target
classes.
The second plot is a heatmap of the classifier's cross-validation accuracy as a
function of ``C`` and ``gamma``. For this example we explore a relatively large
grid for illustration purposes. In practice, a logarithmic grid from
:math:`10^{-3}` to :math:`10^3` is usually sufficient. If the best parameters
lie on the boundaries of the grid, it can be extended in that direction in a
subsequent search.
Note that the heat map plot has a special colorbar with a midpoint value close
to the score values of the best performing models so as to make it easy to tell
them appart in the blink of an eye.
The behavior of the model is very sensitive to the ``gamma`` parameter. If
``gamma`` is too large, the radius of the area of influence of the support
vectors only includes the support vector itself and no amount of
regularization with ``C`` will be able to prevent overfitting.
When ``gamma`` is very small, the model is too constrained and cannot capture
the complexity or "shape" of the data. The region of influence of any selected
support vector would include the whole training set. The resulting model will
behave similarly to a linear model with a set of hyperplanes that separate the
centers of high density of any pair of two classes.
For intermediate values, we can see on the second plot that good models can
be found on a diagonal of ``C`` and ``gamma``. Smooth models (lower ``gamma``
values) can be made more complex by selecting a larger number of support
vectors (larger ``C`` values) hence the diagonal of good performing models.
Finally one can also observe that for some intermediate values of ``gamma`` we
get equally performing models when ``C`` becomes very large: it is not
necessary to regularize by limiting the number of support vectors. The radius of
the RBF kernel alone acts as a good structural regularizer. In practice though
it might still be interesting to limit the number of support vectors with a
lower value of ``C`` so as to favor models that use less memory and that are
faster to predict.
We should also note that small differences in scores results from the random
splits of the cross-validation procedure. Those spurious variations can be
smoothed out by increasing the number of CV iterations ``n_iter`` at the
expense of compute time. Increasing the value number of ``C_range`` and
``gamma_range`` steps will increase the resolution of the hyper-parameter heat
map.
'''
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.model_selection import GridSearchCV
# Utility function to move the midpoint of a colormap to be around
# the values of interest.
class MidpointNormalize(Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
##############################################################################
# Load and prepare data set
#
# dataset for grid search
iris = load_iris()
X = iris.data
y = iris.target
# Dataset for decision function visualization: we only keep the first two
# features in X and sub-sample the dataset to keep only 2 classes and
# make it a binary classification problem.
X_2d = X[:, :2]
X_2d = X_2d[y > 0]
y_2d = y[y > 0]
y_2d -= 1
# It is usually a good idea to scale the data for SVM training.
# We are cheating a bit in this example in scaling all of the data,
# instead of fitting the transformation on the training set and
# just applying it on the test set.
scaler = StandardScaler()
X = scaler.fit_transform(X)
X_2d = scaler.fit_transform(X_2d)
##############################################################################
# Train classifiers
#
# For an initial search, a logarithmic grid with basis
# 10 is often helpful. Using a basis of 2, a finer
# tuning can be achieved but at a much higher cost.
C_range = np.logspace(-2, 10, 13)
gamma_range = np.logspace(-9, 3, 13)
param_grid = dict(gamma=gamma_range, C=C_range)
cv = StratifiedShuffleSplit(n_iter=5, test_size=0.2, random_state=42)
grid = GridSearchCV(SVC(), param_grid=param_grid, cv=cv)
grid.fit(X, y)
print("The best parameters are %s with a score of %0.2f"
% (grid.best_params_, grid.best_score_))
# Now we need to fit a classifier for all parameters in the 2d version
# (we use a smaller set of parameters here because it takes a while to train)
C_2d_range = [1e-2, 1, 1e2]
gamma_2d_range = [1e-1, 1, 1e1]
classifiers = []
for C in C_2d_range:
for gamma in gamma_2d_range:
clf = SVC(C=C, gamma=gamma)
clf.fit(X_2d, y_2d)
classifiers.append((C, gamma, clf))
##############################################################################
# visualization
#
# draw visualization of parameter effects
plt.figure(figsize=(8, 6))
xx, yy = np.meshgrid(np.linspace(-3, 3, 200), np.linspace(-3, 3, 200))
for (k, (C, gamma, clf)) in enumerate(classifiers):
# evaluate decision function in a grid
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# visualize decision function for these parameters
plt.subplot(len(C_2d_range), len(gamma_2d_range), k + 1)
plt.title("gamma=10^%d, C=10^%d" % (np.log10(gamma), np.log10(C)),
size='medium')
# visualize parameter's effect on decision function
plt.pcolormesh(xx, yy, -Z, cmap=plt.cm.RdBu)
plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y_2d, cmap=plt.cm.RdBu_r)
plt.xticks(())
plt.yticks(())
plt.axis('tight')
# plot the scores of the grid
# grid_scores_ contains parameter settings and scores
# We extract just the scores
scores = [x[1] for x in grid.grid_scores_]
scores = np.array(scores).reshape(len(C_range), len(gamma_range))
# Draw heatmap of the validation accuracy as a function of gamma and C
#
# The score are encoded as colors with the hot colormap which varies from dark
# red to bright yellow. As the most interesting scores are all located in the
# 0.92 to 0.97 range we use a custom normalizer to set the mid-point to 0.92 so
# as to make it easier to visualize the small variations of score values in the
# interesting range while not brutally collapsing all the low score values to
# the same color.
plt.figure(figsize=(8, 6))
plt.subplots_adjust(left=.2, right=0.95, bottom=0.15, top=0.95)
plt.imshow(scores, interpolation='nearest', cmap=plt.cm.hot,
norm=MidpointNormalize(vmin=0.2, midpoint=0.92))
plt.xlabel('gamma')
plt.ylabel('C')
plt.colorbar()
plt.xticks(np.arange(len(gamma_range)), gamma_range, rotation=45)
plt.yticks(np.arange(len(C_range)), C_range)
plt.title('Validation accuracy')
plt.show()
| bsd-3-clause | d2921613e107de6e55b6430b74aeb5b2 | 39.683417 | 80 | 0.712945 | 3.646847 | false | false | false | false |
kjung/scikit-learn | examples/cluster/plot_face_compress.py | 70 | 2479 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=========================================================
Vector Quantization Example
=========================================================
Face, a 1024 x 768 size image of a raccoon face,
is used here to illustrate how `k`-means is
used for vector quantization.
"""
print(__doc__)
# Code source: Gaël Varoquaux
# Modified for documentation by Jaques Grobler
# License: BSD 3 clause
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from sklearn import cluster
from sklearn.utils.testing import SkipTest
from sklearn.utils.fixes import sp_version
if sp_version < (0, 12):
raise SkipTest("Skipping because SciPy version earlier than 0.12.0 and "
"thus does not include the scipy.misc.face() image.")
try:
face = sp.face(gray=True)
except AttributeError:
# Newer versions of scipy have face in misc
from scipy import misc
face = misc.face(gray=True)
n_clusters = 5
np.random.seed(0)
X = face.reshape((-1, 1)) # We need an (n_sample, n_feature) array
k_means = cluster.KMeans(n_clusters=n_clusters, n_init=4)
k_means.fit(X)
values = k_means.cluster_centers_.squeeze()
labels = k_means.labels_
# create an array from labels and values
face_compressed = np.choose(labels, values)
face_compressed.shape = face.shape
vmin = face.min()
vmax = face.max()
# original face
plt.figure(1, figsize=(3, 2.2))
plt.imshow(face, cmap=plt.cm.gray, vmin=vmin, vmax=256)
# compressed face
plt.figure(2, figsize=(3, 2.2))
plt.imshow(face_compressed, cmap=plt.cm.gray, vmin=vmin, vmax=vmax)
# equal bins face
regular_values = np.linspace(0, 256, n_clusters + 1)
regular_labels = np.searchsorted(regular_values, face) - 1
regular_values = .5 * (regular_values[1:] + regular_values[:-1]) # mean
regular_face = np.choose(regular_labels.ravel(), regular_values, mode="clip")
regular_face.shape = face.shape
plt.figure(3, figsize=(3, 2.2))
plt.imshow(regular_face, cmap=plt.cm.gray, vmin=vmin, vmax=vmax)
# histogram
plt.figure(4, figsize=(3, 2.2))
plt.clf()
plt.axes([.01, .01, .98, .98])
plt.hist(X, bins=256, color='.5', edgecolor='.5')
plt.yticks(())
plt.xticks(regular_values)
values = np.sort(values)
for center_1, center_2 in zip(values[:-1], values[1:]):
plt.axvline(.5 * (center_1 + center_2), color='b')
for center_1, center_2 in zip(regular_values[:-1], regular_values[1:]):
plt.axvline(.5 * (center_1 + center_2), color='b', linestyle='--')
plt.show()
| bsd-3-clause | a33b222e8dd762cabed6c9ce7f654f1d | 27.482759 | 77 | 0.661017 | 3.063041 | false | false | false | false |
pallets/click | examples/termui/termui.py | 1 | 4150 | import math
import random
import time
import click
@click.group()
def cli():
"""This script showcases different terminal UI helpers in Click."""
pass
@cli.command()
def colordemo():
"""Demonstrates ANSI color support."""
for color in "red", "green", "blue":
click.echo(click.style(f"I am colored {color}", fg=color))
click.echo(click.style(f"I am background colored {color}", bg=color))
@cli.command()
def pager():
"""Demonstrates using the pager."""
lines = []
for x in range(200):
lines.append(f"{click.style(str(x), fg='green')}. Hello World!")
click.echo_via_pager("\n".join(lines))
@cli.command()
@click.option(
"--count",
default=8000,
type=click.IntRange(1, 100000),
help="The number of items to process.",
)
def progress(count):
"""Demonstrates the progress bar."""
items = range(count)
def process_slowly(item):
time.sleep(0.002 * random.random())
def filter(items):
for item in items:
if random.random() > 0.3:
yield item
with click.progressbar(
items, label="Processing accounts", fill_char=click.style("#", fg="green")
) as bar:
for item in bar:
process_slowly(item)
def show_item(item):
if item is not None:
return f"Item #{item}"
with click.progressbar(
filter(items),
label="Committing transaction",
fill_char=click.style("#", fg="yellow"),
item_show_func=show_item,
) as bar:
for item in bar:
process_slowly(item)
with click.progressbar(
length=count,
label="Counting",
bar_template="%(label)s %(bar)s | %(info)s",
fill_char=click.style("█", fg="cyan"),
empty_char=" ",
) as bar:
for item in bar:
process_slowly(item)
with click.progressbar(
length=count,
width=0,
show_percent=False,
show_eta=False,
fill_char=click.style("#", fg="magenta"),
) as bar:
for item in bar:
process_slowly(item)
# 'Non-linear progress bar'
steps = [math.exp(x * 1.0 / 20) - 1 for x in range(20)]
count = int(sum(steps))
with click.progressbar(
length=count,
show_percent=False,
label="Slowing progress bar",
fill_char=click.style("█", fg="green"),
) as bar:
for item in steps:
time.sleep(item)
bar.update(item)
@cli.command()
@click.argument("url")
def open(url):
"""Opens a file or URL In the default application."""
click.launch(url)
@cli.command()
@click.argument("url")
def locate(url):
"""Opens a file or URL In the default application."""
click.launch(url, locate=True)
@cli.command()
def edit():
"""Opens an editor with some text in it."""
MARKER = "# Everything below is ignored\n"
message = click.edit(f"\n\n{MARKER}")
if message is not None:
msg = message.split(MARKER, 1)[0].rstrip("\n")
if not msg:
click.echo("Empty message!")
else:
click.echo(f"Message:\n{msg}")
else:
click.echo("You did not enter anything!")
@cli.command()
def clear():
"""Clears the entire screen."""
click.clear()
@cli.command()
def pause():
"""Waits for the user to press a button."""
click.pause()
@cli.command()
def menu():
"""Shows a simple menu."""
menu = "main"
while True:
if menu == "main":
click.echo("Main menu:")
click.echo(" d: debug menu")
click.echo(" q: quit")
char = click.getchar()
if char == "d":
menu = "debug"
elif char == "q":
menu = "quit"
else:
click.echo("Invalid input")
elif menu == "debug":
click.echo("Debug menu")
click.echo(" b: back")
char = click.getchar()
if char == "b":
menu = "main"
else:
click.echo("Invalid input")
elif menu == "quit":
return
| bsd-3-clause | 9851c21c6c15151e92acdf9aa5e2853b | 23.532544 | 82 | 0.543415 | 3.698483 | false | false | false | false |
pallets/click | src/click/_compat.py | 1 | 18810 | import codecs
import io
import os
import re
import sys
import typing as t
from weakref import WeakKeyDictionary
CYGWIN = sys.platform.startswith("cygwin")
MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)
# Determine local App Engine environment, per Google's own suggestion
APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(
"SERVER_SOFTWARE", ""
)
WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS2
auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None
_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")
def get_filesystem_encoding() -> str:
return sys.getfilesystemencoding() or sys.getdefaultencoding()
def _make_text_stream(
stream: t.BinaryIO,
encoding: t.Optional[str],
errors: t.Optional[str],
force_readable: bool = False,
force_writable: bool = False,
) -> t.TextIO:
if encoding is None:
encoding = get_best_encoding(stream)
if errors is None:
errors = "replace"
return _NonClosingTextIOWrapper(
stream,
encoding,
errors,
line_buffering=True,
force_readable=force_readable,
force_writable=force_writable,
)
def is_ascii_encoding(encoding: str) -> bool:
"""Checks if a given encoding is ascii."""
try:
return codecs.lookup(encoding).name == "ascii"
except LookupError:
return False
def get_best_encoding(stream: t.IO) -> str:
"""Returns the default stream encoding if not found."""
rv = getattr(stream, "encoding", None) or sys.getdefaultencoding()
if is_ascii_encoding(rv):
return "utf-8"
return rv
class _NonClosingTextIOWrapper(io.TextIOWrapper):
def __init__(
self,
stream: t.BinaryIO,
encoding: t.Optional[str],
errors: t.Optional[str],
force_readable: bool = False,
force_writable: bool = False,
**extra: t.Any,
) -> None:
self._stream = stream = t.cast(
t.BinaryIO, _FixupStream(stream, force_readable, force_writable)
)
super().__init__(stream, encoding, errors, **extra)
def __del__(self) -> None:
try:
self.detach()
except Exception:
pass
def isatty(self) -> bool:
# https://bitbucket.org/pypy/pypy/issue/1803
return self._stream.isatty()
class _FixupStream:
"""The new io interface needs more from streams than streams
traditionally implement. As such, this fix-up code is necessary in
some circumstances.
The forcing of readable and writable flags are there because some tools
put badly patched objects on sys (one such offender are certain version
of jupyter notebook).
"""
def __init__(
self,
stream: t.BinaryIO,
force_readable: bool = False,
force_writable: bool = False,
):
self._stream = stream
self._force_readable = force_readable
self._force_writable = force_writable
def __getattr__(self, name: str) -> t.Any:
return getattr(self._stream, name)
def read1(self, size: int) -> bytes:
f = getattr(self._stream, "read1", None)
if f is not None:
return t.cast(bytes, f(size))
return self._stream.read(size)
def readable(self) -> bool:
if self._force_readable:
return True
x = getattr(self._stream, "readable", None)
if x is not None:
return t.cast(bool, x())
try:
self._stream.read(0)
except Exception:
return False
return True
def writable(self) -> bool:
if self._force_writable:
return True
x = getattr(self._stream, "writable", None)
if x is not None:
return t.cast(bool, x())
try:
self._stream.write("") # type: ignore
except Exception:
try:
self._stream.write(b"")
except Exception:
return False
return True
def seekable(self) -> bool:
x = getattr(self._stream, "seekable", None)
if x is not None:
return t.cast(bool, x())
try:
self._stream.seek(self._stream.tell())
except Exception:
return False
return True
def _is_binary_reader(stream: t.IO, default: bool = False) -> bool:
try:
return isinstance(stream.read(0), bytes)
except Exception:
return default
# This happens in some cases where the stream was already
# closed. In this case, we assume the default.
def _is_binary_writer(stream: t.IO, default: bool = False) -> bool:
try:
stream.write(b"")
except Exception:
try:
stream.write("")
return False
except Exception:
pass
return default
return True
def _find_binary_reader(stream: t.IO) -> t.Optional[t.BinaryIO]:
# We need to figure out if the given stream is already binary.
# This can happen because the official docs recommend detaching
# the streams to get binary streams. Some code might do this, so
# we need to deal with this case explicitly.
if _is_binary_reader(stream, False):
return t.cast(t.BinaryIO, stream)
buf = getattr(stream, "buffer", None)
# Same situation here; this time we assume that the buffer is
# actually binary in case it's closed.
if buf is not None and _is_binary_reader(buf, True):
return t.cast(t.BinaryIO, buf)
return None
def _find_binary_writer(stream: t.IO) -> t.Optional[t.BinaryIO]:
# We need to figure out if the given stream is already binary.
# This can happen because the official docs recommend detaching
# the streams to get binary streams. Some code might do this, so
# we need to deal with this case explicitly.
if _is_binary_writer(stream, False):
return t.cast(t.BinaryIO, stream)
buf = getattr(stream, "buffer", None)
# Same situation here; this time we assume that the buffer is
# actually binary in case it's closed.
if buf is not None and _is_binary_writer(buf, True):
return t.cast(t.BinaryIO, buf)
return None
def _stream_is_misconfigured(stream: t.TextIO) -> bool:
"""A stream is misconfigured if its encoding is ASCII."""
# If the stream does not have an encoding set, we assume it's set
# to ASCII. This appears to happen in certain unittest
# environments. It's not quite clear what the correct behavior is
# but this at least will force Click to recover somehow.
return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")
def _is_compat_stream_attr(stream: t.TextIO, attr: str, value: t.Optional[str]) -> bool:
"""A stream attribute is compatible if it is equal to the
desired value or the desired value is unset and the attribute
has a value.
"""
stream_value = getattr(stream, attr, None)
return stream_value == value or (value is None and stream_value is not None)
def _is_compatible_text_stream(
stream: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]
) -> bool:
"""Check if a stream's encoding and errors attributes are
compatible with the desired values.
"""
return _is_compat_stream_attr(
stream, "encoding", encoding
) and _is_compat_stream_attr(stream, "errors", errors)
def _force_correct_text_stream(
text_stream: t.IO,
encoding: t.Optional[str],
errors: t.Optional[str],
is_binary: t.Callable[[t.IO, bool], bool],
find_binary: t.Callable[[t.IO], t.Optional[t.BinaryIO]],
force_readable: bool = False,
force_writable: bool = False,
) -> t.TextIO:
if is_binary(text_stream, False):
binary_reader = t.cast(t.BinaryIO, text_stream)
else:
text_stream = t.cast(t.TextIO, text_stream)
# If the stream looks compatible, and won't default to a
# misconfigured ascii encoding, return it as-is.
if _is_compatible_text_stream(text_stream, encoding, errors) and not (
encoding is None and _stream_is_misconfigured(text_stream)
):
return text_stream
# Otherwise, get the underlying binary reader.
possible_binary_reader = find_binary(text_stream)
# If that's not possible, silently use the original reader
# and get mojibake instead of exceptions.
if possible_binary_reader is None:
return text_stream
binary_reader = possible_binary_reader
# Default errors to replace instead of strict in order to get
# something that works.
if errors is None:
errors = "replace"
# Wrap the binary stream in a text stream with the correct
# encoding parameters.
return _make_text_stream(
binary_reader,
encoding,
errors,
force_readable=force_readable,
force_writable=force_writable,
)
def _force_correct_text_reader(
text_reader: t.IO,
encoding: t.Optional[str],
errors: t.Optional[str],
force_readable: bool = False,
) -> t.TextIO:
return _force_correct_text_stream(
text_reader,
encoding,
errors,
_is_binary_reader,
_find_binary_reader,
force_readable=force_readable,
)
def _force_correct_text_writer(
text_writer: t.IO,
encoding: t.Optional[str],
errors: t.Optional[str],
force_writable: bool = False,
) -> t.TextIO:
return _force_correct_text_stream(
text_writer,
encoding,
errors,
_is_binary_writer,
_find_binary_writer,
force_writable=force_writable,
)
def get_binary_stdin() -> t.BinaryIO:
reader = _find_binary_reader(sys.stdin)
if reader is None:
raise RuntimeError("Was not able to determine binary stream for sys.stdin.")
return reader
def get_binary_stdout() -> t.BinaryIO:
writer = _find_binary_writer(sys.stdout)
if writer is None:
raise RuntimeError("Was not able to determine binary stream for sys.stdout.")
return writer
def get_binary_stderr() -> t.BinaryIO:
writer = _find_binary_writer(sys.stderr)
if writer is None:
raise RuntimeError("Was not able to determine binary stream for sys.stderr.")
return writer
def get_text_stdin(
encoding: t.Optional[str] = None, errors: t.Optional[str] = None
) -> t.TextIO:
rv = _get_windows_console_stream(sys.stdin, encoding, errors)
if rv is not None:
return rv
return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True)
def get_text_stdout(
encoding: t.Optional[str] = None, errors: t.Optional[str] = None
) -> t.TextIO:
rv = _get_windows_console_stream(sys.stdout, encoding, errors)
if rv is not None:
return rv
return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True)
def get_text_stderr(
encoding: t.Optional[str] = None, errors: t.Optional[str] = None
) -> t.TextIO:
rv = _get_windows_console_stream(sys.stderr, encoding, errors)
if rv is not None:
return rv
return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)
def _wrap_io_open(
file: t.Union[str, os.PathLike, int],
mode: str,
encoding: t.Optional[str],
errors: t.Optional[str],
) -> t.IO:
"""Handles not passing ``encoding`` and ``errors`` in binary mode."""
if "b" in mode:
return open(file, mode)
return open(file, mode, encoding=encoding, errors=errors)
def open_stream(
filename: str,
mode: str = "r",
encoding: t.Optional[str] = None,
errors: t.Optional[str] = "strict",
atomic: bool = False,
) -> t.Tuple[t.IO, bool]:
binary = "b" in mode
# Standard streams first. These are simple because they ignore the
# atomic flag. Use fsdecode to handle Path("-").
if os.fsdecode(filename) == "-":
if any(m in mode for m in ["w", "a", "x"]):
if binary:
return get_binary_stdout(), False
return get_text_stdout(encoding=encoding, errors=errors), False
if binary:
return get_binary_stdin(), False
return get_text_stdin(encoding=encoding, errors=errors), False
# Non-atomic writes directly go out through the regular open functions.
if not atomic:
return _wrap_io_open(filename, mode, encoding, errors), True
# Some usability stuff for atomic writes
if "a" in mode:
raise ValueError(
"Appending to an existing file is not supported, because that"
" would involve an expensive `copy`-operation to a temporary"
" file. Open the file in normal `w`-mode and copy explicitly"
" if that's what you're after."
)
if "x" in mode:
raise ValueError("Use the `overwrite`-parameter instead.")
if "w" not in mode:
raise ValueError("Atomic writes only make sense with `w`-mode.")
# Atomic writes are more complicated. They work by opening a file
# as a proxy in the same folder and then using the fdopen
# functionality to wrap it in a Python file. Then we wrap it in an
# atomic file that moves the file over on close.
import errno
import random
try:
perm: t.Optional[int] = os.stat(filename).st_mode
except OSError:
perm = None
flags = os.O_RDWR | os.O_CREAT | os.O_EXCL
if binary:
flags |= getattr(os, "O_BINARY", 0)
while True:
tmp_filename = os.path.join(
os.path.dirname(filename),
f".__atomic-write{random.randrange(1 << 32):08x}",
)
try:
fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)
break
except OSError as e:
if e.errno == errno.EEXIST or (
os.name == "nt"
and e.errno == errno.EACCES
and os.path.isdir(e.filename)
and os.access(e.filename, os.W_OK)
):
continue
raise
if perm is not None:
os.chmod(tmp_filename, perm) # in case perm includes bits in umask
f = _wrap_io_open(fd, mode, encoding, errors)
af = _AtomicFile(f, tmp_filename, os.path.realpath(filename))
return t.cast(t.IO, af), True
class _AtomicFile:
def __init__(self, f: t.IO, tmp_filename: str, real_filename: str) -> None:
self._f = f
self._tmp_filename = tmp_filename
self._real_filename = real_filename
self.closed = False
@property
def name(self) -> str:
return self._real_filename
def close(self, delete: bool = False) -> None:
if self.closed:
return
self._f.close()
os.replace(self._tmp_filename, self._real_filename)
self.closed = True
def __getattr__(self, name: str) -> t.Any:
return getattr(self._f, name)
def __enter__(self) -> "_AtomicFile":
return self
def __exit__(self, exc_type, exc_value, tb): # type: ignore
self.close(delete=exc_type is not None)
def __repr__(self) -> str:
return repr(self._f)
def strip_ansi(value: str) -> str:
return _ansi_re.sub("", value)
def _is_jupyter_kernel_output(stream: t.IO) -> bool:
while isinstance(stream, (_FixupStream, _NonClosingTextIOWrapper)):
stream = stream._stream
return stream.__class__.__module__.startswith("ipykernel.")
def should_strip_ansi(
stream: t.Optional[t.IO] = None, color: t.Optional[bool] = None
) -> bool:
if color is None:
if stream is None:
stream = sys.stdin
return not isatty(stream) and not _is_jupyter_kernel_output(stream)
return not color
# On Windows, wrap the output streams with colorama to support ANSI
# color codes.
# NOTE: double check is needed so mypy does not analyze this on Linux
if sys.platform.startswith("win") and WIN:
from ._winconsole import _get_windows_console_stream
def _get_argv_encoding() -> str:
import locale
return locale.getpreferredencoding()
_ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
def auto_wrap_for_ansi(
stream: t.TextIO, color: t.Optional[bool] = None
) -> t.TextIO:
"""Support ANSI color and style codes on Windows by wrapping a
stream with colorama.
"""
try:
cached = _ansi_stream_wrappers.get(stream)
except Exception:
cached = None
if cached is not None:
return cached
import colorama
strip = should_strip_ansi(stream, color)
ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)
rv = t.cast(t.TextIO, ansi_wrapper.stream)
_write = rv.write
def _safe_write(s):
try:
return _write(s)
except BaseException:
ansi_wrapper.reset_all()
raise
rv.write = _safe_write
try:
_ansi_stream_wrappers[stream] = rv
except Exception:
pass
return rv
else:
def _get_argv_encoding() -> str:
return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()
def _get_windows_console_stream(
f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]
) -> t.Optional[t.TextIO]:
return None
def term_len(x: str) -> int:
return len(strip_ansi(x))
def isatty(stream: t.IO) -> bool:
try:
return stream.isatty()
except Exception:
return False
def _make_cached_stream_func(
src_func: t.Callable[[], t.TextIO], wrapper_func: t.Callable[[], t.TextIO]
) -> t.Callable[[], t.TextIO]:
cache: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()
def func() -> t.TextIO:
stream = src_func()
try:
rv = cache.get(stream)
except Exception:
rv = None
if rv is not None:
return rv
rv = wrapper_func()
try:
cache[stream] = rv
except Exception:
pass
return rv
return func
_default_text_stdin = _make_cached_stream_func(lambda: sys.stdin, get_text_stdin)
_default_text_stdout = _make_cached_stream_func(lambda: sys.stdout, get_text_stdout)
_default_text_stderr = _make_cached_stream_func(lambda: sys.stderr, get_text_stderr)
binary_streams: t.Mapping[str, t.Callable[[], t.BinaryIO]] = {
"stdin": get_binary_stdin,
"stdout": get_binary_stdout,
"stderr": get_binary_stderr,
}
text_streams: t.Mapping[
str, t.Callable[[t.Optional[str], t.Optional[str]], t.TextIO]
] = {
"stdin": get_text_stdin,
"stdout": get_text_stdout,
"stderr": get_text_stderr,
}
| bsd-3-clause | c62064302a7a3f028dc93b6293083cc4 | 29.047923 | 88 | 0.616108 | 3.738076 | false | false | false | false |
pytorch/text | torchtext/models/roberta/bundler.py | 1 | 13133 | import logging
import re
from dataclasses import dataclass
from typing import Any, Callable, Dict, Optional, Union
from urllib.parse import urljoin
import torch
from torch.nn import Module
from torchtext._download_hooks import load_state_dict_from_url
logger = logging.getLogger(__name__)
import torchtext.transforms as T
from torchtext import _TEXT_BUCKET
from .model import RobertaEncoderConf, RobertaModel
def _is_head_available_in_checkpoint(checkpoint, head_state_dict):
# ensure all keys are present
return all(key in checkpoint.keys() for key in head_state_dict.keys())
@dataclass
class RobertaBundle:
"""RobertaBundle(_params: torchtext.models.RobertaEncoderParams, _path: Optional[str] = None, _head: Optional[torch.nn.Module] = None, transform: Optional[Callable] = None)
Example - Pretrained base xlmr encoder
>>> import torch, torchtext
>>> from torchtext.functional import to_tensor
>>> xlmr_base = torchtext.models.XLMR_BASE_ENCODER
>>> model = xlmr_base.get_model()
>>> transform = xlmr_base.transform()
>>> input_batch = ["Hello world", "How are you!"]
>>> model_input = to_tensor(transform(input_batch), padding_value=1)
>>> output = model(model_input)
>>> output.shape
torch.Size([2, 6, 768])
Example - Pretrained large xlmr encoder attached to un-initialized classification head
>>> import torch, torchtext
>>> from torchtext.models import RobertaClassificationHead
>>> from torchtext.functional import to_tensor
>>> xlmr_large = torchtext.models.XLMR_LARGE_ENCODER
>>> classifier_head = torchtext.models.RobertaClassificationHead(num_classes=2, input_dim = 1024)
>>> model = xlmr_large.get_model(head=classifier_head)
>>> transform = xlmr_large.transform()
>>> input_batch = ["Hello world", "How are you!"]
>>> model_input = to_tensor(transform(input_batch), padding_value=1)
>>> output = model(model_input)
>>> output.shape
torch.Size([1, 2])
Example - User-specified configuration and checkpoint
>>> from torchtext.models import RobertaEncoderConf, RobertaBundle, RobertaClassificationHead
>>> model_weights_path = "https://download.pytorch.org/models/text/xlmr.base.encoder.pt"
>>> encoder_conf = RobertaEncoderConf(vocab_size=250002)
>>> classifier_head = RobertaClassificationHead(num_classes=2, input_dim=768)
>>> model = RobertaBundle.build_model(encoder_conf=encoder_conf, head=classifier_head, checkpoint=model_weights_path)
"""
_encoder_conf: RobertaEncoderConf
_path: Optional[str] = None
_head: Optional[Module] = None
transform: Optional[Callable] = None
def get_model(
self,
*,
head: Optional[Module] = None,
load_weights: bool = True,
freeze_encoder: bool = False,
dl_kwargs: Dict[str, Any] = None,
) -> RobertaModel:
r"""get_model(head: Optional[torch.nn.Module] = None, load_weights: bool = True, freeze_encoder: bool = False, *, dl_kwargs=None) -> torctext.models.RobertaModel
Args:
head (nn.Module): A module to be attached to the encoder to perform specific task. If provided, it will replace the default member head (Default: ``None``)
load_weights (bool): Indicates whether or not to load weights if available. (Default: ``True``)
freeze_encoder (bool): Indicates whether or not to freeze the encoder weights. (Default: ``False``)
dl_kwargs (dictionary of keyword arguments): Passed to :func:`torch.hub.load_state_dict_from_url`. (Default: ``None``)
"""
if load_weights:
assert (
self._path is not None
), "load_weights cannot be True. The pre-trained model weights are not available for the current object"
if freeze_encoder:
if not load_weights or not self._path:
logger.warn(
"The encoder is not loaded with pre-trained weights. Setting freeze_encoder to True will hinder encoder from learning appropriate weights."
)
if head is not None:
input_head = head
if self._head is not None:
logger.log("A custom head module was provided, discarding the default head module.")
else:
input_head = self._head
return RobertaBundle.build_model(
encoder_conf=self._encoder_conf,
head=input_head,
freeze_encoder=freeze_encoder,
checkpoint=self._path if load_weights else None,
override_checkpoint_head=True,
strict=False,
dl_kwargs=dl_kwargs,
)
@classmethod
def build_model(
cls,
encoder_conf: RobertaEncoderConf,
*,
head: Optional[Module] = None,
freeze_encoder: bool = False,
checkpoint: Optional[Union[str, Dict[str, torch.Tensor]]] = None,
override_checkpoint_head: bool = False,
strict=False,
dl_kwargs: Dict[str, Any] = None,
) -> RobertaModel:
"""Class builder method
Args:
encoder_conf (RobertaEncoderConf): An instance of class RobertaEncoderConf that defined the encoder configuration
head (nn.Module): A module to be attached to the encoder to perform specific task. (Default: ``None``)
freeze_encoder (bool): Indicates whether to freeze the encoder weights. (Default: ``False``)
checkpoint (str or Dict[str, torch.Tensor]): Path to or actual model state_dict. state_dict can have partial weights i.e only for encoder. (Default: ``None``)
override_checkpoint_head (bool): Override the checkpoint's head state dict (if present) with provided head state dict. (Default: ``False``)
strict (bool): Passed to :func: `torch.nn.Module.load_state_dict` method. (Default: ``True``)
dl_kwargs (dictionary of keyword arguments): Passed to :func:`torch.hub.load_state_dict_from_url`. (Default: ``None``)
"""
model = RobertaModel(encoder_conf, head, freeze_encoder)
if checkpoint is not None:
if torch.jit.isinstance(checkpoint, Dict[str, torch.Tensor]):
state_dict = checkpoint
elif isinstance(checkpoint, str):
dl_kwargs = {} if dl_kwargs is None else dl_kwargs
state_dict = load_state_dict_from_url(checkpoint, **dl_kwargs)
else:
raise TypeError(
"checkpoint must be of type `str` or `Dict[str, torch.Tensor]` but got {}".format(type(checkpoint))
)
if head is not None:
regex = re.compile(r"^head\.")
head_state_dict = {k: v for k, v in model.state_dict().items() if regex.findall(k)}
# If checkpoint does not contains head_state_dict, then we augment the checkpoint with user-provided head state_dict
if not _is_head_available_in_checkpoint(state_dict, head_state_dict) or override_checkpoint_head:
state_dict.update(head_state_dict)
model.load_state_dict(state_dict, strict=strict)
return model
@property
def encoderConf(self) -> RobertaEncoderConf:
return self._encoder_conf
XLMR_BASE_ENCODER = RobertaBundle(
_path=urljoin(_TEXT_BUCKET, "xlmr.base.encoder.pt"),
_encoder_conf=RobertaEncoderConf(vocab_size=250002),
transform=lambda: T.Sequential(
T.SentencePieceTokenizer(urljoin(_TEXT_BUCKET, "xlmr.sentencepiece.bpe.model")),
T.VocabTransform(load_state_dict_from_url(urljoin(_TEXT_BUCKET, "xlmr.vocab.pt"))),
T.Truncate(254),
T.AddToken(token=0, begin=True),
T.AddToken(token=2, begin=False),
),
)
XLMR_BASE_ENCODER.__doc__ = """
XLM-R Encoder with Base configuration
The XLM-RoBERTa model was proposed in `Unsupervised Cross-lingual Representation Learning
at Scale <https://arxiv.org/abs/1911.02116>`. It is a large multi-lingual language model,
trained on 2.5TB of filtered CommonCrawl data and based on the RoBERTa model architecture.
Originally published by the authors of XLM-RoBERTa under MIT License
and redistributed with the same license.
[`License <https://github.com/pytorch/fairseq/blob/main/LICENSE>`__,
`Source <https://github.com/pytorch/fairseq/tree/main/examples/xlmr#pre-trained-models>`__]
Please refer to :func:`torchtext.models.RobertaBundle` for the usage.
"""
XLMR_LARGE_ENCODER = RobertaBundle(
_path=urljoin(_TEXT_BUCKET, "xlmr.large.encoder.pt"),
_encoder_conf=RobertaEncoderConf(
vocab_size=250002, embedding_dim=1024, ffn_dimension=4096, num_attention_heads=16, num_encoder_layers=24
),
transform=lambda: T.Sequential(
T.SentencePieceTokenizer(urljoin(_TEXT_BUCKET, "xlmr.sentencepiece.bpe.model")),
T.VocabTransform(load_state_dict_from_url(urljoin(_TEXT_BUCKET, "xlmr.vocab.pt"))),
T.Truncate(510),
T.AddToken(token=0, begin=True),
T.AddToken(token=2, begin=False),
),
)
XLMR_LARGE_ENCODER.__doc__ = """
XLM-R Encoder with Large configuration
The XLM-RoBERTa model was proposed in `Unsupervised Cross-lingual Representation Learning
at Scale <https://arxiv.org/abs/1911.02116>`. It is a large multi-lingual language model,
trained on 2.5TB of filtered CommonCrawl data and based on the RoBERTa model architecture.
Originally published by the authors of XLM-RoBERTa under MIT License
and redistributed with the same license.
[`License <https://github.com/pytorch/fairseq/blob/main/LICENSE>`__,
`Source <https://github.com/pytorch/fairseq/tree/main/examples/xlmr#pre-trained-models>`__]
Please refer to :func:`torchtext.models.RobertaBundle` for the usage.
"""
ROBERTA_BASE_ENCODER = RobertaBundle(
_path=urljoin(_TEXT_BUCKET, "roberta.base.encoder.pt"),
_encoder_conf=RobertaEncoderConf(vocab_size=50265),
transform=lambda: T.Sequential(
T.GPT2BPETokenizer(
encoder_json_path=urljoin(_TEXT_BUCKET, "gpt2_bpe_encoder.json"),
vocab_bpe_path=urljoin(_TEXT_BUCKET, "gpt2_bpe_vocab.bpe"),
),
T.VocabTransform(load_state_dict_from_url(urljoin(_TEXT_BUCKET, "roberta.vocab.pt"))),
T.Truncate(254),
T.AddToken(token=0, begin=True),
T.AddToken(token=2, begin=False),
),
)
ROBERTA_BASE_ENCODER.__doc__ = """
Roberta Encoder with Base configuration
RoBERTa iterates on BERT's pretraining procedure, including training the model longer,
with bigger batches over more data; removing the next sentence prediction objective;
training on longer sequences; and dynamically changing the masking pattern applied
to the training data.
The RoBERTa model was pretrained on the reunion of five datasets: BookCorpus,
English Wikipedia, CC-News, OpenWebText, and STORIES. Together theses datasets
contain over a 160GB of text.
Originally published by the authors of RoBERTa under MIT License
and redistributed with the same license.
[`License <https://github.com/pytorch/fairseq/blob/main/LICENSE>`__,
`Source <https://github.com/pytorch/fairseq/tree/main/examples/roberta#pre-trained-models>`__]
Please refer to :func:`torchtext.models.RobertaBundle` for the usage.
"""
ROBERTA_LARGE_ENCODER = RobertaBundle(
_path=urljoin(_TEXT_BUCKET, "roberta.large.encoder.pt"),
_encoder_conf=RobertaEncoderConf(
vocab_size=50265,
embedding_dim=1024,
ffn_dimension=4096,
num_attention_heads=16,
num_encoder_layers=24,
),
transform=lambda: T.Sequential(
T.GPT2BPETokenizer(
encoder_json_path=urljoin(_TEXT_BUCKET, "gpt2_bpe_encoder.json"),
vocab_bpe_path=urljoin(_TEXT_BUCKET, "gpt2_bpe_vocab.bpe"),
),
T.VocabTransform(load_state_dict_from_url(urljoin(_TEXT_BUCKET, "roberta.vocab.pt"))),
T.Truncate(510),
T.AddToken(token=0, begin=True),
T.AddToken(token=2, begin=False),
),
)
ROBERTA_LARGE_ENCODER.__doc__ = """
Roberta Encoder with Large configuration
RoBERTa iterates on BERT's pretraining procedure, including training the model longer,
with bigger batches over more data; removing the next sentence prediction objective;
training on longer sequences; and dynamically changing the masking pattern applied
to the training data.
The RoBERTa model was pretrained on the reunion of five datasets: BookCorpus,
English Wikipedia, CC-News, OpenWebText, and STORIES. Together theses datasets
contain over a 160GB of text.
Originally published by the authors of RoBERTa under MIT License
and redistributed with the same license.
[`License <https://github.com/pytorch/fairseq/blob/main/LICENSE>`__,
`Source <https://github.com/pytorch/fairseq/tree/main/examples/roberta#pre-trained-models>`__]
Please refer to :func:`torchtext.models.RobertaBundle` for the usage.
"""
| bsd-3-clause | 6723765062893c09c9e48b2e72dea9dd | 43.368243 | 176 | 0.665575 | 3.737336 | false | false | false | false |
scipy/scipy | benchmarks/benchmarks/cython_special.py | 18 | 1956 | import re
import numpy as np
from scipy import special
from .common import with_attributes, safe_import
with safe_import():
from scipy.special import cython_special
FUNC_ARGS = {
'airy_d': (1,),
'airy_D': (1,),
'beta_dd': (0.25, 0.75),
'erf_d': (1,),
'erf_D': (1+1j,),
'exprel_d': (1e-6,),
'gamma_d': (100,),
'gamma_D': (100+100j,),
'jv_dd': (1, 1),
'jv_dD': (1, (1+1j)),
'loggamma_D': (20,),
'logit_d': (0.5,),
'psi_d': (1,),
'psi_D': (1,),
}
class _CythonSpecialMeta(type):
"""
Add time_* benchmarks corresponding to cython_special._bench_*_cy
"""
def __new__(cls, cls_name, bases, dct):
params = [(10, 100, 1000), ('python', 'numpy', 'cython')]
param_names = ['N', 'api']
def get_time_func(name, args):
@with_attributes(params=[(name,), (args,)] + params,
param_names=['name', 'argument'] + param_names)
def func(self, name, args, N, api):
if api == 'python':
self.py_func(N, *args)
elif api == 'numpy':
self.np_func(*self.obj)
else:
self.cy_func(N, *args)
func.__name__ = 'time_' + name
return func
for name in FUNC_ARGS.keys():
func = get_time_func(name, FUNC_ARGS[name])
dct[func.__name__] = func
return type.__new__(cls, cls_name, bases, dct)
class CythonSpecial(metaclass=_CythonSpecialMeta):
def setup(self, name, args, N, api):
self.py_func = getattr(cython_special, '_bench_{}_py'.format(name))
self.cy_func = getattr(cython_special, '_bench_{}_cy'.format(name))
m = re.match('^(.*)_[dDl]+$', name)
self.np_func = getattr(special, m.group(1))
self.obj = []
for arg in args:
self.obj.append(arg*np.ones(N))
self.obj = tuple(self.obj)
| bsd-3-clause | 11b34a26465dce6fd1d651207a066fc9 | 26.942857 | 76 | 0.500511 | 3.227723 | false | false | false | false |
scipy/scipy | scipy/interpolate/_pade.py | 8 | 1827 | from numpy import zeros, asarray, eye, poly1d, hstack, r_
from scipy import linalg
__all__ = ["pade"]
def pade(an, m, n=None):
"""
Return Pade approximation to a polynomial as the ratio of two polynomials.
Parameters
----------
an : (N,) array_like
Taylor series coefficients.
m : int
The order of the returned approximating polynomial `q`.
n : int, optional
The order of the returned approximating polynomial `p`. By default,
the order is ``len(an)-1-m``.
Returns
-------
p, q : Polynomial class
The Pade approximation of the polynomial defined by `an` is
``p(x)/q(x)``.
Examples
--------
>>> import numpy as np
>>> from scipy.interpolate import pade
>>> e_exp = [1.0, 1.0, 1.0/2.0, 1.0/6.0, 1.0/24.0, 1.0/120.0]
>>> p, q = pade(e_exp, 2)
>>> e_exp.reverse()
>>> e_poly = np.poly1d(e_exp)
Compare ``e_poly(x)`` and the Pade approximation ``p(x)/q(x)``
>>> e_poly(1)
2.7166666666666668
>>> p(1)/q(1)
2.7179487179487181
"""
an = asarray(an)
if n is None:
n = len(an) - 1 - m
if n < 0:
raise ValueError("Order of q <m> must be smaller than len(an)-1.")
if n < 0:
raise ValueError("Order of p <n> must be greater than 0.")
N = m + n
if N > len(an)-1:
raise ValueError("Order of q+p <m+n> must be smaller than len(an).")
an = an[:N+1]
Akj = eye(N+1, n+1, dtype=an.dtype)
Bkj = zeros((N+1, m), dtype=an.dtype)
for row in range(1, m+1):
Bkj[row,:row] = -(an[:row])[::-1]
for row in range(m+1, N+1):
Bkj[row,:] = -(an[row-m:row])[::-1]
C = hstack((Akj, Bkj))
pq = linalg.solve(C, an)
p = pq[:n+1]
q = r_[1.0, pq[n+1:]]
return poly1d(p[::-1]), poly1d(q[::-1])
| bsd-3-clause | 86f2f592937100f77b605e2f19eaebce | 26.268657 | 78 | 0.530378 | 2.937299 | false | false | false | false |
scipy/scipy | scipy/spatial/transform/tests/test_rotation_spline.py | 22 | 5035 | from itertools import product
import numpy as np
from numpy.testing import assert_allclose
from pytest import raises
from scipy.spatial.transform import Rotation, RotationSpline
from scipy.spatial.transform._rotation_spline import (
_angular_rate_to_rotvec_dot_matrix,
_rotvec_dot_to_angular_rate_matrix,
_matrix_vector_product_of_stacks,
_angular_acceleration_nonlinear_term,
_create_block_3_diagonal_matrix)
def test_angular_rate_to_rotvec_conversions():
np.random.seed(0)
rv = np.random.randn(4, 3)
A = _angular_rate_to_rotvec_dot_matrix(rv)
A_inv = _rotvec_dot_to_angular_rate_matrix(rv)
# When the rotation vector is aligned with the angular rate, then
# the rotation vector rate and angular rate are the same.
assert_allclose(_matrix_vector_product_of_stacks(A, rv), rv)
assert_allclose(_matrix_vector_product_of_stacks(A_inv, rv), rv)
# A and A_inv must be reciprocal to each other.
I_stack = np.empty((4, 3, 3))
I_stack[:] = np.eye(3)
assert_allclose(np.matmul(A, A_inv), I_stack, atol=1e-15)
def test_angular_rate_nonlinear_term():
# The only simple test is to check that the term is zero when
# the rotation vector
np.random.seed(0)
rv = np.random.rand(4, 3)
assert_allclose(_angular_acceleration_nonlinear_term(rv, rv), 0,
atol=1e-19)
def test_create_block_3_diagonal_matrix():
np.random.seed(0)
A = np.empty((4, 3, 3))
A[:] = np.arange(1, 5)[:, None, None]
B = np.empty((4, 3, 3))
B[:] = -np.arange(1, 5)[:, None, None]
d = 10 * np.arange(10, 15)
banded = _create_block_3_diagonal_matrix(A, B, d)
# Convert the banded matrix to the full matrix.
k, l = list(zip(*product(np.arange(banded.shape[0]),
np.arange(banded.shape[1]))))
k = np.asarray(k)
l = np.asarray(l)
i = k - 5 + l
j = l
values = banded.ravel()
mask = (i >= 0) & (i < 15)
i = i[mask]
j = j[mask]
values = values[mask]
full = np.zeros((15, 15))
full[i, j] = values
zero = np.zeros((3, 3))
eye = np.eye(3)
# Create the reference full matrix in the most straightforward manner.
ref = np.block([
[d[0] * eye, B[0], zero, zero, zero],
[A[0], d[1] * eye, B[1], zero, zero],
[zero, A[1], d[2] * eye, B[2], zero],
[zero, zero, A[2], d[3] * eye, B[3]],
[zero, zero, zero, A[3], d[4] * eye],
])
assert_allclose(full, ref, atol=1e-19)
def test_spline_2_rotations():
times = [0, 10]
rotations = Rotation.from_euler('xyz', [[0, 0, 0], [10, -20, 30]],
degrees=True)
spline = RotationSpline(times, rotations)
rv = (rotations[0].inv() * rotations[1]).as_rotvec()
rate = rv / (times[1] - times[0])
times_check = np.array([-1, 5, 12])
dt = times_check - times[0]
rv_ref = rate * dt[:, None]
assert_allclose(spline(times_check).as_rotvec(), rv_ref)
assert_allclose(spline(times_check, 1), np.resize(rate, (3, 3)))
assert_allclose(spline(times_check, 2), 0, atol=1e-16)
def test_constant_attitude():
times = np.arange(10)
rotations = Rotation.from_rotvec(np.ones((10, 3)))
spline = RotationSpline(times, rotations)
times_check = np.linspace(-1, 11)
assert_allclose(spline(times_check).as_rotvec(), 1, rtol=1e-15)
assert_allclose(spline(times_check, 1), 0, atol=1e-17)
assert_allclose(spline(times_check, 2), 0, atol=1e-17)
assert_allclose(spline(5.5).as_rotvec(), 1, rtol=1e-15)
assert_allclose(spline(5.5, 1), 0, atol=1e-17)
assert_allclose(spline(5.5, 2), 0, atol=1e-17)
def test_spline_properties():
times = np.array([0, 5, 15, 27])
angles = [[-5, 10, 27], [3, 5, 38], [-12, 10, 25], [-15, 20, 11]]
rotations = Rotation.from_euler('xyz', angles, degrees=True)
spline = RotationSpline(times, rotations)
assert_allclose(spline(times).as_euler('xyz', degrees=True), angles)
assert_allclose(spline(0).as_euler('xyz', degrees=True), angles[0])
h = 1e-8
rv0 = spline(times).as_rotvec()
rvm = spline(times - h).as_rotvec()
rvp = spline(times + h).as_rotvec()
assert_allclose(rv0, 0.5 * (rvp + rvm), rtol=1e-15)
r0 = spline(times, 1)
rm = spline(times - h, 1)
rp = spline(times + h, 1)
assert_allclose(r0, 0.5 * (rm + rp), rtol=1e-14)
a0 = spline(times, 2)
am = spline(times - h, 2)
ap = spline(times + h, 2)
assert_allclose(a0, am, rtol=1e-7)
assert_allclose(a0, ap, rtol=1e-7)
def test_error_handling():
raises(ValueError, RotationSpline, [1.0], Rotation.random())
r = Rotation.random(10)
t = np.arange(10).reshape(5, 2)
raises(ValueError, RotationSpline, t, r)
t = np.arange(9)
raises(ValueError, RotationSpline, t, r)
t = np.arange(10)
t[5] = 0
raises(ValueError, RotationSpline, t, r)
t = np.arange(10)
s = RotationSpline(t, r)
raises(ValueError, s, 10, -1)
raises(ValueError, s, np.arange(10).reshape(5, 2))
| bsd-3-clause | a1d0d0e1b928a7a1556cb897c9249420 | 30.273292 | 74 | 0.606157 | 2.912088 | false | true | false | false |
scipy/scipy | scipy/special/tests/test_nan_inputs.py | 26 | 1845 | """Test how the ufuncs in special handle nan inputs.
"""
from typing import Callable, Dict
import numpy as np
from numpy.testing import assert_array_equal, assert_, suppress_warnings
import pytest
import scipy.special as sc
KNOWNFAILURES: Dict[str, Callable] = {}
POSTPROCESSING: Dict[str, Callable] = {}
def _get_ufuncs():
ufuncs = []
ufunc_names = []
for name in sorted(sc.__dict__):
obj = sc.__dict__[name]
if not isinstance(obj, np.ufunc):
continue
msg = KNOWNFAILURES.get(obj)
if msg is None:
ufuncs.append(obj)
ufunc_names.append(name)
else:
fail = pytest.mark.xfail(run=False, reason=msg)
ufuncs.append(pytest.param(obj, marks=fail))
ufunc_names.append(name)
return ufuncs, ufunc_names
UFUNCS, UFUNC_NAMES = _get_ufuncs()
@pytest.mark.parametrize("func", UFUNCS, ids=UFUNC_NAMES)
def test_nan_inputs(func):
args = (np.nan,)*func.nin
with suppress_warnings() as sup:
# Ignore warnings about unsafe casts from legacy wrappers
sup.filter(RuntimeWarning,
"floating point number truncated to an integer")
try:
with suppress_warnings() as sup:
sup.filter(DeprecationWarning)
res = func(*args)
except TypeError:
# One of the arguments doesn't take real inputs
return
if func in POSTPROCESSING:
res = POSTPROCESSING[func](*res)
msg = "got {} instead of nan".format(res)
assert_array_equal(np.isnan(res), True, err_msg=msg)
def test_legacy_cast():
with suppress_warnings() as sup:
sup.filter(RuntimeWarning,
"floating point number truncated to an integer")
res = sc.bdtrc(np.nan, 1, 0.5)
assert_(np.isnan(res))
| bsd-3-clause | 2450144e4d3039c675d679b23214748d | 27.828125 | 72 | 0.611382 | 3.804124 | false | true | false | false |
scipy/scipy | scipy/stats/_discrete_distns.py | 10 | 54698 | #
# Author: Travis Oliphant 2002-2011 with contributions from
# SciPy Developers 2004-2011
#
from functools import partial
import warnings
from scipy import special
from scipy.special import entr, logsumexp, betaln, gammaln as gamln, zeta
from scipy._lib._util import _lazywhere, rng_integers
from scipy.interpolate import interp1d
from numpy import floor, ceil, log, exp, sqrt, log1p, expm1, tanh, cosh, sinh
import numpy as np
from ._distn_infrastructure import (rv_discrete, get_distribution_names,
_check_shape, _ShapeInfo)
import scipy.stats._boost as _boost
from ._biasedurn import (_PyFishersNCHypergeometric,
_PyWalleniusNCHypergeometric,
_PyStochasticLib3)
def _isintegral(x):
return x == np.round(x)
class binom_gen(rv_discrete):
r"""A binomial discrete random variable.
%(before_notes)s
Notes
-----
The probability mass function for `binom` is:
.. math::
f(k) = \binom{n}{k} p^k (1-p)^{n-k}
for :math:`k \in \{0, 1, \dots, n\}`, :math:`0 \leq p \leq 1`
`binom` takes :math:`n` and :math:`p` as shape parameters,
where :math:`p` is the probability of a single success
and :math:`1-p` is the probability of a single failure.
%(after_notes)s
%(example)s
See Also
--------
hypergeom, nbinom, nhypergeom
"""
def _shape_info(self):
return [_ShapeInfo("n", True, (0, np.inf), (True, False)),
_ShapeInfo("p", False, (0, 1), (True, True))]
def _rvs(self, n, p, size=None, random_state=None):
return random_state.binomial(n, p, size)
def _argcheck(self, n, p):
return (n >= 0) & _isintegral(n) & (p >= 0) & (p <= 1)
def _get_support(self, n, p):
return self.a, n
def _logpmf(self, x, n, p):
k = floor(x)
combiln = (gamln(n+1) - (gamln(k+1) + gamln(n-k+1)))
return combiln + special.xlogy(k, p) + special.xlog1py(n-k, -p)
def _pmf(self, x, n, p):
# binom.pmf(k) = choose(n, k) * p**k * (1-p)**(n-k)
return _boost._binom_pdf(x, n, p)
def _cdf(self, x, n, p):
k = floor(x)
return _boost._binom_cdf(k, n, p)
def _sf(self, x, n, p):
k = floor(x)
return _boost._binom_sf(k, n, p)
def _isf(self, x, n, p):
return _boost._binom_isf(x, n, p)
def _ppf(self, q, n, p):
return _boost._binom_ppf(q, n, p)
def _stats(self, n, p, moments='mv'):
mu = _boost._binom_mean(n, p)
var = _boost._binom_variance(n, p)
g1, g2 = None, None
if 's' in moments:
g1 = _boost._binom_skewness(n, p)
if 'k' in moments:
g2 = _boost._binom_kurtosis_excess(n, p)
return mu, var, g1, g2
def _entropy(self, n, p):
k = np.r_[0:n + 1]
vals = self._pmf(k, n, p)
return np.sum(entr(vals), axis=0)
binom = binom_gen(name='binom')
class bernoulli_gen(binom_gen):
r"""A Bernoulli discrete random variable.
%(before_notes)s
Notes
-----
The probability mass function for `bernoulli` is:
.. math::
f(k) = \begin{cases}1-p &\text{if } k = 0\\
p &\text{if } k = 1\end{cases}
for :math:`k` in :math:`\{0, 1\}`, :math:`0 \leq p \leq 1`
`bernoulli` takes :math:`p` as shape parameter,
where :math:`p` is the probability of a single success
and :math:`1-p` is the probability of a single failure.
%(after_notes)s
%(example)s
"""
def _shape_info(self):
return [_ShapeInfo("p", False, (0, 1), (True, True))]
def _rvs(self, p, size=None, random_state=None):
return binom_gen._rvs(self, 1, p, size=size, random_state=random_state)
def _argcheck(self, p):
return (p >= 0) & (p <= 1)
def _get_support(self, p):
# Overrides binom_gen._get_support!x
return self.a, self.b
def _logpmf(self, x, p):
return binom._logpmf(x, 1, p)
def _pmf(self, x, p):
# bernoulli.pmf(k) = 1-p if k = 0
# = p if k = 1
return binom._pmf(x, 1, p)
def _cdf(self, x, p):
return binom._cdf(x, 1, p)
def _sf(self, x, p):
return binom._sf(x, 1, p)
def _isf(self, x, p):
return binom._isf(x, 1, p)
def _ppf(self, q, p):
return binom._ppf(q, 1, p)
def _stats(self, p):
return binom._stats(1, p)
def _entropy(self, p):
return entr(p) + entr(1-p)
bernoulli = bernoulli_gen(b=1, name='bernoulli')
class betabinom_gen(rv_discrete):
r"""A beta-binomial discrete random variable.
%(before_notes)s
Notes
-----
The beta-binomial distribution is a binomial distribution with a
probability of success `p` that follows a beta distribution.
The probability mass function for `betabinom` is:
.. math::
f(k) = \binom{n}{k} \frac{B(k + a, n - k + b)}{B(a, b)}
for :math:`k \in \{0, 1, \dots, n\}`, :math:`n \geq 0`, :math:`a > 0`,
:math:`b > 0`, where :math:`B(a, b)` is the beta function.
`betabinom` takes :math:`n`, :math:`a`, and :math:`b` as shape parameters.
References
----------
.. [1] https://en.wikipedia.org/wiki/Beta-binomial_distribution
%(after_notes)s
.. versionadded:: 1.4.0
See Also
--------
beta, binom
%(example)s
"""
def _shape_info(self):
return [_ShapeInfo("n", True, (0, np.inf), (True, False)),
_ShapeInfo("a", False, (0, np.inf), (False, False)),
_ShapeInfo("b", False, (0, np.inf), (False, False))]
def _rvs(self, n, a, b, size=None, random_state=None):
p = random_state.beta(a, b, size)
return random_state.binomial(n, p, size)
def _get_support(self, n, a, b):
return 0, n
def _argcheck(self, n, a, b):
return (n >= 0) & _isintegral(n) & (a > 0) & (b > 0)
def _logpmf(self, x, n, a, b):
k = floor(x)
combiln = -log(n + 1) - betaln(n - k + 1, k + 1)
return combiln + betaln(k + a, n - k + b) - betaln(a, b)
def _pmf(self, x, n, a, b):
return exp(self._logpmf(x, n, a, b))
def _stats(self, n, a, b, moments='mv'):
e_p = a / (a + b)
e_q = 1 - e_p
mu = n * e_p
var = n * (a + b + n) * e_p * e_q / (a + b + 1)
g1, g2 = None, None
if 's' in moments:
g1 = 1.0 / sqrt(var)
g1 *= (a + b + 2 * n) * (b - a)
g1 /= (a + b + 2) * (a + b)
if 'k' in moments:
g2 = a + b
g2 *= (a + b - 1 + 6 * n)
g2 += 3 * a * b * (n - 2)
g2 += 6 * n ** 2
g2 -= 3 * e_p * b * n * (6 - n)
g2 -= 18 * e_p * e_q * n ** 2
g2 *= (a + b) ** 2 * (1 + a + b)
g2 /= (n * a * b * (a + b + 2) * (a + b + 3) * (a + b + n))
g2 -= 3
return mu, var, g1, g2
betabinom = betabinom_gen(name='betabinom')
class nbinom_gen(rv_discrete):
r"""A negative binomial discrete random variable.
%(before_notes)s
Notes
-----
Negative binomial distribution describes a sequence of i.i.d. Bernoulli
trials, repeated until a predefined, non-random number of successes occurs.
The probability mass function of the number of failures for `nbinom` is:
.. math::
f(k) = \binom{k+n-1}{n-1} p^n (1-p)^k
for :math:`k \ge 0`, :math:`0 < p \leq 1`
`nbinom` takes :math:`n` and :math:`p` as shape parameters where :math:`n`
is the number of successes, :math:`p` is the probability of a single
success, and :math:`1-p` is the probability of a single failure.
Another common parameterization of the negative binomial distribution is
in terms of the mean number of failures :math:`\mu` to achieve :math:`n`
successes. The mean :math:`\mu` is related to the probability of success
as
.. math::
p = \frac{n}{n + \mu}
The number of successes :math:`n` may also be specified in terms of a
"dispersion", "heterogeneity", or "aggregation" parameter :math:`\alpha`,
which relates the mean :math:`\mu` to the variance :math:`\sigma^2`,
e.g. :math:`\sigma^2 = \mu + \alpha \mu^2`. Regardless of the convention
used for :math:`\alpha`,
.. math::
p &= \frac{\mu}{\sigma^2} \\
n &= \frac{\mu^2}{\sigma^2 - \mu}
%(after_notes)s
%(example)s
See Also
--------
hypergeom, binom, nhypergeom
"""
def _shape_info(self):
return [_ShapeInfo("n", True, (0, np.inf), (True, False)),
_ShapeInfo("p", False, (0, 1), (True, True))]
def _rvs(self, n, p, size=None, random_state=None):
return random_state.negative_binomial(n, p, size)
def _argcheck(self, n, p):
return (n > 0) & (p > 0) & (p <= 1)
def _pmf(self, x, n, p):
# nbinom.pmf(k) = choose(k+n-1, n-1) * p**n * (1-p)**k
return _boost._nbinom_pdf(x, n, p)
def _logpmf(self, x, n, p):
coeff = gamln(n+x) - gamln(x+1) - gamln(n)
return coeff + n*log(p) + special.xlog1py(x, -p)
def _cdf(self, x, n, p):
k = floor(x)
return _boost._nbinom_cdf(k, n, p)
def _logcdf(self, x, n, p):
k = floor(x)
cdf = self._cdf(k, n, p)
cond = cdf > 0.5
def f1(k, n, p):
return np.log1p(-special.betainc(k + 1, n, 1 - p))
# do calc in place
logcdf = cdf
with np.errstate(divide='ignore'):
logcdf[cond] = f1(k[cond], n[cond], p[cond])
logcdf[~cond] = np.log(cdf[~cond])
return logcdf
def _sf(self, x, n, p):
k = floor(x)
return _boost._nbinom_sf(k, n, p)
def _isf(self, x, n, p):
with warnings.catch_warnings():
# See gh-14901
message = "overflow encountered in _nbinom_isf"
warnings.filterwarnings('ignore', message=message)
return _boost._nbinom_isf(x, n, p)
def _ppf(self, q, n, p):
with warnings.catch_warnings():
message = "overflow encountered in _nbinom_ppf"
warnings.filterwarnings('ignore', message=message)
return _boost._nbinom_ppf(q, n, p)
def _stats(self, n, p):
return(
_boost._nbinom_mean(n, p),
_boost._nbinom_variance(n, p),
_boost._nbinom_skewness(n, p),
_boost._nbinom_kurtosis_excess(n, p),
)
nbinom = nbinom_gen(name='nbinom')
class geom_gen(rv_discrete):
r"""A geometric discrete random variable.
%(before_notes)s
Notes
-----
The probability mass function for `geom` is:
.. math::
f(k) = (1-p)^{k-1} p
for :math:`k \ge 1`, :math:`0 < p \leq 1`
`geom` takes :math:`p` as shape parameter,
where :math:`p` is the probability of a single success
and :math:`1-p` is the probability of a single failure.
%(after_notes)s
See Also
--------
planck
%(example)s
"""
def _shape_info(self):
return [_ShapeInfo("p", False, (0, 1), (True, True))]
def _rvs(self, p, size=None, random_state=None):
return random_state.geometric(p, size=size)
def _argcheck(self, p):
return (p <= 1) & (p > 0)
def _pmf(self, k, p):
return np.power(1-p, k-1) * p
def _logpmf(self, k, p):
return special.xlog1py(k - 1, -p) + log(p)
def _cdf(self, x, p):
k = floor(x)
return -expm1(log1p(-p)*k)
def _sf(self, x, p):
return np.exp(self._logsf(x, p))
def _logsf(self, x, p):
k = floor(x)
return k*log1p(-p)
def _ppf(self, q, p):
vals = ceil(log1p(-q) / log1p(-p))
temp = self._cdf(vals-1, p)
return np.where((temp >= q) & (vals > 0), vals-1, vals)
def _stats(self, p):
mu = 1.0/p
qr = 1.0-p
var = qr / p / p
g1 = (2.0-p) / sqrt(qr)
g2 = np.polyval([1, -6, 6], p)/(1.0-p)
return mu, var, g1, g2
geom = geom_gen(a=1, name='geom', longname="A geometric")
class hypergeom_gen(rv_discrete):
r"""A hypergeometric discrete random variable.
The hypergeometric distribution models drawing objects from a bin.
`M` is the total number of objects, `n` is total number of Type I objects.
The random variate represents the number of Type I objects in `N` drawn
without replacement from the total population.
%(before_notes)s
Notes
-----
The symbols used to denote the shape parameters (`M`, `n`, and `N`) are not
universally accepted. See the Examples for a clarification of the
definitions used here.
The probability mass function is defined as,
.. math:: p(k, M, n, N) = \frac{\binom{n}{k} \binom{M - n}{N - k}}
{\binom{M}{N}}
for :math:`k \in [\max(0, N - M + n), \min(n, N)]`, where the binomial
coefficients are defined as,
.. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}.
%(after_notes)s
Examples
--------
>>> import numpy as np
>>> from scipy.stats import hypergeom
>>> import matplotlib.pyplot as plt
Suppose we have a collection of 20 animals, of which 7 are dogs. Then if
we want to know the probability of finding a given number of dogs if we
choose at random 12 of the 20 animals, we can initialize a frozen
distribution and plot the probability mass function:
>>> [M, n, N] = [20, 7, 12]
>>> rv = hypergeom(M, n, N)
>>> x = np.arange(0, n+1)
>>> pmf_dogs = rv.pmf(x)
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> ax.plot(x, pmf_dogs, 'bo')
>>> ax.vlines(x, 0, pmf_dogs, lw=2)
>>> ax.set_xlabel('# of dogs in our group of chosen animals')
>>> ax.set_ylabel('hypergeom PMF')
>>> plt.show()
Instead of using a frozen distribution we can also use `hypergeom`
methods directly. To for example obtain the cumulative distribution
function, use:
>>> prb = hypergeom.cdf(x, M, n, N)
And to generate random numbers:
>>> R = hypergeom.rvs(M, n, N, size=10)
See Also
--------
nhypergeom, binom, nbinom
"""
def _shape_info(self):
return [_ShapeInfo("M", True, (0, np.inf), (True, False)),
_ShapeInfo("n", True, (0, np.inf), (True, False)),
_ShapeInfo("N", True, (0, np.inf), (True, False))]
def _rvs(self, M, n, N, size=None, random_state=None):
return random_state.hypergeometric(n, M-n, N, size=size)
def _get_support(self, M, n, N):
return np.maximum(N-(M-n), 0), np.minimum(n, N)
def _argcheck(self, M, n, N):
cond = (M > 0) & (n >= 0) & (N >= 0)
cond &= (n <= M) & (N <= M)
cond &= _isintegral(M) & _isintegral(n) & _isintegral(N)
return cond
def _logpmf(self, k, M, n, N):
tot, good = M, n
bad = tot - good
result = (betaln(good+1, 1) + betaln(bad+1, 1) + betaln(tot-N+1, N+1) -
betaln(k+1, good-k+1) - betaln(N-k+1, bad-N+k+1) -
betaln(tot+1, 1))
return result
def _pmf(self, k, M, n, N):
return _boost._hypergeom_pdf(k, n, N, M)
def _cdf(self, k, M, n, N):
return _boost._hypergeom_cdf(k, n, N, M)
def _stats(self, M, n, N):
M, n, N = 1. * M, 1. * n, 1. * N
m = M - n
# Boost kurtosis_excess doesn't return the same as the value
# computed here.
g2 = M * (M + 1) - 6. * N * (M - N) - 6. * n * m
g2 *= (M - 1) * M * M
g2 += 6. * n * N * (M - N) * m * (5. * M - 6)
g2 /= n * N * (M - N) * m * (M - 2.) * (M - 3.)
return (
_boost._hypergeom_mean(n, N, M),
_boost._hypergeom_variance(n, N, M),
_boost._hypergeom_skewness(n, N, M),
g2,
)
def _entropy(self, M, n, N):
k = np.r_[N - (M - n):min(n, N) + 1]
vals = self.pmf(k, M, n, N)
return np.sum(entr(vals), axis=0)
def _sf(self, k, M, n, N):
return _boost._hypergeom_sf(k, n, N, M)
def _logsf(self, k, M, n, N):
res = []
for quant, tot, good, draw in zip(*np.broadcast_arrays(k, M, n, N)):
if (quant + 0.5) * (tot + 0.5) < (good - 0.5) * (draw - 0.5):
# Less terms to sum if we calculate log(1-cdf)
res.append(log1p(-exp(self.logcdf(quant, tot, good, draw))))
else:
# Integration over probability mass function using logsumexp
k2 = np.arange(quant + 1, draw + 1)
res.append(logsumexp(self._logpmf(k2, tot, good, draw)))
return np.asarray(res)
def _logcdf(self, k, M, n, N):
res = []
for quant, tot, good, draw in zip(*np.broadcast_arrays(k, M, n, N)):
if (quant + 0.5) * (tot + 0.5) > (good - 0.5) * (draw - 0.5):
# Less terms to sum if we calculate log(1-sf)
res.append(log1p(-exp(self.logsf(quant, tot, good, draw))))
else:
# Integration over probability mass function using logsumexp
k2 = np.arange(0, quant + 1)
res.append(logsumexp(self._logpmf(k2, tot, good, draw)))
return np.asarray(res)
hypergeom = hypergeom_gen(name='hypergeom')
class nhypergeom_gen(rv_discrete):
r"""A negative hypergeometric discrete random variable.
Consider a box containing :math:`M` balls:, :math:`n` red and
:math:`M-n` blue. We randomly sample balls from the box, one
at a time and *without* replacement, until we have picked :math:`r`
blue balls. `nhypergeom` is the distribution of the number of
red balls :math:`k` we have picked.
%(before_notes)s
Notes
-----
The symbols used to denote the shape parameters (`M`, `n`, and `r`) are not
universally accepted. See the Examples for a clarification of the
definitions used here.
The probability mass function is defined as,
.. math:: f(k; M, n, r) = \frac{{{k+r-1}\choose{k}}{{M-r-k}\choose{n-k}}}
{{M \choose n}}
for :math:`k \in [0, n]`, :math:`n \in [0, M]`, :math:`r \in [0, M-n]`,
and the binomial coefficient is:
.. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}.
It is equivalent to observing :math:`k` successes in :math:`k+r-1`
samples with :math:`k+r`'th sample being a failure. The former
can be modelled as a hypergeometric distribution. The probability
of the latter is simply the number of failures remaining
:math:`M-n-(r-1)` divided by the size of the remaining population
:math:`M-(k+r-1)`. This relationship can be shown as:
.. math:: NHG(k;M,n,r) = HG(k;M,n,k+r-1)\frac{(M-n-(r-1))}{(M-(k+r-1))}
where :math:`NHG` is probability mass function (PMF) of the
negative hypergeometric distribution and :math:`HG` is the
PMF of the hypergeometric distribution.
%(after_notes)s
Examples
--------
>>> import numpy as np
>>> from scipy.stats import nhypergeom
>>> import matplotlib.pyplot as plt
Suppose we have a collection of 20 animals, of which 7 are dogs.
Then if we want to know the probability of finding a given number
of dogs (successes) in a sample with exactly 12 animals that
aren't dogs (failures), we can initialize a frozen distribution
and plot the probability mass function:
>>> M, n, r = [20, 7, 12]
>>> rv = nhypergeom(M, n, r)
>>> x = np.arange(0, n+2)
>>> pmf_dogs = rv.pmf(x)
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> ax.plot(x, pmf_dogs, 'bo')
>>> ax.vlines(x, 0, pmf_dogs, lw=2)
>>> ax.set_xlabel('# of dogs in our group with given 12 failures')
>>> ax.set_ylabel('nhypergeom PMF')
>>> plt.show()
Instead of using a frozen distribution we can also use `nhypergeom`
methods directly. To for example obtain the probability mass
function, use:
>>> prb = nhypergeom.pmf(x, M, n, r)
And to generate random numbers:
>>> R = nhypergeom.rvs(M, n, r, size=10)
To verify the relationship between `hypergeom` and `nhypergeom`, use:
>>> from scipy.stats import hypergeom, nhypergeom
>>> M, n, r = 45, 13, 8
>>> k = 6
>>> nhypergeom.pmf(k, M, n, r)
0.06180776620271643
>>> hypergeom.pmf(k, M, n, k+r-1) * (M - n - (r-1)) / (M - (k+r-1))
0.06180776620271644
See Also
--------
hypergeom, binom, nbinom
References
----------
.. [1] Negative Hypergeometric Distribution on Wikipedia
https://en.wikipedia.org/wiki/Negative_hypergeometric_distribution
.. [2] Negative Hypergeometric Distribution from
http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Negativehypergeometric.pdf
"""
def _shape_info(self):
return [_ShapeInfo("M", True, (0, np.inf), (True, False)),
_ShapeInfo("n", True, (0, np.inf), (True, False)),
_ShapeInfo("r", True, (0, np.inf), (True, False))]
def _get_support(self, M, n, r):
return 0, n
def _argcheck(self, M, n, r):
cond = (n >= 0) & (n <= M) & (r >= 0) & (r <= M-n)
cond &= _isintegral(M) & _isintegral(n) & _isintegral(r)
return cond
def _rvs(self, M, n, r, size=None, random_state=None):
@_vectorize_rvs_over_shapes
def _rvs1(M, n, r, size, random_state):
# invert cdf by calculating all values in support, scalar M, n, r
a, b = self.support(M, n, r)
ks = np.arange(a, b+1)
cdf = self.cdf(ks, M, n, r)
ppf = interp1d(cdf, ks, kind='next', fill_value='extrapolate')
rvs = ppf(random_state.uniform(size=size)).astype(int)
if size is None:
return rvs.item()
return rvs
return _rvs1(M, n, r, size=size, random_state=random_state)
def _logpmf(self, k, M, n, r):
cond = ((r == 0) & (k == 0))
result = _lazywhere(~cond, (k, M, n, r),
lambda k, M, n, r:
(-betaln(k+1, r) + betaln(k+r, 1) -
betaln(n-k+1, M-r-n+1) + betaln(M-r-k+1, 1) +
betaln(n+1, M-n+1) - betaln(M+1, 1)),
fillvalue=0.0)
return result
def _pmf(self, k, M, n, r):
# same as the following but numerically more precise
# return comb(k+r-1, k) * comb(M-r-k, n-k) / comb(M, n)
return exp(self._logpmf(k, M, n, r))
def _stats(self, M, n, r):
# Promote the datatype to at least float
# mu = rn / (M-n+1)
M, n, r = 1.*M, 1.*n, 1.*r
mu = r*n / (M-n+1)
var = r*(M+1)*n / ((M-n+1)*(M-n+2)) * (1 - r / (M-n+1))
# The skew and kurtosis are mathematically
# intractable so return `None`. See [2]_.
g1, g2 = None, None
return mu, var, g1, g2
nhypergeom = nhypergeom_gen(name='nhypergeom')
# FIXME: Fails _cdfvec
class logser_gen(rv_discrete):
r"""A Logarithmic (Log-Series, Series) discrete random variable.
%(before_notes)s
Notes
-----
The probability mass function for `logser` is:
.. math::
f(k) = - \frac{p^k}{k \log(1-p)}
for :math:`k \ge 1`, :math:`0 < p < 1`
`logser` takes :math:`p` as shape parameter,
where :math:`p` is the probability of a single success
and :math:`1-p` is the probability of a single failure.
%(after_notes)s
%(example)s
"""
def _shape_info(self):
return [_ShapeInfo("p", False, (0, 1), (True, True))]
def _rvs(self, p, size=None, random_state=None):
# looks wrong for p>0.5, too few k=1
# trying to use generic is worse, no k=1 at all
return random_state.logseries(p, size=size)
def _argcheck(self, p):
return (p > 0) & (p < 1)
def _pmf(self, k, p):
# logser.pmf(k) = - p**k / (k*log(1-p))
return -np.power(p, k) * 1.0 / k / special.log1p(-p)
def _stats(self, p):
r = special.log1p(-p)
mu = p / (p - 1.0) / r
mu2p = -p / r / (p - 1.0)**2
var = mu2p - mu*mu
mu3p = -p / r * (1.0+p) / (1.0 - p)**3
mu3 = mu3p - 3*mu*mu2p + 2*mu**3
g1 = mu3 / np.power(var, 1.5)
mu4p = -p / r * (
1.0 / (p-1)**2 - 6*p / (p - 1)**3 + 6*p*p / (p-1)**4)
mu4 = mu4p - 4*mu3p*mu + 6*mu2p*mu*mu - 3*mu**4
g2 = mu4 / var**2 - 3.0
return mu, var, g1, g2
logser = logser_gen(a=1, name='logser', longname='A logarithmic')
class poisson_gen(rv_discrete):
r"""A Poisson discrete random variable.
%(before_notes)s
Notes
-----
The probability mass function for `poisson` is:
.. math::
f(k) = \exp(-\mu) \frac{\mu^k}{k!}
for :math:`k \ge 0`.
`poisson` takes :math:`\mu \geq 0` as shape parameter.
When :math:`\mu = 0`, the ``pmf`` method
returns ``1.0`` at quantile :math:`k = 0`.
%(after_notes)s
%(example)s
"""
def _shape_info(self):
return [_ShapeInfo("mu", False, (0, np.inf), (True, False))]
# Override rv_discrete._argcheck to allow mu=0.
def _argcheck(self, mu):
return mu >= 0
def _rvs(self, mu, size=None, random_state=None):
return random_state.poisson(mu, size)
def _logpmf(self, k, mu):
Pk = special.xlogy(k, mu) - gamln(k + 1) - mu
return Pk
def _pmf(self, k, mu):
# poisson.pmf(k) = exp(-mu) * mu**k / k!
return exp(self._logpmf(k, mu))
def _cdf(self, x, mu):
k = floor(x)
return special.pdtr(k, mu)
def _sf(self, x, mu):
k = floor(x)
return special.pdtrc(k, mu)
def _ppf(self, q, mu):
vals = ceil(special.pdtrik(q, mu))
vals1 = np.maximum(vals - 1, 0)
temp = special.pdtr(vals1, mu)
return np.where(temp >= q, vals1, vals)
def _stats(self, mu):
var = mu
tmp = np.asarray(mu)
mu_nonzero = tmp > 0
g1 = _lazywhere(mu_nonzero, (tmp,), lambda x: sqrt(1.0/x), np.inf)
g2 = _lazywhere(mu_nonzero, (tmp,), lambda x: 1.0/x, np.inf)
return mu, var, g1, g2
poisson = poisson_gen(name="poisson", longname='A Poisson')
class planck_gen(rv_discrete):
r"""A Planck discrete exponential random variable.
%(before_notes)s
Notes
-----
The probability mass function for `planck` is:
.. math::
f(k) = (1-\exp(-\lambda)) \exp(-\lambda k)
for :math:`k \ge 0` and :math:`\lambda > 0`.
`planck` takes :math:`\lambda` as shape parameter. The Planck distribution
can be written as a geometric distribution (`geom`) with
:math:`p = 1 - \exp(-\lambda)` shifted by ``loc = -1``.
%(after_notes)s
See Also
--------
geom
%(example)s
"""
def _shape_info(self):
return [_ShapeInfo("lambda", False, (0, np.inf), (False, False))]
def _argcheck(self, lambda_):
return lambda_ > 0
def _pmf(self, k, lambda_):
return -expm1(-lambda_)*exp(-lambda_*k)
def _cdf(self, x, lambda_):
k = floor(x)
return -expm1(-lambda_*(k+1))
def _sf(self, x, lambda_):
return exp(self._logsf(x, lambda_))
def _logsf(self, x, lambda_):
k = floor(x)
return -lambda_*(k+1)
def _ppf(self, q, lambda_):
vals = ceil(-1.0/lambda_ * log1p(-q)-1)
vals1 = (vals-1).clip(*(self._get_support(lambda_)))
temp = self._cdf(vals1, lambda_)
return np.where(temp >= q, vals1, vals)
def _rvs(self, lambda_, size=None, random_state=None):
# use relation to geometric distribution for sampling
p = -expm1(-lambda_)
return random_state.geometric(p, size=size) - 1.0
def _stats(self, lambda_):
mu = 1/expm1(lambda_)
var = exp(-lambda_)/(expm1(-lambda_))**2
g1 = 2*cosh(lambda_/2.0)
g2 = 4+2*cosh(lambda_)
return mu, var, g1, g2
def _entropy(self, lambda_):
C = -expm1(-lambda_)
return lambda_*exp(-lambda_)/C - log(C)
planck = planck_gen(a=0, name='planck', longname='A discrete exponential ')
class boltzmann_gen(rv_discrete):
r"""A Boltzmann (Truncated Discrete Exponential) random variable.
%(before_notes)s
Notes
-----
The probability mass function for `boltzmann` is:
.. math::
f(k) = (1-\exp(-\lambda)) \exp(-\lambda k) / (1-\exp(-\lambda N))
for :math:`k = 0,..., N-1`.
`boltzmann` takes :math:`\lambda > 0` and :math:`N > 0` as shape parameters.
%(after_notes)s
%(example)s
"""
def _shape_info(self):
return [_ShapeInfo("lambda_", False, (0, np.inf), (False, False)),
_ShapeInfo("N", True, (0, np.inf), (False, False))]
def _argcheck(self, lambda_, N):
return (lambda_ > 0) & (N > 0) & _isintegral(N)
def _get_support(self, lambda_, N):
return self.a, N - 1
def _pmf(self, k, lambda_, N):
# boltzmann.pmf(k) =
# (1-exp(-lambda_)*exp(-lambda_*k)/(1-exp(-lambda_*N))
fact = (1-exp(-lambda_))/(1-exp(-lambda_*N))
return fact*exp(-lambda_*k)
def _cdf(self, x, lambda_, N):
k = floor(x)
return (1-exp(-lambda_*(k+1)))/(1-exp(-lambda_*N))
def _ppf(self, q, lambda_, N):
qnew = q*(1-exp(-lambda_*N))
vals = ceil(-1.0/lambda_ * log(1-qnew)-1)
vals1 = (vals-1).clip(0.0, np.inf)
temp = self._cdf(vals1, lambda_, N)
return np.where(temp >= q, vals1, vals)
def _stats(self, lambda_, N):
z = exp(-lambda_)
zN = exp(-lambda_*N)
mu = z/(1.0-z)-N*zN/(1-zN)
var = z/(1.0-z)**2 - N*N*zN/(1-zN)**2
trm = (1-zN)/(1-z)
trm2 = (z*trm**2 - N*N*zN)
g1 = z*(1+z)*trm**3 - N**3*zN*(1+zN)
g1 = g1 / trm2**(1.5)
g2 = z*(1+4*z+z*z)*trm**4 - N**4 * zN*(1+4*zN+zN*zN)
g2 = g2 / trm2 / trm2
return mu, var, g1, g2
boltzmann = boltzmann_gen(name='boltzmann', a=0,
longname='A truncated discrete exponential ')
class randint_gen(rv_discrete):
r"""A uniform discrete random variable.
%(before_notes)s
Notes
-----
The probability mass function for `randint` is:
.. math::
f(k) = \frac{1}{\texttt{high} - \texttt{low}}
for :math:`k \in \{\texttt{low}, \dots, \texttt{high} - 1\}`.
`randint` takes :math:`\texttt{low}` and :math:`\texttt{high}` as shape
parameters.
%(after_notes)s
%(example)s
"""
def _shape_info(self):
return [_ShapeInfo("low", True, (-np.inf, np.inf), (False, False)),
_ShapeInfo("high", True, (-np.inf, np.inf), (False, False))]
def _argcheck(self, low, high):
return (high > low) & _isintegral(low) & _isintegral(high)
def _get_support(self, low, high):
return low, high-1
def _pmf(self, k, low, high):
# randint.pmf(k) = 1./(high - low)
p = np.ones_like(k) / (high - low)
return np.where((k >= low) & (k < high), p, 0.)
def _cdf(self, x, low, high):
k = floor(x)
return (k - low + 1.) / (high - low)
def _ppf(self, q, low, high):
vals = ceil(q * (high - low) + low) - 1
vals1 = (vals - 1).clip(low, high)
temp = self._cdf(vals1, low, high)
return np.where(temp >= q, vals1, vals)
def _stats(self, low, high):
m2, m1 = np.asarray(high), np.asarray(low)
mu = (m2 + m1 - 1.0) / 2
d = m2 - m1
var = (d*d - 1) / 12.0
g1 = 0.0
g2 = -6.0/5.0 * (d*d + 1.0) / (d*d - 1.0)
return mu, var, g1, g2
def _rvs(self, low, high, size=None, random_state=None):
"""An array of *size* random integers >= ``low`` and < ``high``."""
if np.asarray(low).size == 1 and np.asarray(high).size == 1:
# no need to vectorize in that case
return rng_integers(random_state, low, high, size=size)
if size is not None:
# NumPy's RandomState.randint() doesn't broadcast its arguments.
# Use `broadcast_to()` to extend the shapes of low and high
# up to size. Then we can use the numpy.vectorize'd
# randint without needing to pass it a `size` argument.
low = np.broadcast_to(low, size)
high = np.broadcast_to(high, size)
randint = np.vectorize(partial(rng_integers, random_state),
otypes=[np.int_])
return randint(low, high)
def _entropy(self, low, high):
return log(high - low)
randint = randint_gen(name='randint', longname='A discrete uniform '
'(random integer)')
# FIXME: problems sampling.
class zipf_gen(rv_discrete):
r"""A Zipf (Zeta) discrete random variable.
%(before_notes)s
See Also
--------
zipfian
Notes
-----
The probability mass function for `zipf` is:
.. math::
f(k, a) = \frac{1}{\zeta(a) k^a}
for :math:`k \ge 1`, :math:`a > 1`.
`zipf` takes :math:`a > 1` as shape parameter. :math:`\zeta` is the
Riemann zeta function (`scipy.special.zeta`)
The Zipf distribution is also known as the zeta distribution, which is
a special case of the Zipfian distribution (`zipfian`).
%(after_notes)s
References
----------
.. [1] "Zeta Distribution", Wikipedia,
https://en.wikipedia.org/wiki/Zeta_distribution
%(example)s
Confirm that `zipf` is the large `n` limit of `zipfian`.
>>> import numpy as np
>>> from scipy.stats import zipfian
>>> k = np.arange(11)
>>> np.allclose(zipf.pmf(k, a), zipfian.pmf(k, a, n=10000000))
True
"""
def _shape_info(self):
return [_ShapeInfo("a", False, (1, np.inf), (False, False))]
def _rvs(self, a, size=None, random_state=None):
return random_state.zipf(a, size=size)
def _argcheck(self, a):
return a > 1
def _pmf(self, k, a):
# zipf.pmf(k, a) = 1/(zeta(a) * k**a)
Pk = 1.0 / special.zeta(a, 1) / k**a
return Pk
def _munp(self, n, a):
return _lazywhere(
a > n + 1, (a, n),
lambda a, n: special.zeta(a - n, 1) / special.zeta(a, 1),
np.inf)
zipf = zipf_gen(a=1, name='zipf', longname='A Zipf')
def _gen_harmonic_gt1(n, a):
"""Generalized harmonic number, a > 1"""
# See https://en.wikipedia.org/wiki/Harmonic_number; search for "hurwitz"
return zeta(a, 1) - zeta(a, n+1)
def _gen_harmonic_leq1(n, a):
"""Generalized harmonic number, a <= 1"""
if not np.size(n):
return n
n_max = np.max(n) # loop starts at maximum of all n
out = np.zeros_like(a, dtype=float)
# add terms of harmonic series; starting from smallest to avoid roundoff
for i in np.arange(n_max, 0, -1, dtype=float):
mask = i <= n # don't add terms after nth
out[mask] += 1/i**a[mask]
return out
def _gen_harmonic(n, a):
"""Generalized harmonic number"""
n, a = np.broadcast_arrays(n, a)
return _lazywhere(a > 1, (n, a),
f=_gen_harmonic_gt1, f2=_gen_harmonic_leq1)
class zipfian_gen(rv_discrete):
r"""A Zipfian discrete random variable.
%(before_notes)s
See Also
--------
zipf
Notes
-----
The probability mass function for `zipfian` is:
.. math::
f(k, a, n) = \frac{1}{H_{n,a} k^a}
for :math:`k \in \{1, 2, \dots, n-1, n\}`, :math:`a \ge 0`,
:math:`n \in \{1, 2, 3, \dots\}`.
`zipfian` takes :math:`a` and :math:`n` as shape parameters.
:math:`H_{n,a}` is the :math:`n`:sup:`th` generalized harmonic
number of order :math:`a`.
The Zipfian distribution reduces to the Zipf (zeta) distribution as
:math:`n \rightarrow \infty`.
%(after_notes)s
References
----------
.. [1] "Zipf's Law", Wikipedia, https://en.wikipedia.org/wiki/Zipf's_law
.. [2] Larry Leemis, "Zipf Distribution", Univariate Distribution
Relationships. http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Zipf.pdf
%(example)s
Confirm that `zipfian` reduces to `zipf` for large `n`, `a > 1`.
>>> import numpy as np
>>> from scipy.stats import zipf
>>> k = np.arange(11)
>>> np.allclose(zipfian.pmf(k, a=3.5, n=10000000), zipf.pmf(k, a=3.5))
True
"""
def _shape_info(self):
return [_ShapeInfo("a", False, (0, np.inf), (True, False)),
_ShapeInfo("n", True, (0, np.inf), (False, False))]
def _argcheck(self, a, n):
# we need np.asarray here because moment (maybe others) don't convert
return (a >= 0) & (n > 0) & (n == np.asarray(n, dtype=int))
def _get_support(self, a, n):
return 1, n
def _pmf(self, k, a, n):
return 1.0 / _gen_harmonic(n, a) / k**a
def _cdf(self, k, a, n):
return _gen_harmonic(k, a) / _gen_harmonic(n, a)
def _sf(self, k, a, n):
k = k + 1 # # to match SciPy convention
# see http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Zipf.pdf
return ((k**a*(_gen_harmonic(n, a) - _gen_harmonic(k, a)) + 1)
/ (k**a*_gen_harmonic(n, a)))
def _stats(self, a, n):
# see # see http://www.math.wm.edu/~leemis/chart/UDR/PDFs/Zipf.pdf
Hna = _gen_harmonic(n, a)
Hna1 = _gen_harmonic(n, a-1)
Hna2 = _gen_harmonic(n, a-2)
Hna3 = _gen_harmonic(n, a-3)
Hna4 = _gen_harmonic(n, a-4)
mu1 = Hna1/Hna
mu2n = (Hna2*Hna - Hna1**2)
mu2d = Hna**2
mu2 = mu2n / mu2d
g1 = (Hna3/Hna - 3*Hna1*Hna2/Hna**2 + 2*Hna1**3/Hna**3)/mu2**(3/2)
g2 = (Hna**3*Hna4 - 4*Hna**2*Hna1*Hna3 + 6*Hna*Hna1**2*Hna2
- 3*Hna1**4) / mu2n**2
g2 -= 3
return mu1, mu2, g1, g2
zipfian = zipfian_gen(a=1, name='zipfian', longname='A Zipfian')
class dlaplace_gen(rv_discrete):
r"""A Laplacian discrete random variable.
%(before_notes)s
Notes
-----
The probability mass function for `dlaplace` is:
.. math::
f(k) = \tanh(a/2) \exp(-a |k|)
for integers :math:`k` and :math:`a > 0`.
`dlaplace` takes :math:`a` as shape parameter.
%(after_notes)s
%(example)s
"""
def _shape_info(self):
return [_ShapeInfo("a", False, (0, np.inf), (False, False))]
def _pmf(self, k, a):
# dlaplace.pmf(k) = tanh(a/2) * exp(-a*abs(k))
return tanh(a/2.0) * exp(-a * abs(k))
def _cdf(self, x, a):
k = floor(x)
f = lambda k, a: 1.0 - exp(-a * k) / (exp(a) + 1)
f2 = lambda k, a: exp(a * (k+1)) / (exp(a) + 1)
return _lazywhere(k >= 0, (k, a), f=f, f2=f2)
def _ppf(self, q, a):
const = 1 + exp(a)
vals = ceil(np.where(q < 1.0 / (1 + exp(-a)),
log(q*const) / a - 1,
-log((1-q) * const) / a))
vals1 = vals - 1
return np.where(self._cdf(vals1, a) >= q, vals1, vals)
def _stats(self, a):
ea = exp(a)
mu2 = 2.*ea/(ea-1.)**2
mu4 = 2.*ea*(ea**2+10.*ea+1.) / (ea-1.)**4
return 0., mu2, 0., mu4/mu2**2 - 3.
def _entropy(self, a):
return a / sinh(a) - log(tanh(a/2.0))
def _rvs(self, a, size=None, random_state=None):
# The discrete Laplace is equivalent to the two-sided geometric
# distribution with PMF:
# f(k) = (1 - alpha)/(1 + alpha) * alpha^abs(k)
# Reference:
# https://www.sciencedirect.com/science/
# article/abs/pii/S0378375804003519
# Furthermore, the two-sided geometric distribution is
# equivalent to the difference between two iid geometric
# distributions.
# Reference (page 179):
# https://pdfs.semanticscholar.org/61b3/
# b99f466815808fd0d03f5d2791eea8b541a1.pdf
# Thus, we can leverage the following:
# 1) alpha = e^-a
# 2) probability_of_success = 1 - alpha (Bernoulli trial)
probOfSuccess = -np.expm1(-np.asarray(a))
x = random_state.geometric(probOfSuccess, size=size)
y = random_state.geometric(probOfSuccess, size=size)
return x - y
dlaplace = dlaplace_gen(a=-np.inf,
name='dlaplace', longname='A discrete Laplacian')
class skellam_gen(rv_discrete):
r"""A Skellam discrete random variable.
%(before_notes)s
Notes
-----
Probability distribution of the difference of two correlated or
uncorrelated Poisson random variables.
Let :math:`k_1` and :math:`k_2` be two Poisson-distributed r.v. with
expected values :math:`\lambda_1` and :math:`\lambda_2`. Then,
:math:`k_1 - k_2` follows a Skellam distribution with parameters
:math:`\mu_1 = \lambda_1 - \rho \sqrt{\lambda_1 \lambda_2}` and
:math:`\mu_2 = \lambda_2 - \rho \sqrt{\lambda_1 \lambda_2}`, where
:math:`\rho` is the correlation coefficient between :math:`k_1` and
:math:`k_2`. If the two Poisson-distributed r.v. are independent then
:math:`\rho = 0`.
Parameters :math:`\mu_1` and :math:`\mu_2` must be strictly positive.
For details see: https://en.wikipedia.org/wiki/Skellam_distribution
`skellam` takes :math:`\mu_1` and :math:`\mu_2` as shape parameters.
%(after_notes)s
%(example)s
"""
def _shape_info(self):
return [_ShapeInfo("mu1", False, (0, np.inf), (False, False)),
_ShapeInfo("mu2", False, (0, np.inf), (False, False))]
def _rvs(self, mu1, mu2, size=None, random_state=None):
n = size
return (random_state.poisson(mu1, n) -
random_state.poisson(mu2, n))
def _pmf(self, x, mu1, mu2):
with warnings.catch_warnings():
message = "overflow encountered in _ncx2_pdf"
warnings.filterwarnings("ignore", message=message)
px = np.where(x < 0,
_boost._ncx2_pdf(2*mu2, 2*(1-x), 2*mu1)*2,
_boost._ncx2_pdf(2*mu1, 2*(1+x), 2*mu2)*2)
# ncx2.pdf() returns nan's for extremely low probabilities
return px
def _cdf(self, x, mu1, mu2):
x = floor(x)
px = np.where(x < 0,
_boost._ncx2_cdf(2*mu2, -2*x, 2*mu1),
1 - _boost._ncx2_cdf(2*mu1, 2*(x+1), 2*mu2))
return px
def _stats(self, mu1, mu2):
mean = mu1 - mu2
var = mu1 + mu2
g1 = mean / sqrt((var)**3)
g2 = 1 / var
return mean, var, g1, g2
skellam = skellam_gen(a=-np.inf, name="skellam", longname='A Skellam')
class yulesimon_gen(rv_discrete):
r"""A Yule-Simon discrete random variable.
%(before_notes)s
Notes
-----
The probability mass function for the `yulesimon` is:
.. math::
f(k) = \alpha B(k, \alpha+1)
for :math:`k=1,2,3,...`, where :math:`\alpha>0`.
Here :math:`B` refers to the `scipy.special.beta` function.
The sampling of random variates is based on pg 553, Section 6.3 of [1]_.
Our notation maps to the referenced logic via :math:`\alpha=a-1`.
For details see the wikipedia entry [2]_.
References
----------
.. [1] Devroye, Luc. "Non-uniform Random Variate Generation",
(1986) Springer, New York.
.. [2] https://en.wikipedia.org/wiki/Yule-Simon_distribution
%(after_notes)s
%(example)s
"""
def _shape_info(self):
return [_ShapeInfo("alpha", False, (0, np.inf), (False, False))]
def _rvs(self, alpha, size=None, random_state=None):
E1 = random_state.standard_exponential(size)
E2 = random_state.standard_exponential(size)
ans = ceil(-E1 / log1p(-exp(-E2 / alpha)))
return ans
def _pmf(self, x, alpha):
return alpha * special.beta(x, alpha + 1)
def _argcheck(self, alpha):
return (alpha > 0)
def _logpmf(self, x, alpha):
return log(alpha) + special.betaln(x, alpha + 1)
def _cdf(self, x, alpha):
return 1 - x * special.beta(x, alpha + 1)
def _sf(self, x, alpha):
return x * special.beta(x, alpha + 1)
def _logsf(self, x, alpha):
return log(x) + special.betaln(x, alpha + 1)
def _stats(self, alpha):
mu = np.where(alpha <= 1, np.inf, alpha / (alpha - 1))
mu2 = np.where(alpha > 2,
alpha**2 / ((alpha - 2.0) * (alpha - 1)**2),
np.inf)
mu2 = np.where(alpha <= 1, np.nan, mu2)
g1 = np.where(alpha > 3,
sqrt(alpha - 2) * (alpha + 1)**2 / (alpha * (alpha - 3)),
np.inf)
g1 = np.where(alpha <= 2, np.nan, g1)
g2 = np.where(alpha > 4,
(alpha + 3) + (alpha**3 - 49 * alpha - 22) / (alpha *
(alpha - 4) * (alpha - 3)), np.inf)
g2 = np.where(alpha <= 2, np.nan, g2)
return mu, mu2, g1, g2
yulesimon = yulesimon_gen(name='yulesimon', a=1)
def _vectorize_rvs_over_shapes(_rvs1):
"""Decorator that vectorizes _rvs method to work on ndarray shapes"""
# _rvs1 must be a _function_ that accepts _scalar_ args as positional
# arguments, `size` and `random_state` as keyword arguments.
# _rvs1 must return a random variate array with shape `size`. If `size` is
# None, _rvs1 must return a scalar.
# When applied to _rvs1, this decorator broadcasts ndarray args
# and loops over them, calling _rvs1 for each set of scalar args.
# For usage example, see _nchypergeom_gen
def _rvs(*args, size, random_state):
_rvs1_size, _rvs1_indices = _check_shape(args[0].shape, size)
size = np.array(size)
_rvs1_size = np.array(_rvs1_size)
_rvs1_indices = np.array(_rvs1_indices)
if np.all(_rvs1_indices): # all args are scalars
return _rvs1(*args, size, random_state)
out = np.empty(size)
# out.shape can mix dimensions associated with arg_shape and _rvs1_size
# Sort them to arg_shape + _rvs1_size for easy indexing of dimensions
# corresponding with the different sets of scalar args
j0 = np.arange(out.ndim)
j1 = np.hstack((j0[~_rvs1_indices], j0[_rvs1_indices]))
out = np.moveaxis(out, j1, j0)
for i in np.ndindex(*size[~_rvs1_indices]):
# arg can be squeezed because singleton dimensions will be
# associated with _rvs1_size, not arg_shape per _check_shape
out[i] = _rvs1(*[np.squeeze(arg)[i] for arg in args],
_rvs1_size, random_state)
return np.moveaxis(out, j0, j1) # move axes back before returning
return _rvs
class _nchypergeom_gen(rv_discrete):
r"""A noncentral hypergeometric discrete random variable.
For subclassing by nchypergeom_fisher_gen and nchypergeom_wallenius_gen.
"""
rvs_name = None
dist = None
def _shape_info(self):
return [_ShapeInfo("M", True, (0, np.inf), (True, False)),
_ShapeInfo("n", True, (0, np.inf), (True, False)),
_ShapeInfo("N", True, (0, np.inf), (True, False)),
_ShapeInfo("odds", False, (0, np.inf), (False, False))]
def _get_support(self, M, n, N, odds):
N, m1, n = M, n, N # follow Wikipedia notation
m2 = N - m1
x_min = np.maximum(0, n - m2)
x_max = np.minimum(n, m1)
return x_min, x_max
def _argcheck(self, M, n, N, odds):
M, n = np.asarray(M), np.asarray(n),
N, odds = np.asarray(N), np.asarray(odds)
cond1 = (M.astype(int) == M) & (M >= 0)
cond2 = (n.astype(int) == n) & (n >= 0)
cond3 = (N.astype(int) == N) & (N >= 0)
cond4 = odds > 0
cond5 = N <= M
cond6 = n <= M
return cond1 & cond2 & cond3 & cond4 & cond5 & cond6
def _rvs(self, M, n, N, odds, size=None, random_state=None):
@_vectorize_rvs_over_shapes
def _rvs1(M, n, N, odds, size, random_state):
length = np.prod(size)
urn = _PyStochasticLib3()
rv_gen = getattr(urn, self.rvs_name)
rvs = rv_gen(N, n, M, odds, length, random_state)
rvs = rvs.reshape(size)
return rvs
return _rvs1(M, n, N, odds, size=size, random_state=random_state)
def _pmf(self, x, M, n, N, odds):
x, M, n, N, odds = np.broadcast_arrays(x, M, n, N, odds)
if x.size == 0: # np.vectorize doesn't work with zero size input
return np.empty_like(x)
@np.vectorize
def _pmf1(x, M, n, N, odds):
urn = self.dist(N, n, M, odds, 1e-12)
return urn.probability(x)
return _pmf1(x, M, n, N, odds)
def _stats(self, M, n, N, odds, moments):
@np.vectorize
def _moments1(M, n, N, odds):
urn = self.dist(N, n, M, odds, 1e-12)
return urn.moments()
m, v = (_moments1(M, n, N, odds) if ("m" in moments or "v" in moments)
else (None, None))
s, k = None, None
return m, v, s, k
class nchypergeom_fisher_gen(_nchypergeom_gen):
r"""A Fisher's noncentral hypergeometric discrete random variable.
Fisher's noncentral hypergeometric distribution models drawing objects of
two types from a bin. `M` is the total number of objects, `n` is the
number of Type I objects, and `odds` is the odds ratio: the odds of
selecting a Type I object rather than a Type II object when there is only
one object of each type.
The random variate represents the number of Type I objects drawn if we
take a handful of objects from the bin at once and find out afterwards
that we took `N` objects.
%(before_notes)s
See Also
--------
nchypergeom_wallenius, hypergeom, nhypergeom
Notes
-----
Let mathematical symbols :math:`N`, :math:`n`, and :math:`M` correspond
with parameters `N`, `n`, and `M` (respectively) as defined above.
The probability mass function is defined as
.. math::
p(x; M, n, N, \omega) =
\frac{\binom{n}{x}\binom{M - n}{N-x}\omega^x}{P_0},
for
:math:`x \in [x_l, x_u]`,
:math:`M \in {\mathbb N}`,
:math:`n \in [0, M]`,
:math:`N \in [0, M]`,
:math:`\omega > 0`,
where
:math:`x_l = \max(0, N - (M - n))`,
:math:`x_u = \min(N, n)`,
.. math::
P_0 = \sum_{y=x_l}^{x_u} \binom{n}{y}\binom{M - n}{N-y}\omega^y,
and the binomial coefficients are defined as
.. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}.
`nchypergeom_fisher` uses the BiasedUrn package by Agner Fog with
permission for it to be distributed under SciPy's license.
The symbols used to denote the shape parameters (`N`, `n`, and `M`) are not
universally accepted; they are chosen for consistency with `hypergeom`.
Note that Fisher's noncentral hypergeometric distribution is distinct
from Wallenius' noncentral hypergeometric distribution, which models
drawing a pre-determined `N` objects from a bin one by one.
When the odds ratio is unity, however, both distributions reduce to the
ordinary hypergeometric distribution.
%(after_notes)s
References
----------
.. [1] Agner Fog, "Biased Urn Theory".
https://cran.r-project.org/web/packages/BiasedUrn/vignettes/UrnTheory.pdf
.. [2] "Fisher's noncentral hypergeometric distribution", Wikipedia,
https://en.wikipedia.org/wiki/Fisher's_noncentral_hypergeometric_distribution
%(example)s
"""
rvs_name = "rvs_fisher"
dist = _PyFishersNCHypergeometric
nchypergeom_fisher = nchypergeom_fisher_gen(
name='nchypergeom_fisher',
longname="A Fisher's noncentral hypergeometric")
class nchypergeom_wallenius_gen(_nchypergeom_gen):
r"""A Wallenius' noncentral hypergeometric discrete random variable.
Wallenius' noncentral hypergeometric distribution models drawing objects of
two types from a bin. `M` is the total number of objects, `n` is the
number of Type I objects, and `odds` is the odds ratio: the odds of
selecting a Type I object rather than a Type II object when there is only
one object of each type.
The random variate represents the number of Type I objects drawn if we
draw a pre-determined `N` objects from a bin one by one.
%(before_notes)s
See Also
--------
nchypergeom_fisher, hypergeom, nhypergeom
Notes
-----
Let mathematical symbols :math:`N`, :math:`n`, and :math:`M` correspond
with parameters `N`, `n`, and `M` (respectively) as defined above.
The probability mass function is defined as
.. math::
p(x; N, n, M) = \binom{n}{x} \binom{M - n}{N-x}
\int_0^1 \left(1-t^{\omega/D}\right)^x\left(1-t^{1/D}\right)^{N-x} dt
for
:math:`x \in [x_l, x_u]`,
:math:`M \in {\mathbb N}`,
:math:`n \in [0, M]`,
:math:`N \in [0, M]`,
:math:`\omega > 0`,
where
:math:`x_l = \max(0, N - (M - n))`,
:math:`x_u = \min(N, n)`,
.. math::
D = \omega(n - x) + ((M - n)-(N-x)),
and the binomial coefficients are defined as
.. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}.
`nchypergeom_wallenius` uses the BiasedUrn package by Agner Fog with
permission for it to be distributed under SciPy's license.
The symbols used to denote the shape parameters (`N`, `n`, and `M`) are not
universally accepted; they are chosen for consistency with `hypergeom`.
Note that Wallenius' noncentral hypergeometric distribution is distinct
from Fisher's noncentral hypergeometric distribution, which models
take a handful of objects from the bin at once, finding out afterwards
that `N` objects were taken.
When the odds ratio is unity, however, both distributions reduce to the
ordinary hypergeometric distribution.
%(after_notes)s
References
----------
.. [1] Agner Fog, "Biased Urn Theory".
https://cran.r-project.org/web/packages/BiasedUrn/vignettes/UrnTheory.pdf
.. [2] "Wallenius' noncentral hypergeometric distribution", Wikipedia,
https://en.wikipedia.org/wiki/Wallenius'_noncentral_hypergeometric_distribution
%(example)s
"""
rvs_name = "rvs_wallenius"
dist = _PyWalleniusNCHypergeometric
nchypergeom_wallenius = nchypergeom_wallenius_gen(
name='nchypergeom_wallenius',
longname="A Wallenius' noncentral hypergeometric")
# Collect names of classes and objects in this module.
pairs = list(globals().copy().items())
_distn_names, _distn_gen_names = get_distribution_names(pairs, rv_discrete)
__all__ = _distn_names + _distn_gen_names
| bsd-3-clause | 2527f0991bb8ba6313190da1d7aa25dd | 29.153252 | 90 | 0.548027 | 3.013664 | false | false | false | false |
scipy/scipy | scipy/_lib/_uarray/__init__.py | 11 | 4493 | """
.. note:
If you are looking for overrides for NumPy-specific methods, see the
documentation for :obj:`unumpy`. This page explains how to write
back-ends and multimethods.
``uarray`` is built around a back-end protocol, and overridable multimethods.
It is necessary to define multimethods for back-ends to be able to override them.
See the documentation of :obj:`generate_multimethod` on how to write multimethods.
Let's start with the simplest:
``__ua_domain__`` defines the back-end *domain*. The domain consists of period-
separated string consisting of the modules you extend plus the submodule. For
example, if a submodule ``module2.submodule`` extends ``module1``
(i.e., it exposes dispatchables marked as types available in ``module1``),
then the domain string should be ``"module1.module2.submodule"``.
For the purpose of this demonstration, we'll be creating an object and setting
its attributes directly. However, note that you can use a module or your own type
as a backend as well.
>>> class Backend: pass
>>> be = Backend()
>>> be.__ua_domain__ = "ua_examples"
It might be useful at this point to sidetrack to the documentation of
:obj:`generate_multimethod` to find out how to generate a multimethod
overridable by :obj:`uarray`. Needless to say, writing a backend and
creating multimethods are mostly orthogonal activities, and knowing
one doesn't necessarily require knowledge of the other, although it
is certainly helpful. We expect core API designers/specifiers to write the
multimethods, and implementors to override them. But, as is often the case,
similar people write both.
Without further ado, here's an example multimethod:
>>> import uarray as ua
>>> from uarray import Dispatchable
>>> def override_me(a, b):
... return Dispatchable(a, int),
>>> def override_replacer(args, kwargs, dispatchables):
... return (dispatchables[0], args[1]), {}
>>> overridden_me = ua.generate_multimethod(
... override_me, override_replacer, "ua_examples"
... )
Next comes the part about overriding the multimethod. This requires
the ``__ua_function__`` protocol, and the ``__ua_convert__``
protocol. The ``__ua_function__`` protocol has the signature
``(method, args, kwargs)`` where ``method`` is the passed
multimethod, ``args``/``kwargs`` specify the arguments and ``dispatchables``
is the list of converted dispatchables passed in.
>>> def __ua_function__(method, args, kwargs):
... return method.__name__, args, kwargs
>>> be.__ua_function__ = __ua_function__
The other protocol of interest is the ``__ua_convert__`` protocol. It has the
signature ``(dispatchables, coerce)``. When ``coerce`` is ``False``, conversion
between the formats should ideally be an ``O(1)`` operation, but it means that
no memory copying should be involved, only views of the existing data.
>>> def __ua_convert__(dispatchables, coerce):
... for d in dispatchables:
... if d.type is int:
... if coerce and d.coercible:
... yield str(d.value)
... else:
... yield d.value
>>> be.__ua_convert__ = __ua_convert__
Now that we have defined the backend, the next thing to do is to call the multimethod.
>>> with ua.set_backend(be):
... overridden_me(1, "2")
('override_me', (1, '2'), {})
Note that the marked type has no effect on the actual type of the passed object.
We can also coerce the type of the input.
>>> with ua.set_backend(be, coerce=True):
... overridden_me(1, "2")
... overridden_me(1.0, "2")
('override_me', ('1', '2'), {})
('override_me', ('1.0', '2'), {})
Another feature is that if you remove ``__ua_convert__``, the arguments are not
converted at all and it's up to the backend to handle that.
>>> del be.__ua_convert__
>>> with ua.set_backend(be):
... overridden_me(1, "2")
('override_me', (1, '2'), {})
You also have the option to return ``NotImplemented``, in which case processing moves on
to the next back-end, which in this case, doesn't exist. The same applies to
``__ua_convert__``.
>>> be.__ua_function__ = lambda *a, **kw: NotImplemented
>>> with ua.set_backend(be):
... overridden_me(1, "2")
Traceback (most recent call last):
...
uarray.BackendNotImplementedError: ...
The last possibility is if we don't have ``__ua_convert__``, in which case the job is left
up to ``__ua_function__``, but putting things back into arrays after conversion will not be
possible.
"""
from ._backend import *
__version__ = '0.8.8.dev0+aa94c5a4.scipy'
| bsd-3-clause | ab305dadb14a5002ab5a66be5cd80a8e | 37.732759 | 91 | 0.691743 | 3.611736 | false | false | false | false |
scipy/scipy | scipy/io/_netcdf.py | 1 | 39085 | """
NetCDF reader/writer module.
This module is used to read and create NetCDF files. NetCDF files are
accessed through the `netcdf_file` object. Data written to and from NetCDF
files are contained in `netcdf_variable` objects. Attributes are given
as member variables of the `netcdf_file` and `netcdf_variable` objects.
This module implements the Scientific.IO.NetCDF API to read and create
NetCDF files. The same API is also used in the PyNIO and pynetcdf
modules, allowing these modules to be used interchangeably when working
with NetCDF files.
Only NetCDF3 is supported here; for NetCDF4 see
`netCDF4-python <http://unidata.github.io/netcdf4-python/>`__,
which has a similar API.
"""
# TODO:
# * properly implement ``_FillValue``.
# * fix character variables.
# * implement PAGESIZE for Python 2.6?
# The Scientific.IO.NetCDF API allows attributes to be added directly to
# instances of ``netcdf_file`` and ``netcdf_variable``. To differentiate
# between user-set attributes and instance attributes, user-set attributes
# are automatically stored in the ``_attributes`` attribute by overloading
#``__setattr__``. This is the reason why the code sometimes uses
#``obj.__dict__['key'] = value``, instead of simply ``obj.key = value``;
# otherwise the key would be inserted into userspace attributes.
__all__ = ['netcdf_file', 'netcdf_variable']
import warnings
import weakref
from operator import mul
from platform import python_implementation
import mmap as mm
import numpy as np
from numpy import frombuffer, dtype, empty, array, asarray
from numpy import little_endian as LITTLE_ENDIAN
from functools import reduce
IS_PYPY = python_implementation() == 'PyPy'
ABSENT = b'\x00\x00\x00\x00\x00\x00\x00\x00'
ZERO = b'\x00\x00\x00\x00'
NC_BYTE = b'\x00\x00\x00\x01'
NC_CHAR = b'\x00\x00\x00\x02'
NC_SHORT = b'\x00\x00\x00\x03'
NC_INT = b'\x00\x00\x00\x04'
NC_FLOAT = b'\x00\x00\x00\x05'
NC_DOUBLE = b'\x00\x00\x00\x06'
NC_DIMENSION = b'\x00\x00\x00\n'
NC_VARIABLE = b'\x00\x00\x00\x0b'
NC_ATTRIBUTE = b'\x00\x00\x00\x0c'
FILL_BYTE = b'\x81'
FILL_CHAR = b'\x00'
FILL_SHORT = b'\x80\x01'
FILL_INT = b'\x80\x00\x00\x01'
FILL_FLOAT = b'\x7C\xF0\x00\x00'
FILL_DOUBLE = b'\x47\x9E\x00\x00\x00\x00\x00\x00'
TYPEMAP = {NC_BYTE: ('b', 1),
NC_CHAR: ('c', 1),
NC_SHORT: ('h', 2),
NC_INT: ('i', 4),
NC_FLOAT: ('f', 4),
NC_DOUBLE: ('d', 8)}
FILLMAP = {NC_BYTE: FILL_BYTE,
NC_CHAR: FILL_CHAR,
NC_SHORT: FILL_SHORT,
NC_INT: FILL_INT,
NC_FLOAT: FILL_FLOAT,
NC_DOUBLE: FILL_DOUBLE}
REVERSE = {('b', 1): NC_BYTE,
('B', 1): NC_CHAR,
('c', 1): NC_CHAR,
('h', 2): NC_SHORT,
('i', 4): NC_INT,
('f', 4): NC_FLOAT,
('d', 8): NC_DOUBLE,
# these come from asarray(1).dtype.char and asarray('foo').dtype.char,
# used when getting the types from generic attributes.
('l', 4): NC_INT,
('S', 1): NC_CHAR}
class netcdf_file:
"""
A file object for NetCDF data.
A `netcdf_file` object has two standard attributes: `dimensions` and
`variables`. The values of both are dictionaries, mapping dimension
names to their associated lengths and variable names to variables,
respectively. Application programs should never modify these
dictionaries.
All other attributes correspond to global attributes defined in the
NetCDF file. Global file attributes are created by assigning to an
attribute of the `netcdf_file` object.
Parameters
----------
filename : string or file-like
string -> filename
mode : {'r', 'w', 'a'}, optional
read-write-append mode, default is 'r'
mmap : None or bool, optional
Whether to mmap `filename` when reading. Default is True
when `filename` is a file name, False when `filename` is a
file-like object. Note that when mmap is in use, data arrays
returned refer directly to the mmapped data on disk, and the
file cannot be closed as long as references to it exist.
version : {1, 2}, optional
version of netcdf to read / write, where 1 means *Classic
format* and 2 means *64-bit offset format*. Default is 1. See
`here <https://www.unidata.ucar.edu/software/netcdf/docs/netcdf_introduction.html#select_format>`__
for more info.
maskandscale : bool, optional
Whether to automatically scale and/or mask data based on attributes.
Default is False.
Notes
-----
The major advantage of this module over other modules is that it doesn't
require the code to be linked to the NetCDF libraries. This module is
derived from `pupynere <https://bitbucket.org/robertodealmeida/pupynere/>`_.
NetCDF files are a self-describing binary data format. The file contains
metadata that describes the dimensions and variables in the file. More
details about NetCDF files can be found `here
<https://www.unidata.ucar.edu/software/netcdf/guide_toc.html>`__. There
are three main sections to a NetCDF data structure:
1. Dimensions
2. Variables
3. Attributes
The dimensions section records the name and length of each dimension used
by the variables. The variables would then indicate which dimensions it
uses and any attributes such as data units, along with containing the data
values for the variable. It is good practice to include a
variable that is the same name as a dimension to provide the values for
that axes. Lastly, the attributes section would contain additional
information such as the name of the file creator or the instrument used to
collect the data.
When writing data to a NetCDF file, there is often the need to indicate the
'record dimension'. A record dimension is the unbounded dimension for a
variable. For example, a temperature variable may have dimensions of
latitude, longitude and time. If one wants to add more temperature data to
the NetCDF file as time progresses, then the temperature variable should
have the time dimension flagged as the record dimension.
In addition, the NetCDF file header contains the position of the data in
the file, so access can be done in an efficient manner without loading
unnecessary data into memory. It uses the ``mmap`` module to create
Numpy arrays mapped to the data on disk, for the same purpose.
Note that when `netcdf_file` is used to open a file with mmap=True
(default for read-only), arrays returned by it refer to data
directly on the disk. The file should not be closed, and cannot be cleanly
closed when asked, if such arrays are alive. You may want to copy data arrays
obtained from mmapped Netcdf file if they are to be processed after the file
is closed, see the example below.
Examples
--------
To create a NetCDF file:
>>> from scipy.io import netcdf_file
>>> import numpy as np
>>> f = netcdf_file('simple.nc', 'w')
>>> f.history = 'Created for a test'
>>> f.createDimension('time', 10)
>>> time = f.createVariable('time', 'i', ('time',))
>>> time[:] = np.arange(10)
>>> time.units = 'days since 2008-01-01'
>>> f.close()
Note the assignment of ``arange(10)`` to ``time[:]``. Exposing the slice
of the time variable allows for the data to be set in the object, rather
than letting ``arange(10)`` overwrite the ``time`` variable.
To read the NetCDF file we just created:
>>> from scipy.io import netcdf_file
>>> f = netcdf_file('simple.nc', 'r')
>>> print(f.history)
b'Created for a test'
>>> time = f.variables['time']
>>> print(time.units)
b'days since 2008-01-01'
>>> print(time.shape)
(10,)
>>> print(time[-1])
9
NetCDF files, when opened read-only, return arrays that refer
directly to memory-mapped data on disk:
>>> data = time[:]
If the data is to be processed after the file is closed, it needs
to be copied to main memory:
>>> data = time[:].copy()
>>> f.close()
>>> data.mean()
4.5
A NetCDF file can also be used as context manager:
>>> from scipy.io import netcdf_file
>>> with netcdf_file('simple.nc', 'r') as f:
... print(f.history)
b'Created for a test'
"""
def __init__(self, filename, mode='r', mmap=None, version=1,
maskandscale=False):
"""Initialize netcdf_file from fileobj (str or file-like)."""
if mode not in 'rwa':
raise ValueError("Mode must be either 'r', 'w' or 'a'.")
if hasattr(filename, 'seek'): # file-like
self.fp = filename
self.filename = 'None'
if mmap is None:
mmap = False
elif mmap and not hasattr(filename, 'fileno'):
raise ValueError('Cannot use file object for mmap')
else: # maybe it's a string
self.filename = filename
omode = 'r+' if mode == 'a' else mode
self.fp = open(self.filename, '%sb' % omode)
if mmap is None:
# Mmapped files on PyPy cannot be usually closed
# before the GC runs, so it's better to use mmap=False
# as the default.
mmap = (not IS_PYPY)
if mode != 'r':
# Cannot read write-only files
mmap = False
self.use_mmap = mmap
self.mode = mode
self.version_byte = version
self.maskandscale = maskandscale
self.dimensions = {}
self.variables = {}
self._dims = []
self._recs = 0
self._recsize = 0
self._mm = None
self._mm_buf = None
if self.use_mmap:
self._mm = mm.mmap(self.fp.fileno(), 0, access=mm.ACCESS_READ)
self._mm_buf = np.frombuffer(self._mm, dtype=np.int8)
self._attributes = {}
if mode in 'ra':
self._read()
def __setattr__(self, attr, value):
# Store user defined attributes in a separate dict,
# so we can save them to file later.
try:
self._attributes[attr] = value
except AttributeError:
pass
self.__dict__[attr] = value
def close(self):
"""Closes the NetCDF file."""
if hasattr(self, 'fp') and not self.fp.closed:
try:
self.flush()
finally:
self.variables = {}
if self._mm_buf is not None:
ref = weakref.ref(self._mm_buf)
self._mm_buf = None
if ref() is None:
# self._mm_buf is gc'd, and we can close the mmap
self._mm.close()
else:
# we cannot close self._mm, since self._mm_buf is
# alive and there may still be arrays referring to it
warnings.warn((
"Cannot close a netcdf_file opened with mmap=True, when "
"netcdf_variables or arrays referring to its data still exist. "
"All data arrays obtained from such files refer directly to "
"data on disk, and must be copied before the file can be cleanly "
"closed. (See netcdf_file docstring for more information on mmap.)"
), category=RuntimeWarning)
self._mm = None
self.fp.close()
__del__ = close
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def createDimension(self, name, length):
"""
Adds a dimension to the Dimension section of the NetCDF data structure.
Note that this function merely adds a new dimension that the variables can
reference. The values for the dimension, if desired, should be added as
a variable using `createVariable`, referring to this dimension.
Parameters
----------
name : str
Name of the dimension (Eg, 'lat' or 'time').
length : int
Length of the dimension.
See Also
--------
createVariable
"""
if length is None and self._dims:
raise ValueError("Only first dimension may be unlimited!")
self.dimensions[name] = length
self._dims.append(name)
def createVariable(self, name, type, dimensions):
"""
Create an empty variable for the `netcdf_file` object, specifying its data
type and the dimensions it uses.
Parameters
----------
name : str
Name of the new variable.
type : dtype or str
Data type of the variable.
dimensions : sequence of str
List of the dimension names used by the variable, in the desired order.
Returns
-------
variable : netcdf_variable
The newly created ``netcdf_variable`` object.
This object has also been added to the `netcdf_file` object as well.
See Also
--------
createDimension
Notes
-----
Any dimensions to be used by the variable should already exist in the
NetCDF data structure or should be created by `createDimension` prior to
creating the NetCDF variable.
"""
shape = tuple([self.dimensions[dim] for dim in dimensions])
shape_ = tuple([dim or 0 for dim in shape]) # replace None with 0 for NumPy
type = dtype(type)
typecode, size = type.char, type.itemsize
if (typecode, size) not in REVERSE:
raise ValueError("NetCDF 3 does not support type %s" % type)
data = empty(shape_, dtype=type.newbyteorder("B")) # convert to big endian always for NetCDF 3
self.variables[name] = netcdf_variable(
data, typecode, size, shape, dimensions,
maskandscale=self.maskandscale)
return self.variables[name]
def flush(self):
"""
Perform a sync-to-disk flush if the `netcdf_file` object is in write mode.
See Also
--------
sync : Identical function
"""
if hasattr(self, 'mode') and self.mode in 'wa':
self._write()
sync = flush
def _write(self):
self.fp.seek(0)
self.fp.write(b'CDF')
self.fp.write(array(self.version_byte, '>b').tobytes())
# Write headers and data.
self._write_numrecs()
self._write_dim_array()
self._write_gatt_array()
self._write_var_array()
def _write_numrecs(self):
# Get highest record count from all record variables.
for var in self.variables.values():
if var.isrec and len(var.data) > self._recs:
self.__dict__['_recs'] = len(var.data)
self._pack_int(self._recs)
def _write_dim_array(self):
if self.dimensions:
self.fp.write(NC_DIMENSION)
self._pack_int(len(self.dimensions))
for name in self._dims:
self._pack_string(name)
length = self.dimensions[name]
self._pack_int(length or 0) # replace None with 0 for record dimension
else:
self.fp.write(ABSENT)
def _write_gatt_array(self):
self._write_att_array(self._attributes)
def _write_att_array(self, attributes):
if attributes:
self.fp.write(NC_ATTRIBUTE)
self._pack_int(len(attributes))
for name, values in attributes.items():
self._pack_string(name)
self._write_att_values(values)
else:
self.fp.write(ABSENT)
def _write_var_array(self):
if self.variables:
self.fp.write(NC_VARIABLE)
self._pack_int(len(self.variables))
# Sort variable names non-recs first, then recs.
def sortkey(n):
v = self.variables[n]
if v.isrec:
return (-1,)
return v._shape
variables = sorted(self.variables, key=sortkey, reverse=True)
# Set the metadata for all variables.
for name in variables:
self._write_var_metadata(name)
# Now that we have the metadata, we know the vsize of
# each record variable, so we can calculate recsize.
self.__dict__['_recsize'] = sum([
var._vsize for var in self.variables.values()
if var.isrec])
# Set the data for all variables.
for name in variables:
self._write_var_data(name)
else:
self.fp.write(ABSENT)
def _write_var_metadata(self, name):
var = self.variables[name]
self._pack_string(name)
self._pack_int(len(var.dimensions))
for dimname in var.dimensions:
dimid = self._dims.index(dimname)
self._pack_int(dimid)
self._write_att_array(var._attributes)
nc_type = REVERSE[var.typecode(), var.itemsize()]
self.fp.write(nc_type)
if not var.isrec:
vsize = var.data.size * var.data.itemsize
vsize += -vsize % 4
else: # record variable
try:
vsize = var.data[0].size * var.data.itemsize
except IndexError:
vsize = 0
rec_vars = len([v for v in self.variables.values()
if v.isrec])
if rec_vars > 1:
vsize += -vsize % 4
self.variables[name].__dict__['_vsize'] = vsize
self._pack_int(vsize)
# Pack a bogus begin, and set the real value later.
self.variables[name].__dict__['_begin'] = self.fp.tell()
self._pack_begin(0)
def _write_var_data(self, name):
var = self.variables[name]
# Set begin in file header.
the_beguine = self.fp.tell()
self.fp.seek(var._begin)
self._pack_begin(the_beguine)
self.fp.seek(the_beguine)
# Write data.
if not var.isrec:
self.fp.write(var.data.tobytes())
count = var.data.size * var.data.itemsize
self._write_var_padding(var, var._vsize - count)
else: # record variable
# Handle rec vars with shape[0] < nrecs.
if self._recs > len(var.data):
shape = (self._recs,) + var.data.shape[1:]
# Resize in-place does not always work since
# the array might not be single-segment
try:
var.data.resize(shape)
except ValueError:
var.__dict__['data'] = np.resize(var.data, shape).astype(var.data.dtype)
pos0 = pos = self.fp.tell()
for rec in var.data:
# Apparently scalars cannot be converted to big endian. If we
# try to convert a ``=i4`` scalar to, say, '>i4' the dtype
# will remain as ``=i4``.
if not rec.shape and (rec.dtype.byteorder == '<' or
(rec.dtype.byteorder == '=' and LITTLE_ENDIAN)):
rec = rec.byteswap()
self.fp.write(rec.tobytes())
# Padding
count = rec.size * rec.itemsize
self._write_var_padding(var, var._vsize - count)
pos += self._recsize
self.fp.seek(pos)
self.fp.seek(pos0 + var._vsize)
def _write_var_padding(self, var, size):
encoded_fill_value = var._get_encoded_fill_value()
num_fills = size // len(encoded_fill_value)
self.fp.write(encoded_fill_value * num_fills)
def _write_att_values(self, values):
if hasattr(values, 'dtype'):
nc_type = REVERSE[values.dtype.char, values.dtype.itemsize]
else:
types = [(int, NC_INT), (float, NC_FLOAT), (str, NC_CHAR)]
# bytes index into scalars in py3k. Check for "string" types
if isinstance(values, (str, bytes)):
sample = values
else:
try:
sample = values[0] # subscriptable?
except TypeError:
sample = values # scalar
for class_, nc_type in types:
if isinstance(sample, class_):
break
typecode, size = TYPEMAP[nc_type]
dtype_ = '>%s' % typecode
# asarray() dies with bytes and '>c' in py3k. Change to 'S'
dtype_ = 'S' if dtype_ == '>c' else dtype_
values = asarray(values, dtype=dtype_)
self.fp.write(nc_type)
if values.dtype.char == 'S':
nelems = values.itemsize
else:
nelems = values.size
self._pack_int(nelems)
if not values.shape and (values.dtype.byteorder == '<' or
(values.dtype.byteorder == '=' and LITTLE_ENDIAN)):
values = values.byteswap()
self.fp.write(values.tobytes())
count = values.size * values.itemsize
self.fp.write(b'\x00' * (-count % 4)) # pad
def _read(self):
# Check magic bytes and version
magic = self.fp.read(3)
if not magic == b'CDF':
raise TypeError("Error: %s is not a valid NetCDF 3 file" %
self.filename)
self.__dict__['version_byte'] = frombuffer(self.fp.read(1), '>b')[0]
# Read file headers and set data.
self._read_numrecs()
self._read_dim_array()
self._read_gatt_array()
self._read_var_array()
def _read_numrecs(self):
self.__dict__['_recs'] = self._unpack_int()
def _read_dim_array(self):
header = self.fp.read(4)
if header not in [ZERO, NC_DIMENSION]:
raise ValueError("Unexpected header.")
count = self._unpack_int()
for dim in range(count):
name = self._unpack_string().decode('latin1')
length = self._unpack_int() or None # None for record dimension
self.dimensions[name] = length
self._dims.append(name) # preserve order
def _read_gatt_array(self):
for k, v in self._read_att_array().items():
self.__setattr__(k, v)
def _read_att_array(self):
header = self.fp.read(4)
if header not in [ZERO, NC_ATTRIBUTE]:
raise ValueError("Unexpected header.")
count = self._unpack_int()
attributes = {}
for attr in range(count):
name = self._unpack_string().decode('latin1')
attributes[name] = self._read_att_values()
return attributes
def _read_var_array(self):
header = self.fp.read(4)
if header not in [ZERO, NC_VARIABLE]:
raise ValueError("Unexpected header.")
begin = 0
dtypes = {'names': [], 'formats': []}
rec_vars = []
count = self._unpack_int()
for var in range(count):
(name, dimensions, shape, attributes,
typecode, size, dtype_, begin_, vsize) = self._read_var()
# https://www.unidata.ucar.edu/software/netcdf/guide_toc.html
# Note that vsize is the product of the dimension lengths
# (omitting the record dimension) and the number of bytes
# per value (determined from the type), increased to the
# next multiple of 4, for each variable. If a record
# variable, this is the amount of space per record. The
# netCDF "record size" is calculated as the sum of the
# vsize's of all the record variables.
#
# The vsize field is actually redundant, because its value
# may be computed from other information in the header. The
# 32-bit vsize field is not large enough to contain the size
# of variables that require more than 2^32 - 4 bytes, so
# 2^32 - 1 is used in the vsize field for such variables.
if shape and shape[0] is None: # record variable
rec_vars.append(name)
# The netCDF "record size" is calculated as the sum of
# the vsize's of all the record variables.
self.__dict__['_recsize'] += vsize
if begin == 0:
begin = begin_
dtypes['names'].append(name)
dtypes['formats'].append(str(shape[1:]) + dtype_)
# Handle padding with a virtual variable.
if typecode in 'bch':
actual_size = reduce(mul, (1,) + shape[1:]) * size
padding = -actual_size % 4
if padding:
dtypes['names'].append('_padding_%d' % var)
dtypes['formats'].append('(%d,)>b' % padding)
# Data will be set later.
data = None
else: # not a record variable
# Calculate size to avoid problems with vsize (above)
a_size = reduce(mul, shape, 1) * size
if self.use_mmap:
data = self._mm_buf[begin_:begin_+a_size].view(dtype=dtype_)
data.shape = shape
else:
pos = self.fp.tell()
self.fp.seek(begin_)
data = frombuffer(self.fp.read(a_size), dtype=dtype_
).copy()
data.shape = shape
self.fp.seek(pos)
# Add variable.
self.variables[name] = netcdf_variable(
data, typecode, size, shape, dimensions, attributes,
maskandscale=self.maskandscale)
if rec_vars:
# Remove padding when only one record variable.
if len(rec_vars) == 1:
dtypes['names'] = dtypes['names'][:1]
dtypes['formats'] = dtypes['formats'][:1]
# Build rec array.
if self.use_mmap:
rec_array = self._mm_buf[begin:begin+self._recs*self._recsize].view(dtype=dtypes)
rec_array.shape = (self._recs,)
else:
pos = self.fp.tell()
self.fp.seek(begin)
rec_array = frombuffer(self.fp.read(self._recs*self._recsize),
dtype=dtypes).copy()
rec_array.shape = (self._recs,)
self.fp.seek(pos)
for var in rec_vars:
self.variables[var].__dict__['data'] = rec_array[var]
def _read_var(self):
name = self._unpack_string().decode('latin1')
dimensions = []
shape = []
dims = self._unpack_int()
for i in range(dims):
dimid = self._unpack_int()
dimname = self._dims[dimid]
dimensions.append(dimname)
dim = self.dimensions[dimname]
shape.append(dim)
dimensions = tuple(dimensions)
shape = tuple(shape)
attributes = self._read_att_array()
nc_type = self.fp.read(4)
vsize = self._unpack_int()
begin = [self._unpack_int, self._unpack_int64][self.version_byte-1]()
typecode, size = TYPEMAP[nc_type]
dtype_ = '>%s' % typecode
return name, dimensions, shape, attributes, typecode, size, dtype_, begin, vsize
def _read_att_values(self):
nc_type = self.fp.read(4)
n = self._unpack_int()
typecode, size = TYPEMAP[nc_type]
count = n*size
values = self.fp.read(int(count))
self.fp.read(-count % 4) # read padding
if typecode != 'c':
values = frombuffer(values, dtype='>%s' % typecode).copy()
if values.shape == (1,):
values = values[0]
else:
values = values.rstrip(b'\x00')
return values
def _pack_begin(self, begin):
if self.version_byte == 1:
self._pack_int(begin)
elif self.version_byte == 2:
self._pack_int64(begin)
def _pack_int(self, value):
self.fp.write(array(value, '>i').tobytes())
_pack_int32 = _pack_int
def _unpack_int(self):
return int(frombuffer(self.fp.read(4), '>i')[0])
_unpack_int32 = _unpack_int
def _pack_int64(self, value):
self.fp.write(array(value, '>q').tobytes())
def _unpack_int64(self):
return frombuffer(self.fp.read(8), '>q')[0]
def _pack_string(self, s):
count = len(s)
self._pack_int(count)
self.fp.write(s.encode('latin1'))
self.fp.write(b'\x00' * (-count % 4)) # pad
def _unpack_string(self):
count = self._unpack_int()
s = self.fp.read(count).rstrip(b'\x00')
self.fp.read(-count % 4) # read padding
return s
class netcdf_variable:
"""
A data object for netcdf files.
`netcdf_variable` objects are constructed by calling the method
`netcdf_file.createVariable` on the `netcdf_file` object. `netcdf_variable`
objects behave much like array objects defined in numpy, except that their
data resides in a file. Data is read by indexing and written by assigning
to an indexed subset; the entire array can be accessed by the index ``[:]``
or (for scalars) by using the methods `getValue` and `assignValue`.
`netcdf_variable` objects also have attribute `shape` with the same meaning
as for arrays, but the shape cannot be modified. There is another read-only
attribute `dimensions`, whose value is the tuple of dimension names.
All other attributes correspond to variable attributes defined in
the NetCDF file. Variable attributes are created by assigning to an
attribute of the `netcdf_variable` object.
Parameters
----------
data : array_like
The data array that holds the values for the variable.
Typically, this is initialized as empty, but with the proper shape.
typecode : dtype character code
Desired data-type for the data array.
size : int
Desired element size for the data array.
shape : sequence of ints
The shape of the array. This should match the lengths of the
variable's dimensions.
dimensions : sequence of strings
The names of the dimensions used by the variable. Must be in the
same order of the dimension lengths given by `shape`.
attributes : dict, optional
Attribute values (any type) keyed by string names. These attributes
become attributes for the netcdf_variable object.
maskandscale : bool, optional
Whether to automatically scale and/or mask data based on attributes.
Default is False.
Attributes
----------
dimensions : list of str
List of names of dimensions used by the variable object.
isrec, shape
Properties
See also
--------
isrec, shape
"""
def __init__(self, data, typecode, size, shape, dimensions,
attributes=None,
maskandscale=False):
self.data = data
self._typecode = typecode
self._size = size
self._shape = shape
self.dimensions = dimensions
self.maskandscale = maskandscale
self._attributes = attributes or {}
for k, v in self._attributes.items():
self.__dict__[k] = v
def __setattr__(self, attr, value):
# Store user defined attributes in a separate dict,
# so we can save them to file later.
try:
self._attributes[attr] = value
except AttributeError:
pass
self.__dict__[attr] = value
def isrec(self):
"""Returns whether the variable has a record dimension or not.
A record dimension is a dimension along which additional data could be
easily appended in the netcdf data structure without much rewriting of
the data file. This attribute is a read-only property of the
`netcdf_variable`.
"""
return bool(self.data.shape) and not self._shape[0]
isrec = property(isrec)
def shape(self):
"""Returns the shape tuple of the data variable.
This is a read-only attribute and can not be modified in the
same manner of other numpy arrays.
"""
return self.data.shape
shape = property(shape)
def getValue(self):
"""
Retrieve a scalar value from a `netcdf_variable` of length one.
Raises
------
ValueError
If the netcdf variable is an array of length greater than one,
this exception will be raised.
"""
return self.data.item()
def assignValue(self, value):
"""
Assign a scalar value to a `netcdf_variable` of length one.
Parameters
----------
value : scalar
Scalar value (of compatible type) to assign to a length-one netcdf
variable. This value will be written to file.
Raises
------
ValueError
If the input is not a scalar, or if the destination is not a length-one
netcdf variable.
"""
if not self.data.flags.writeable:
# Work-around for a bug in NumPy. Calling itemset() on a read-only
# memory-mapped array causes a seg. fault.
# See NumPy ticket #1622, and SciPy ticket #1202.
# This check for `writeable` can be removed when the oldest version
# of NumPy still supported by scipy contains the fix for #1622.
raise RuntimeError("variable is not writeable")
self.data.itemset(value)
def typecode(self):
"""
Return the typecode of the variable.
Returns
-------
typecode : char
The character typecode of the variable (e.g., 'i' for int).
"""
return self._typecode
def itemsize(self):
"""
Return the itemsize of the variable.
Returns
-------
itemsize : int
The element size of the variable (e.g., 8 for float64).
"""
return self._size
def __getitem__(self, index):
if not self.maskandscale:
return self.data[index]
data = self.data[index].copy()
missing_value = self._get_missing_value()
data = self._apply_missing_value(data, missing_value)
scale_factor = self._attributes.get('scale_factor')
add_offset = self._attributes.get('add_offset')
if add_offset is not None or scale_factor is not None:
data = data.astype(np.float64)
if scale_factor is not None:
data = data * scale_factor
if add_offset is not None:
data += add_offset
return data
def __setitem__(self, index, data):
if self.maskandscale:
missing_value = (
self._get_missing_value() or
getattr(data, 'fill_value', 999999))
self._attributes.setdefault('missing_value', missing_value)
self._attributes.setdefault('_FillValue', missing_value)
data = ((data - self._attributes.get('add_offset', 0.0)) /
self._attributes.get('scale_factor', 1.0))
data = np.ma.asarray(data).filled(missing_value)
if self._typecode not in 'fd' and data.dtype.kind == 'f':
data = np.round(data)
# Expand data for record vars?
if self.isrec:
if isinstance(index, tuple):
rec_index = index[0]
else:
rec_index = index
if isinstance(rec_index, slice):
recs = (rec_index.start or 0) + len(data)
else:
recs = rec_index + 1
if recs > len(self.data):
shape = (recs,) + self._shape[1:]
# Resize in-place does not always work since
# the array might not be single-segment
try:
self.data.resize(shape)
except ValueError:
self.__dict__['data'] = np.resize(self.data, shape).astype(self.data.dtype)
self.data[index] = data
def _default_encoded_fill_value(self):
"""
The default encoded fill-value for this Variable's data type.
"""
nc_type = REVERSE[self.typecode(), self.itemsize()]
return FILLMAP[nc_type]
def _get_encoded_fill_value(self):
"""
Returns the encoded fill value for this variable as bytes.
This is taken from either the _FillValue attribute, or the default fill
value for this variable's data type.
"""
if '_FillValue' in self._attributes:
fill_value = np.array(self._attributes['_FillValue'],
dtype=self.data.dtype).tobytes()
if len(fill_value) == self.itemsize():
return fill_value
else:
return self._default_encoded_fill_value()
else:
return self._default_encoded_fill_value()
def _get_missing_value(self):
"""
Returns the value denoting "no data" for this variable.
If this variable does not have a missing/fill value, returns None.
If both _FillValue and missing_value are given, give precedence to
_FillValue. The netCDF standard gives special meaning to _FillValue;
missing_value is just used for compatibility with old datasets.
"""
if '_FillValue' in self._attributes:
missing_value = self._attributes['_FillValue']
elif 'missing_value' in self._attributes:
missing_value = self._attributes['missing_value']
else:
missing_value = None
return missing_value
@staticmethod
def _apply_missing_value(data, missing_value):
"""
Applies the given missing value to the data array.
Returns a numpy.ma array, with any value equal to missing_value masked
out (unless missing_value is None, in which case the original array is
returned).
"""
if missing_value is None:
newdata = data
else:
try:
missing_value_isnan = np.isnan(missing_value)
except (TypeError, NotImplementedError):
# some data types (e.g., characters) cannot be tested for NaN
missing_value_isnan = False
if missing_value_isnan:
mymask = np.isnan(data)
else:
mymask = (data == missing_value)
newdata = np.ma.masked_where(mymask, data)
return newdata
NetCDFFile = netcdf_file
NetCDFVariable = netcdf_variable
| bsd-3-clause | c6476d4a2bbdc0fa7517fc5f5ca2ffc3 | 34.923713 | 107 | 0.570577 | 4.117678 | false | false | false | false |
scipy/scipy | scipy/integrate/tests/test_odeint_jac.py | 29 | 1820 |
import numpy as np
from numpy.testing import assert_equal, assert_allclose
from scipy.integrate import odeint
import scipy.integrate._test_odeint_banded as banded5x5
def rhs(y, t):
dydt = np.zeros_like(y)
banded5x5.banded5x5(t, y, dydt)
return dydt
def jac(y, t):
n = len(y)
jac = np.zeros((n, n), order='F')
banded5x5.banded5x5_jac(t, y, 1, 1, jac)
return jac
def bjac(y, t):
n = len(y)
bjac = np.zeros((4, n), order='F')
banded5x5.banded5x5_bjac(t, y, 1, 1, bjac)
return bjac
JACTYPE_FULL = 1
JACTYPE_BANDED = 4
def check_odeint(jactype):
if jactype == JACTYPE_FULL:
ml = None
mu = None
jacobian = jac
elif jactype == JACTYPE_BANDED:
ml = 2
mu = 1
jacobian = bjac
else:
raise ValueError("invalid jactype: %r" % (jactype,))
y0 = np.arange(1.0, 6.0)
# These tolerances must match the tolerances used in banded5x5.f.
rtol = 1e-11
atol = 1e-13
dt = 0.125
nsteps = 64
t = dt * np.arange(nsteps+1)
sol, info = odeint(rhs, y0, t,
Dfun=jacobian, ml=ml, mu=mu,
atol=atol, rtol=rtol, full_output=True)
yfinal = sol[-1]
odeint_nst = info['nst'][-1]
odeint_nfe = info['nfe'][-1]
odeint_nje = info['nje'][-1]
y1 = y0.copy()
# Pure Fortran solution. y1 is modified in-place.
nst, nfe, nje = banded5x5.banded5x5_solve(y1, nsteps, dt, jactype)
# It is likely that yfinal and y1 are *exactly* the same, but
# we'll be cautious and use assert_allclose.
assert_allclose(yfinal, y1, rtol=1e-12)
assert_equal((odeint_nst, odeint_nfe, odeint_nje), (nst, nfe, nje))
def test_odeint_full_jac():
check_odeint(JACTYPE_FULL)
def test_odeint_banded_jac():
check_odeint(JACTYPE_BANDED)
| bsd-3-clause | a0ca9b4d822b11b49be475c1a69630fa | 23.266667 | 71 | 0.601648 | 2.633864 | false | true | false | false |
statsmodels/statsmodels | statsmodels/tsa/arima/model.py | 3 | 25337 | """
ARIMA model class.
Author: Chad Fulton
License: BSD-3
"""
from statsmodels.compat.pandas import Appender
import warnings
import numpy as np
from statsmodels.tools.data import _is_using_pandas
from statsmodels.tsa.statespace import sarimax
from statsmodels.tsa.statespace.kalman_filter import MEMORY_CONSERVE
from statsmodels.tsa.statespace.tools import diff
import statsmodels.base.wrapper as wrap
from statsmodels.tsa.arima.estimators.yule_walker import yule_walker
from statsmodels.tsa.arima.estimators.burg import burg
from statsmodels.tsa.arima.estimators.hannan_rissanen import hannan_rissanen
from statsmodels.tsa.arima.estimators.innovations import (
innovations, innovations_mle)
from statsmodels.tsa.arima.estimators.gls import gls as estimate_gls
from statsmodels.tsa.arima.specification import SARIMAXSpecification
class ARIMA(sarimax.SARIMAX):
r"""
Autoregressive Integrated Moving Average (ARIMA) model, and extensions
This model is the basic interface for ARIMA-type models, including those
with exogenous regressors and those with seasonal components. The most
general form of the model is SARIMAX(p, d, q)x(P, D, Q, s). It also allows
all specialized cases, including
- autoregressive models: AR(p)
- moving average models: MA(q)
- mixed autoregressive moving average models: ARMA(p, q)
- integration models: ARIMA(p, d, q)
- seasonal models: SARIMA(P, D, Q, s)
- regression with errors that follow one of the above ARIMA-type models
Parameters
----------
endog : array_like, optional
The observed time-series process :math:`y`.
exog : array_like, optional
Array of exogenous regressors.
order : tuple, optional
The (p,d,q) order of the model for the autoregressive, differences, and
moving average components. d is always an integer, while p and q may
either be integers or lists of integers.
seasonal_order : tuple, optional
The (P,D,Q,s) order of the seasonal component of the model for the
AR parameters, differences, MA parameters, and periodicity. Default
is (0, 0, 0, 0). D and s are always integers, while P and Q
may either be integers or lists of positive integers.
trend : str{'n','c','t','ct'} or iterable, optional
Parameter controlling the deterministic trend. Can be specified as a
string where 'c' indicates a constant term, 't' indicates a
linear trend in time, and 'ct' includes both. Can also be specified as
an iterable defining a polynomial, as in `numpy.poly1d`, where
`[1,1,0,1]` would denote :math:`a + bt + ct^3`. Default is 'c' for
models without integration, and no trend for models with integration.
Note that all trend terms are included in the model as exogenous
regressors, which differs from how trends are included in ``SARIMAX``
models. See the Notes section for a precise definition of the
treatment of trend terms.
enforce_stationarity : bool, optional
Whether or not to require the autoregressive parameters to correspond
to a stationarity process.
enforce_invertibility : bool, optional
Whether or not to require the moving average parameters to correspond
to an invertible process.
concentrate_scale : bool, optional
Whether or not to concentrate the scale (variance of the error term)
out of the likelihood. This reduces the number of parameters by one.
This is only applicable when considering estimation by numerical
maximum likelihood.
trend_offset : int, optional
The offset at which to start time trend values. Default is 1, so that
if `trend='t'` the trend is equal to 1, 2, ..., nobs. Typically is only
set when the model created by extending a previous dataset.
dates : array_like of datetime, optional
If no index is given by `endog` or `exog`, an array-like object of
datetime objects can be provided.
freq : str, optional
If no index is given by `endog` or `exog`, the frequency of the
time-series may be specified here as a Pandas offset or offset string.
missing : str
Available options are 'none', 'drop', and 'raise'. If 'none', no nan
checking is done. If 'drop', any observations with nans are dropped.
If 'raise', an error is raised. Default is 'none'.
Notes
-----
This model incorporates both exogenous regressors and trend components
through "regression with ARIMA errors". This differs from the
specification estimated using ``SARIMAX`` which treats the trend
components separately from any included exogenous regressors. The full
specification of the model estimated here is:
.. math::
Y_{t}-\delta_{0}-\delta_{1}t-\ldots-\delta_{k}t^{k}-X_{t}\beta
& =\epsilon_{t} \\
\left(1-L\right)^{d}\left(1-L^{s}\right)^{D}\Phi\left(L\right)
\Phi_{s}\left(L\right)\epsilon_{t}
& =\Theta\left(L\right)\Theta_{s}\left(L\right)\eta_{t}
where :math:`\eta_t \sim WN(0,\sigma^2)` is a white noise process, L
is the lag operator, and :math:`G(L)` are lag polynomials corresponding
to the autoregressive (:math:`\Phi`), seasonal autoregressive
(:math:`\Phi_s`), moving average (:math:`\Theta`), and seasonal moving
average components (:math:`\Theta_s`).
`enforce_stationarity` and `enforce_invertibility` are specified in the
constructor because they affect loglikelihood computations, and so should
not be changed on the fly. This is why they are not instead included as
arguments to the `fit` method.
.. todo:: should concentrate_scale=True by default
Examples
--------
>>> mod = sm.tsa.arima.ARIMA(endog, order=(1, 0, 0))
>>> res = mod.fit()
>>> print(res.summary())
"""
def __init__(self, endog, exog=None, order=(0, 0, 0),
seasonal_order=(0, 0, 0, 0), trend=None,
enforce_stationarity=True, enforce_invertibility=True,
concentrate_scale=False, trend_offset=1, dates=None,
freq=None, missing='none', validate_specification=True):
# Default for trend
# 'c' if there is no integration and 'n' otherwise
# TODO: if trend='c', then we could alternatively use `demean=True` in
# the estimation methods rather than setting up `exog` and using GLS.
# Not sure if it's worth the trouble though.
integrated = order[1] > 0 or seasonal_order[1] > 0
if trend is None and not integrated:
trend = 'c'
elif trend is None:
trend = 'n'
# Construct the specification
# (don't pass specific values of enforce stationarity/invertibility,
# because we don't actually want to restrict the estimators based on
# this criteria. Instead, we'll just make sure that the parameter
# estimates from those methods satisfy the criteria.)
self._spec_arima = SARIMAXSpecification(
endog, exog=exog, order=order, seasonal_order=seasonal_order,
trend=trend, enforce_stationarity=None, enforce_invertibility=None,
concentrate_scale=concentrate_scale, trend_offset=trend_offset,
dates=dates, freq=freq, missing=missing,
validate_specification=validate_specification)
exog = self._spec_arima._model.data.orig_exog
# Raise an error if we have a constant in an integrated model
has_trend = len(self._spec_arima.trend_terms) > 0
if has_trend:
lowest_trend = np.min(self._spec_arima.trend_terms)
if lowest_trend < order[1] + seasonal_order[1]:
raise ValueError(
'In models with integration (`d > 0`) or seasonal'
' integration (`D > 0`), trend terms of lower order than'
' `d + D` cannot be (as they would be eliminated due to'
' the differencing operation). For example, a constant'
' cannot be included in an ARIMA(1, 1, 1) model, but'
' including a linear trend, which would have the same'
' effect as fitting a constant to the differenced data,'
' is allowed.')
# Keep the given `exog` by removing the prepended trend variables
input_exog = None
if exog is not None:
if _is_using_pandas(exog, None):
input_exog = exog.iloc[:, self._spec_arima.k_trend:]
else:
input_exog = exog[:, self._spec_arima.k_trend:]
# Initialize the base SARIMAX class
# Note: we don't pass in a trend value to the base class, since ARIMA
# standardizes the trend to always be part of exog, while the base
# SARIMAX class puts it in the transition equation.
super().__init__(
endog, exog, trend=None, order=order,
seasonal_order=seasonal_order,
enforce_stationarity=enforce_stationarity,
enforce_invertibility=enforce_invertibility,
concentrate_scale=concentrate_scale, dates=dates, freq=freq,
missing=missing, validate_specification=validate_specification)
self.trend = trend
# Save the input exog and input exog names, so that we can refer to
# them later (see especially `ARIMAResults.append`)
self._input_exog = input_exog
if exog is not None:
self._input_exog_names = self.exog_names[self._spec_arima.k_trend:]
else:
self._input_exog_names = None
# Override the public attributes for k_exog and k_trend to reflect the
# distinction here (for the purpose of the superclass, these are both
# combined as `k_exog`)
self.k_exog = self._spec_arima.k_exog
self.k_trend = self._spec_arima.k_trend
# Remove some init kwargs that aren't used in this model
unused = ['measurement_error', 'time_varying_regression',
'mle_regression', 'simple_differencing',
'hamilton_representation']
self._init_keys = [key for key in self._init_keys if key not in unused]
@property
def _res_classes(self):
return {'fit': (ARIMAResults, ARIMAResultsWrapper)}
def fit(self, start_params=None, transformed=True, includes_fixed=False,
method=None, method_kwargs=None, gls=None, gls_kwargs=None,
cov_type=None, cov_kwds=None, return_params=False,
low_memory=False):
"""
Fit (estimate) the parameters of the model.
Parameters
----------
start_params : array_like, optional
Initial guess of the solution for the loglikelihood maximization.
If None, the default is given by Model.start_params.
transformed : bool, optional
Whether or not `start_params` is already transformed. Default is
True.
includes_fixed : bool, optional
If parameters were previously fixed with the `fix_params` method,
this argument describes whether or not `start_params` also includes
the fixed parameters, in addition to the free parameters. Default
is False.
method : str, optional
The method used for estimating the parameters of the model. Valid
options include 'statespace', 'innovations_mle', 'hannan_rissanen',
'burg', 'innovations', and 'yule_walker'. Not all options are
available for every specification (for example 'yule_walker' can
only be used with AR(p) models).
method_kwargs : dict, optional
Arguments to pass to the fit function for the parameter estimator
described by the `method` argument.
gls : bool, optional
Whether or not to use generalized least squares (GLS) to estimate
regression effects. The default is False if `method='statespace'`
and is True otherwise.
gls_kwargs : dict, optional
Arguments to pass to the GLS estimation fit method. Only applicable
if GLS estimation is used (see `gls` argument for details).
cov_type : str, optional
The `cov_type` keyword governs the method for calculating the
covariance matrix of parameter estimates. Can be one of:
- 'opg' for the outer product of gradient estimator
- 'oim' for the observed information matrix estimator, calculated
using the method of Harvey (1989)
- 'approx' for the observed information matrix estimator,
calculated using a numerical approximation of the Hessian matrix.
- 'robust' for an approximate (quasi-maximum likelihood) covariance
matrix that may be valid even in the presence of some
misspecifications. Intermediate calculations use the 'oim'
method.
- 'robust_approx' is the same as 'robust' except that the
intermediate calculations use the 'approx' method.
- 'none' for no covariance matrix calculation.
Default is 'opg' unless memory conservation is used to avoid
computing the loglikelihood values for each observation, in which
case the default is 'oim'.
cov_kwds : dict or None, optional
A dictionary of arguments affecting covariance matrix computation.
**opg, oim, approx, robust, robust_approx**
- 'approx_complex_step' : bool, optional - If True, numerical
approximations are computed using complex-step methods. If False,
numerical approximations are computed using finite difference
methods. Default is True.
- 'approx_centered' : bool, optional - If True, numerical
approximations computed using finite difference methods use a
centered approximation. Default is False.
return_params : bool, optional
Whether or not to return only the array of maximizing parameters.
Default is False.
low_memory : bool, optional
If set to True, techniques are applied to substantially reduce
memory usage. If used, some features of the results object will
not be available (including smoothed results and in-sample
prediction), although out-of-sample forecasting is possible.
Default is False.
Returns
-------
ARIMAResults
Examples
--------
>>> mod = sm.tsa.arima.ARIMA(endog, order=(1, 0, 0))
>>> res = mod.fit()
>>> print(res.summary())
"""
# Determine which method to use
# 1. If method is specified, make sure it is valid
if method is not None:
self._spec_arima.validate_estimator(method)
# 2. Otherwise, use state space
# TODO: may want to consider using innovations (MLE) if possible here,
# (since in some cases it may be faster than state space), but it is
# less tested.
else:
method = 'statespace'
# Can only use fixed parameters with the following methods
methods_with_fixed_params = ['statespace', 'hannan_rissanen']
if self._has_fixed_params and method not in methods_with_fixed_params:
raise ValueError(
"When parameters have been fixed, only the methods "
f"{methods_with_fixed_params} can be used; got '{method}'."
)
# Handle kwargs related to the fit method
if method_kwargs is None:
method_kwargs = {}
required_kwargs = []
if method == 'statespace':
required_kwargs = ['enforce_stationarity', 'enforce_invertibility',
'concentrate_scale']
elif method == 'innovations_mle':
required_kwargs = ['enforce_invertibility']
for name in required_kwargs:
if name in method_kwargs:
raise ValueError('Cannot override model level value for "%s"'
' when method="%s".' % (name, method))
method_kwargs[name] = getattr(self, name)
# Handle kwargs related to GLS estimation
if gls_kwargs is None:
gls_kwargs = {}
# Handle starting parameters
# TODO: maybe should have standard way of computing starting
# parameters in this class?
if start_params is not None:
if method not in ['statespace', 'innovations_mle']:
raise ValueError('Estimation method "%s" does not use starting'
' parameters, but `start_params` argument was'
' given.' % method)
method_kwargs['start_params'] = start_params
method_kwargs['transformed'] = transformed
method_kwargs['includes_fixed'] = includes_fixed
# Perform estimation, depending on whether we have exog or not
p = None
fit_details = None
has_exog = self._spec_arima.exog is not None
if has_exog or method == 'statespace':
# Use GLS if it was explicitly requested (`gls = True`) or if it
# was left at the default (`gls = None`) and the ARMA estimator is
# anything but statespace.
# Note: both GLS and statespace are able to handle models with
# integration, so we don't need to difference endog or exog here.
if has_exog and (gls or (gls is None and method != 'statespace')):
if self._has_fixed_params:
raise NotImplementedError(
'GLS estimation is not yet implemented for the case '
'with fixed parameters.'
)
p, fit_details = estimate_gls(
self.endog, exog=self.exog, order=self.order,
seasonal_order=self.seasonal_order, include_constant=False,
arma_estimator=method, arma_estimator_kwargs=method_kwargs,
**gls_kwargs)
elif method != 'statespace':
raise ValueError('If `exog` is given and GLS is disabled'
' (`gls=False`), then the only valid'
" method is 'statespace'. Got '%s'."
% method)
else:
method_kwargs.setdefault('disp', 0)
res = super().fit(
return_params=return_params, low_memory=low_memory,
cov_type=cov_type, cov_kwds=cov_kwds, **method_kwargs)
if not return_params:
res.fit_details = res.mlefit
else:
# Handle differencing if we have an integrated model
# (these methods do not support handling integration internally,
# so we need to manually do the differencing)
endog = self.endog
order = self._spec_arima.order
seasonal_order = self._spec_arima.seasonal_order
if self._spec_arima.is_integrated:
warnings.warn('Provided `endog` series has been differenced'
' to eliminate integration prior to parameter'
' estimation by method "%s".' % method,
stacklevel=2,)
endog = diff(
endog, k_diff=self._spec_arima.diff,
k_seasonal_diff=self._spec_arima.seasonal_diff,
seasonal_periods=self._spec_arima.seasonal_periods)
if order[1] > 0:
order = (order[0], 0, order[2])
if seasonal_order[1] > 0:
seasonal_order = (seasonal_order[0], 0, seasonal_order[2],
seasonal_order[3])
if self._has_fixed_params:
method_kwargs['fixed_params'] = self._fixed_params.copy()
# Now, estimate parameters
if method == 'yule_walker':
p, fit_details = yule_walker(
endog, ar_order=order[0], demean=False,
**method_kwargs)
elif method == 'burg':
p, fit_details = burg(endog, ar_order=order[0],
demean=False, **method_kwargs)
elif method == 'hannan_rissanen':
p, fit_details = hannan_rissanen(
endog, ar_order=order[0],
ma_order=order[2], demean=False, **method_kwargs)
elif method == 'innovations':
p, fit_details = innovations(
endog, ma_order=order[2], demean=False,
**method_kwargs)
# innovations computes estimates through the given order, so
# we want to take the estimate associated with the given order
p = p[-1]
elif method == 'innovations_mle':
p, fit_details = innovations_mle(
endog, order=order,
seasonal_order=seasonal_order,
demean=False, **method_kwargs)
# In all cases except method='statespace', we now need to extract the
# parameters and, optionally, create a new results object
if p is not None:
# Need to check that fitted parameters satisfy given restrictions
if (self.enforce_stationarity
and self._spec_arima.max_reduced_ar_order > 0
and not p.is_stationary):
raise ValueError('Non-stationary autoregressive parameters'
' found with `enforce_stationarity=True`.'
' Consider setting it to False or using a'
' different estimation method, such as'
' method="statespace".')
if (self.enforce_invertibility
and self._spec_arima.max_reduced_ma_order > 0
and not p.is_invertible):
raise ValueError('Non-invertible moving average parameters'
' found with `enforce_invertibility=True`.'
' Consider setting it to False or using a'
' different estimation method, such as'
' method="statespace".')
# Build the requested results
if return_params:
res = p.params
else:
# Handle memory conservation option
if low_memory:
conserve_memory = self.ssm.conserve_memory
self.ssm.set_conserve_memory(MEMORY_CONSERVE)
# Perform filtering / smoothing
if (self.ssm.memory_no_predicted or self.ssm.memory_no_gain
or self.ssm.memory_no_smoothing):
func = self.filter
else:
func = self.smooth
res = func(p.params, transformed=True, includes_fixed=True,
cov_type=cov_type, cov_kwds=cov_kwds)
# Save any details from the fit method
res.fit_details = fit_details
# Reset memory conservation
if low_memory:
self.ssm.set_conserve_memory(conserve_memory)
return res
@Appender(sarimax.SARIMAXResults.__doc__)
class ARIMAResults(sarimax.SARIMAXResults):
@Appender(sarimax.SARIMAXResults.append.__doc__)
def append(self, endog, exog=None, refit=False, fit_kwargs=None, **kwargs):
# MLEResults.append will concatenate the given `exog` here with
# `data.orig_exog`. However, `data.orig_exog` already has had any
# trend variables prepended to it, while the `exog` given here should
# not. Instead, we need to temporarily replace `orig_exog` and
# `exog_names` with the ones that correspond to those that were input
# by the user.
if exog is not None:
orig_exog = self.model.data.orig_exog
exog_names = self.model.exog_names
self.model.data.orig_exog = self.model._input_exog
self.model.exog_names = self.model._input_exog_names
# Perform the appending procedure
out = super().append(endog, exog=exog, refit=refit,
fit_kwargs=fit_kwargs, **kwargs)
# Now we reverse the temporary change made above
if exog is not None:
self.model.data.orig_exog = orig_exog
self.model.exog_names = exog_names
return out
class ARIMAResultsWrapper(sarimax.SARIMAXResultsWrapper):
_attrs = {}
_wrap_attrs = wrap.union_dicts(
sarimax.SARIMAXResultsWrapper._wrap_attrs, _attrs)
_methods = {}
_wrap_methods = wrap.union_dicts(
sarimax.SARIMAXResultsWrapper._wrap_methods, _methods)
wrap.populate_wrapper(ARIMAResultsWrapper, ARIMAResults) # noqa:E305
| bsd-3-clause | 9145ca34808a33cde1312b4a1044f333 | 46.89603 | 79 | 0.600939 | 4.251174 | false | false | false | false |
statsmodels/statsmodels | statsmodels/datasets/modechoice/data.py | 3 | 2633 | """Travel Mode Choice"""
from statsmodels.datasets import utils as du
__docformat__ = 'restructuredtext'
COPYRIGHT = """This is public domain."""
TITLE = __doc__
SOURCE = """
Greene, W.H. and D. Hensher (1997) Multinomial logit and discrete choice models
in Greene, W. H. (1997) LIMDEP version 7.0 user's manual revised, Plainview,
New York econometric software, Inc.
Download from on-line complements to Greene, W.H. (2011) Econometric Analysis,
Prentice Hall, 7th Edition (data table F18-2)
http://people.stern.nyu.edu/wgreene/Text/Edition7/TableF18-2.csv
"""
DESCRSHORT = """Data used to study travel mode choice between Australian cities
"""
DESCRLONG = """The data, collected as part of a 1987 intercity mode choice
study, are a sub-sample of 210 non-business trips between Sydney, Canberra and
Melbourne in which the traveler chooses a mode from four alternatives (plane,
car, bus and train). The sample, 840 observations, is choice based with
over-sampling of the less popular modes (plane, train and bus) and under-sampling
of the more popular mode, car. The level of service data was derived from highway
and transport networks in Sydney, Melbourne, non-metropolitan N.S.W. and Victoria,
including the Australian Capital Territory."""
NOTE = """::
Number of observations: 840 Observations On 4 Modes for 210 Individuals.
Number of variables: 8
Variable name definitions::
individual = 1 to 210
mode =
1 - air
2 - train
3 - bus
4 - car
choice =
0 - no
1 - yes
ttme = terminal waiting time for plane, train and bus (minutes); 0
for car.
invc = in vehicle cost for all stages (dollars).
invt = travel time (in-vehicle time) for all stages (minutes).
gc = generalized cost measure:invc+(invt*value of travel time savings)
(dollars).
hinc = household income ($1000s).
psize = traveling group size in mode chosen (number)."""
def load():
"""
Load the data modechoice data and return a Dataset class instance.
Returns
-------
Dataset
See DATASET_PROPOSAL.txt for more information.
"""
return load_pandas()
def load_pandas():
"""
Load the data modechoice data and return a Dataset class instance.
Returns
-------
Dataset
See DATASET_PROPOSAL.txt for more information.
"""
data = _get_data()
return du.process_pandas(data, endog_idx = 2, exog_idx=[3,4,5,6,7,8])
def _get_data():
return du.load_csv(__file__, 'modechoice.csv', sep=';', convert_float=True)
| bsd-3-clause | 0c09303cac9505d8c32102de9411a628 | 31.9125 | 82 | 0.663122 | 3.572592 | false | false | false | false |
statsmodels/statsmodels | statsmodels/nonparametric/tests/test_kde.py | 3 | 12795 | import os
import numpy.testing as npt
import numpy as np
import pytest
from scipy import stats
from statsmodels.distributions.mixture_rvs import mixture_rvs
from statsmodels.nonparametric.kde import KDEUnivariate as KDE
import statsmodels.sandbox.nonparametric.kernels as kernels
import statsmodels.nonparametric.bandwidths as bandwidths
# get results from Stata
curdir = os.path.dirname(os.path.abspath(__file__))
rfname = os.path.join(curdir, 'results', 'results_kde.csv')
# print rfname
KDEResults = np.genfromtxt(open(rfname, 'rb'), delimiter=",", names=True)
rfname = os.path.join(curdir, 'results', 'results_kde_univ_weights.csv')
KDEWResults = np.genfromtxt(open(rfname, 'rb'), delimiter=",", names=True)
# get results from R
curdir = os.path.dirname(os.path.abspath(__file__))
rfname = os.path.join(curdir, 'results', 'results_kcde.csv')
# print rfname
KCDEResults = np.genfromtxt(open(rfname, 'rb'), delimiter=",", names=True)
# setup test data
np.random.seed(12345)
Xi = mixture_rvs([.25, .75], size=200, dist=[stats.norm, stats.norm],
kwargs=(dict(loc=-1, scale=.5), dict(loc=1, scale=.5)))
class TestKDEExceptions:
@classmethod
def setup_class(cls):
cls.kde = KDE(Xi)
cls.weights_200 = np.linspace(1, 100, 200)
cls.weights_100 = np.linspace(1, 100, 100)
def test_check_is_fit_exception(self):
with pytest.raises(ValueError):
self.kde.evaluate(0)
def test_non_weighted_fft_exception(self):
with pytest.raises(NotImplementedError):
self.kde.fit(kernel="gau", gridsize=50, weights=self.weights_200,
fft=True, bw="silverman")
def test_wrong_weight_length_exception(self):
with pytest.raises(ValueError):
self.kde.fit(kernel="gau", gridsize=50, weights=self.weights_100,
fft=False, bw="silverman")
def test_non_gaussian_fft_exception(self):
with pytest.raises(NotImplementedError):
self.kde.fit(kernel="epa", gridsize=50, fft=True, bw="silverman")
class CheckKDE:
decimal_density = 7
def test_density(self):
npt.assert_almost_equal(self.res1.density, self.res_density,
self.decimal_density)
def test_evaluate(self):
# disable test
# fails for Epan, Triangular and Biweight, only Gaussian is correct
# added it as test method to TestKDEGauss below
# inDomain is not vectorized
# kde_vals = self.res1.evaluate(self.res1.support)
kde_vals = [np.squeeze(self.res1.evaluate(xi)) for xi in self.res1.support]
kde_vals = np.squeeze(kde_vals) # kde_vals is a "column_list"
mask_valid = np.isfinite(kde_vals)
# TODO: nans at the boundaries
kde_vals[~mask_valid] = 0
npt.assert_almost_equal(kde_vals, self.res_density,
self.decimal_density)
class TestKDEGauss(CheckKDE):
@classmethod
def setup_class(cls):
res1 = KDE(Xi)
res1.fit(kernel="gau", fft=False, bw="silverman")
cls.res1 = res1
cls.res_density = KDEResults["gau_d"]
def test_evaluate(self):
# kde_vals = self.res1.evaluate(self.res1.support)
kde_vals = [self.res1.evaluate(xi) for xi in self.res1.support]
kde_vals = np.squeeze(kde_vals) # kde_vals is a "column_list"
mask_valid = np.isfinite(kde_vals)
# TODO: nans at the boundaries
kde_vals[~mask_valid] = 0
npt.assert_almost_equal(kde_vals, self.res_density,
self.decimal_density)
# The following tests are regression tests
# Values have been checked to be very close to R 'ks' package (Dec 2013)
def test_support_gridded(self):
kde = self.res1
support = KCDEResults['gau_support']
npt.assert_allclose(support, kde.support)
def test_cdf_gridded(self):
kde = self.res1
cdf = KCDEResults['gau_cdf']
npt.assert_allclose(cdf, kde.cdf)
def test_sf_gridded(self):
kde = self.res1
sf = KCDEResults['gau_sf']
npt.assert_allclose(sf, kde.sf)
def test_icdf_gridded(self):
kde = self.res1
icdf = KCDEResults['gau_icdf']
npt.assert_allclose(icdf, kde.icdf)
class TestKDEEpanechnikov(CheckKDE):
@classmethod
def setup_class(cls):
res1 = KDE(Xi)
res1.fit(kernel="epa", fft=False, bw="silverman")
cls.res1 = res1
cls.res_density = KDEResults["epa2_d"]
class TestKDETriangular(CheckKDE):
@classmethod
def setup_class(cls):
res1 = KDE(Xi)
res1.fit(kernel="tri", fft=False, bw="silverman")
cls.res1 = res1
cls.res_density = KDEResults["tri_d"]
class TestKDEBiweight(CheckKDE):
@classmethod
def setup_class(cls):
res1 = KDE(Xi)
res1.fit(kernel="biw", fft=False, bw="silverman")
cls.res1 = res1
cls.res_density = KDEResults["biw_d"]
# FIXME: enable/xfail/skip or delete
# NOTE: This is a knownfailure due to a definitional difference of Cosine kernel
# class TestKDECosine(CheckKDE):
# @classmethod
# def setup_class(cls):
# res1 = KDE(Xi)
# res1.fit(kernel="cos", fft=False, bw="silverman")
# cls.res1 = res1
# cls.res_density = KDEResults["cos_d"]
# weighted estimates taken from matlab so we can allow len(weights) != gridsize
class TestKdeWeights(CheckKDE):
@classmethod
def setup_class(cls):
res1 = KDE(Xi)
weights = np.linspace(1, 100, 200)
res1.fit(kernel="gau", gridsize=50, weights=weights, fft=False,
bw="silverman")
cls.res1 = res1
fname = os.path.join(curdir, 'results', 'results_kde_weights.csv')
cls.res_density = np.genfromtxt(open(fname, 'rb'), skip_header=1)
def test_evaluate(self):
# kde_vals = self.res1.evaluate(self.res1.support)
kde_vals = [self.res1.evaluate(xi) for xi in self.res1.support]
kde_vals = np.squeeze(kde_vals) # kde_vals is a "column_list"
mask_valid = np.isfinite(kde_vals)
# TODO: nans at the boundaries
kde_vals[~mask_valid] = 0
npt.assert_almost_equal(kde_vals, self.res_density,
self.decimal_density)
class TestKDEGaussFFT(CheckKDE):
@classmethod
def setup_class(cls):
cls.decimal_density = 2 # low accuracy because binning is different
res1 = KDE(Xi)
res1.fit(kernel="gau", fft=True, bw="silverman")
cls.res1 = res1
rfname2 = os.path.join(curdir, 'results', 'results_kde_fft.csv')
cls.res_density = np.genfromtxt(open(rfname2, 'rb'))
class CheckKDEWeights:
@classmethod
def setup_class(cls):
cls.x = x = KDEWResults['x']
weights = KDEWResults['weights']
res1 = KDE(x)
# default kernel was scott when reference values computed
res1.fit(kernel=cls.kernel_name, weights=weights, fft=False, bw="scott")
cls.res1 = res1
cls.res_density = KDEWResults[cls.res_kernel_name]
decimal_density = 7
@pytest.mark.xfail(reason="Not almost equal to 7 decimals",
raises=AssertionError, strict=True)
def test_density(self):
npt.assert_almost_equal(self.res1.density, self.res_density,
self.decimal_density)
def test_evaluate(self):
if self.kernel_name == 'cos':
pytest.skip("Cosine kernel fails against Stata")
kde_vals = [self.res1.evaluate(xi) for xi in self.x]
kde_vals = np.squeeze(kde_vals) # kde_vals is a "column_list"
npt.assert_almost_equal(kde_vals, self.res_density,
self.decimal_density)
def test_compare(self):
xx = self.res1.support
kde_vals = [np.squeeze(self.res1.evaluate(xi)) for xi in xx]
kde_vals = np.squeeze(kde_vals) # kde_vals is a "column_list"
mask_valid = np.isfinite(kde_vals)
# TODO: nans at the boundaries
kde_vals[~mask_valid] = 0
npt.assert_almost_equal(self.res1.density, kde_vals,
self.decimal_density)
# regression test, not compared to another package
nobs = len(self.res1.endog)
kern = self.res1.kernel
v = kern.density_var(kde_vals, nobs)
v_direct = kde_vals * kern.L2Norm / kern.h / nobs
npt.assert_allclose(v, v_direct, rtol=1e-10)
ci = kern.density_confint(kde_vals, nobs)
crit = 1.9599639845400545 # stats.norm.isf(0.05 / 2)
hw = kde_vals - ci[:, 0]
npt.assert_allclose(hw, crit * np.sqrt(v), rtol=1e-10)
hw = ci[:, 1] - kde_vals
npt.assert_allclose(hw, crit * np.sqrt(v), rtol=1e-10)
def test_kernel_constants(self):
kern = self.res1.kernel
nc = kern.norm_const
# trigger numerical integration
kern._norm_const = None
nc2 = kern.norm_const
npt.assert_allclose(nc, nc2, rtol=1e-10)
l2n = kern.L2Norm
# trigger numerical integration
kern._L2Norm = None
l2n2 = kern.L2Norm
npt.assert_allclose(l2n, l2n2, rtol=1e-10)
v = kern.kernel_var
# trigger numerical integration
kern._kernel_var = None
v2 = kern.kernel_var
npt.assert_allclose(v, v2, rtol=1e-10)
class TestKDEWGauss(CheckKDEWeights):
kernel_name = "gau"
res_kernel_name = "x_gau_wd"
class TestKDEWEpa(CheckKDEWeights):
kernel_name = "epa"
res_kernel_name = "x_epan2_wd"
class TestKDEWTri(CheckKDEWeights):
kernel_name = "tri"
res_kernel_name = "x_" + kernel_name + "_wd"
class TestKDEWBiw(CheckKDEWeights):
kernel_name = "biw"
res_kernel_name = "x_bi_wd"
class TestKDEWCos(CheckKDEWeights):
kernel_name = "cos"
res_kernel_name = "x_cos_wd"
class TestKDEWCos2(CheckKDEWeights):
kernel_name = "cos2"
res_kernel_name = "x_cos_wd"
class _TestKDEWRect(CheckKDEWeights):
# TODO in docstring but not in kernel_switch
kernel_name = "rect"
res_kernel_name = "x_rec_wd"
class _TestKDEWPar(CheckKDEWeights):
# TODO in docstring but not implemented in kernels
kernel_name = "par"
res_kernel_name = "x_par_wd"
class TestKdeRefit:
np.random.seed(12345)
data1 = np.random.randn(100) * 100
pdf = KDE(data1)
pdf.fit()
data2 = np.random.randn(100) * 100
pdf2 = KDE(data2)
pdf2.fit()
for attr in ['icdf', 'cdf', 'sf']:
npt.assert_(not np.allclose(getattr(pdf, attr)[:10],
getattr(pdf2, attr)[:10]))
class TestNormConstant:
def test_norm_constant_calculation(self):
custom_gauss = kernels.CustomKernel(lambda x: np.exp(-x ** 2 / 2.0))
gauss_true_const = 0.3989422804014327
npt.assert_almost_equal(gauss_true_const, custom_gauss.norm_const)
def test_kde_bw_positive():
# GH 6679
x = np.array([4.59511985, 4.59511985, 4.59511985, 4.59511985, 4.59511985,
4.59511985, 4.59511985, 4.59511985, 4.59511985, 4.59511985,
5.67332327, 6.19847872, 7.43189192])
kde = KDE(x)
kde.fit()
assert kde.bw > 0
def test_fit_self(reset_randomstate):
x = np.random.standard_normal(100)
kde = KDE(x)
assert isinstance(kde, KDE)
assert isinstance(kde.fit(), KDE)
class TestKDECustomBandwidth:
decimal_density = 7
@classmethod
def setup_class(cls):
cls.kde = KDE(Xi)
cls.weights_200 = np.linspace(1, 100, 200)
cls.weights_100 = np.linspace(1, 100, 100)
def test_check_is_fit_ok_with_custom_bandwidth(self):
def custom_bw(X, kern):
return np.std(X) * len(X)
kde = self.kde.fit(bw=custom_bw)
assert isinstance(kde, KDE)
def test_check_is_fit_ok_with_standard_custom_bandwidth(self):
# Note, we are passing the function, not the string - this is intended
kde = self.kde.fit(bw=bandwidths.bw_silverman)
s1 = kde.support.copy()
d1 = kde.density.copy()
kde = self.kde.fit(bw='silverman')
npt.assert_almost_equal(s1, kde.support, self.decimal_density)
npt.assert_almost_equal(d1, kde.density, self.decimal_density)
@pytest.mark.parametrize("fft", [True, False])
def test_check_is_fit_ok_with_float_bandwidth(self, fft):
# Note, we are passing the function, not the string - this is intended
kde = self.kde.fit(bw=bandwidths.bw_silverman, fft=fft)
s1 = kde.support.copy()
d1 = kde.density.copy()
kde = self.kde.fit(bw=kde.bw, fft=fft)
npt.assert_almost_equal(s1, kde.support, self.decimal_density)
npt.assert_almost_equal(d1, kde.density, self.decimal_density)
| bsd-3-clause | b07d9ee41dba39895c70257af30aa36a | 31.807692 | 83 | 0.621102 | 3.147601 | false | true | false | false |
statsmodels/statsmodels | statsmodels/graphics/tests/test_dotplot.py | 3 | 15085 | import numpy as np
import pandas as pd
import pytest
from statsmodels.graphics.dotplots import dot_plot
# If true, the output is written to a multi-page pdf file.
pdf_output = False
try:
import matplotlib.pyplot as plt
except ImportError:
pass
def close_or_save(pdf, fig):
if pdf_output:
pdf.savefig(fig)
@pytest.mark.matplotlib
def test_all(close_figures, reset_randomstate):
if pdf_output:
from matplotlib.backends.backend_pdf import PdfPages
pdf = PdfPages("test_dotplot.pdf")
else:
pdf = None
# Basic dotplot with points only
plt.clf()
points = range(20)
ax = plt.axes()
fig = dot_plot(points, ax=ax)
ax.set_title("Basic horizontal dotplot")
close_or_save(pdf, fig)
# Basic vertical dotplot
plt.clf()
points = range(20)
ax = plt.axes()
fig = dot_plot(points, ax=ax, horizontal=False)
ax.set_title("Basic vertical dotplot")
close_or_save(pdf, fig)
# Tall and skinny
plt.figure(figsize=(4,12))
ax = plt.axes()
vals = np.arange(40)
fig = dot_plot(points, ax=ax)
ax.set_title("Tall and skinny dotplot")
ax.set_xlabel("x axis label")
close_or_save(pdf, fig)
# Short and wide
plt.figure(figsize=(12,4))
ax = plt.axes()
vals = np.arange(40)
fig = dot_plot(points, ax=ax, horizontal=False)
ax.set_title("Short and wide dotplot")
ax.set_ylabel("y axis label")
close_or_save(pdf, fig)
# Tall and skinny striped dotplot
plt.figure(figsize=(4,12))
ax = plt.axes()
points = np.arange(40)
fig = dot_plot(points, ax=ax, striped=True)
ax.set_title("Tall and skinny striped dotplot")
ax.set_xlim(-10, 50)
close_or_save(pdf, fig)
# Short and wide striped
plt.figure(figsize=(12,4))
ax = plt.axes()
points = np.arange(40)
fig = dot_plot(points, ax=ax, striped=True, horizontal=False)
ax.set_title("Short and wide striped dotplot")
ax.set_ylim(-10, 50)
close_or_save(pdf, fig)
# Basic dotplot with few points
plt.figure()
ax = plt.axes()
points = np.arange(4)
fig = dot_plot(points, ax=ax)
ax.set_title("Basic horizontal dotplot with few lines")
close_or_save(pdf, fig)
# Basic dotplot with few points
plt.figure()
ax = plt.axes()
points = np.arange(4)
fig = dot_plot(points, ax=ax, horizontal=False)
ax.set_title("Basic vertical dotplot with few lines")
close_or_save(pdf, fig)
# Manually set the x axis limits
plt.figure()
ax = plt.axes()
points = np.arange(20)
fig = dot_plot(points, ax=ax)
ax.set_xlim(-10, 30)
ax.set_title("Dotplot with adjusted horizontal range")
close_or_save(pdf, fig)
# Left row labels
plt.clf()
ax = plt.axes()
lines = ["ABCDEFGH"[np.random.randint(0, 8)] for k in range(20)]
points = np.random.normal(size=20)
fig = dot_plot(points, lines=lines, ax=ax)
ax.set_title("Dotplot with user-supplied labels in the left margin")
close_or_save(pdf, fig)
# Left and right row labels
plt.clf()
ax = plt.axes()
points = np.random.normal(size=20)
lines = ["ABCDEFGH"[np.random.randint(0, 8)] + "::" + str(k+1)
for k in range(20)]
fig = dot_plot(points, lines=lines, ax=ax, split_names="::")
ax.set_title("Dotplot with user-supplied labels in both margins")
close_or_save(pdf, fig)
# Both sides row labels
plt.clf()
ax = plt.axes([0.1, 0.1, 0.88, 0.8])
points = np.random.normal(size=20)
lines = ["ABCDEFGH"[np.random.randint(0, 8)] + "::" + str(k+1)
for k in range(20)]
fig = dot_plot(points, lines=lines, ax=ax, split_names="::",
horizontal=False)
txt = ax.set_title("Vertical dotplot with user-supplied labels in both margins")
txt.set_position((0.5, 1.06))
close_or_save(pdf, fig)
# Custom colors and symbols
plt.clf()
ax = plt.axes([0.1, 0.07, 0.78, 0.85])
points = np.random.normal(size=20)
lines = np.kron(range(5), np.ones(4)).astype(np.int32)
styles = np.kron(np.ones(5), range(4)).astype(np.int32)
marker_props = {k: {"color": "rgbc"[k], "marker": "osvp"[k],
"ms": 7, "alpha": 0.6} for k in range(4)}
fig = dot_plot(points, lines=lines, styles=styles, ax=ax,
marker_props=marker_props)
ax.set_title("Dotplot with custom colors and symbols")
close_or_save(pdf, fig)
# Basic dotplot with symmetric intervals
plt.clf()
ax = plt.axes()
points = range(20)
fig = dot_plot(points, intervals=np.ones(20), ax=ax)
ax.set_title("Dotplot with symmetric intervals")
close_or_save(pdf, fig)
# Basic dotplot with symmetric intervals, pandas inputs.
plt.clf()
ax = plt.axes()
points = pd.Series(range(20))
intervals = pd.Series(np.ones(20))
fig = dot_plot(points, intervals=intervals, ax=ax)
ax.set_title("Dotplot with symmetric intervals (Pandas inputs)")
close_or_save(pdf, fig)
# Basic dotplot with nonsymmetric intervals
plt.clf()
ax = plt.axes()
points = np.arange(20)
intervals = [(1, 3) for i in range(20)]
fig = dot_plot(points, intervals=intervals, ax=ax)
ax.set_title("Dotplot with nonsymmetric intervals")
close_or_save(pdf, fig)
# Vertical dotplot with nonsymmetric intervals
plt.clf()
ax = plt.axes()
points = np.arange(20)
intervals = [(1, 3) for i in range(20)]
fig = dot_plot(points, intervals=intervals, ax=ax, horizontal=False)
ax.set_title("Vertical dotplot with nonsymmetric intervals")
close_or_save(pdf, fig)
# Dotplot with nonsymmetric intervals, adjust line properties
plt.clf()
ax = plt.axes()
points = np.arange(20)
intervals = [(1, 3) for x in range(20)]
line_props = {0: {"color": "lightgrey",
"solid_capstyle": "round"}}
fig = dot_plot(points, intervals=intervals, line_props=line_props, ax=ax)
ax.set_title("Dotplot with custom line properties")
close_or_save(pdf, fig)
# Dotplot with two points per line and a legend
plt.clf()
ax = plt.axes([0.1, 0.1, 0.75, 0.8])
points = 5*np.random.normal(size=40)
lines = np.kron(range(20), (1,1))
intervals = [(1,3) for k in range(40)]
styles = np.kron(np.ones(20), (0,1)).astype(np.int32)
styles = [["Cat", "Dog"][i] for i in styles]
fig = dot_plot(points, intervals=intervals, lines=lines, styles=styles,
ax=ax, stacked=True)
handles, labels = ax.get_legend_handles_labels()
leg = plt.figlegend(handles, labels, loc="center right", numpoints=1,
handletextpad=0.0001)
leg.draw_frame(False)
ax.set_title("Dotplot with two points per line")
close_or_save(pdf, fig)
# Dotplot with two points per line and a legend
plt.clf()
ax = plt.axes([0.1, 0.1, 0.75, 0.8])
fig = dot_plot(points, intervals=intervals, lines=lines,
styles=styles, ax=ax, stacked=True,
styles_order=["Dog", "Cat"])
handles, labels = ax.get_legend_handles_labels()
leg = plt.figlegend(handles, labels, loc="center right", numpoints=1,
handletextpad=0.0001)
leg.draw_frame(False)
ax.set_title("Dotplot with two points per line (reverse order)")
close_or_save(pdf, fig)
# Vertical dotplot with two points per line and a legend
plt.clf()
ax = plt.axes([0.1, 0.1, 0.75, 0.8])
points = 5*np.random.normal(size=40)
lines = np.kron(range(20), (1,1))
intervals = [(1,3) for k in range(40)]
styles = np.kron(np.ones(20), (0,1)).astype(np.int32)
styles = [["Cat", "Dog"][i] for i in styles]
fig = dot_plot(points, intervals=intervals, lines=lines, styles=styles,
ax=ax, stacked=True, horizontal=False)
handles, labels = ax.get_legend_handles_labels()
leg = plt.figlegend(handles, labels, loc="center right", numpoints=1,
handletextpad=0.0001)
leg.draw_frame(False)
ax.set_title("Vertical dotplot with two points per line")
close_or_save(pdf, fig)
# Vertical dotplot with two points per line and a legend
plt.clf()
ax = plt.axes([0.1, 0.1, 0.75, 0.8])
styles_order = ["Dog", "Cat"]
fig = dot_plot(points, intervals=intervals, lines=lines,
styles=styles, ax=ax, stacked=True,
horizontal=False, styles_order=styles_order)
handles, labels = ax.get_legend_handles_labels()
lh = dict(zip(labels, handles))
handles = [lh[l] for l in styles_order]
leg = plt.figlegend(handles, styles_order, loc="center right", numpoints=1,
handletextpad=0.0001)
leg.draw_frame(False)
ax.set_title("Vertical dotplot with two points per line (reverse order)")
close_or_save(pdf, fig)
# Vertical dotplot with two points per line and a legend
plt.clf()
ax = plt.axes([0.1, 0.1, 0.75, 0.8])
points = 5*np.random.normal(size=40)
lines = np.kron(range(20), (1,1))
intervals = [(1,3) for k in range(40)]
styles = np.kron(np.ones(20), (0,1)).astype(np.int32)
styles = [["Cat", "Dog"][i] for i in styles]
fig = dot_plot(points, intervals=intervals, lines=lines, styles=styles,
ax=ax, stacked=True, striped=True, horizontal=False)
handles, labels = ax.get_legend_handles_labels()
leg = plt.figlegend(handles, labels, loc="center right", numpoints=1,
handletextpad=0.0001)
leg.draw_frame(False)
plt.ylim(-20, 20)
ax.set_title("Vertical dotplot with two points per line")
close_or_save(pdf, fig)
# Dotplot with color-matched points and intervals
plt.clf()
ax = plt.axes([0.1, 0.1, 0.75, 0.8])
points = 5*np.random.normal(size=40)
lines = np.kron(range(20), (1,1))
intervals = [(1,3) for k in range(40)]
styles = np.kron(np.ones(20), (0,1)).astype(np.int32)
styles = [["Cat", "Dog"][i] for i in styles]
marker_props = {"Cat": {"color": "orange"},
"Dog": {"color": "purple"}}
line_props = {"Cat": {"color": "orange"},
"Dog": {"color": "purple"}}
fig = dot_plot(points, intervals=intervals, lines=lines, styles=styles,
ax=ax, stacked=True, marker_props=marker_props,
line_props=line_props)
handles, labels = ax.get_legend_handles_labels()
leg = plt.figlegend(handles, labels, loc="center right", numpoints=1,
handletextpad=0.0001)
leg.draw_frame(False)
ax.set_title("Dotplot with color-matched points and intervals")
close_or_save(pdf, fig)
# Dotplot with color-matched points and intervals
plt.clf()
ax = plt.axes([0.1, 0.1, 0.75, 0.8])
points = 5*np.random.normal(size=40)
lines = np.kron(range(20), (1,1))
intervals = [(1,3) for k in range(40)]
styles = np.kron(np.ones(20), (0,1)).astype(np.int32)
styles = [["Cat", "Dog"][i] for i in styles]
marker_props = {"Cat": {"color": "orange"},
"Dog": {"color": "purple"}}
line_props = {"Cat": {"color": "orange"},
"Dog": {"color": "purple"}}
fig = dot_plot(points, intervals=intervals, lines=lines, styles=styles,
ax=ax, stacked=True, marker_props=marker_props,
line_props=line_props, horizontal=False)
handles, labels = ax.get_legend_handles_labels()
leg = plt.figlegend(handles, labels, loc="center right", numpoints=1,
handletextpad=0.0001)
leg.draw_frame(False)
ax.set_title("Dotplot with color-matched points and intervals")
close_or_save(pdf, fig)
# Dotplot with sections
plt.clf()
ax = plt.axes()
points = range(30)
lines = np.kron(range(15), (1,1)).astype(np.int32)
styles = np.kron(np.ones(15), (0,1)).astype(np.int32)
sections = np.kron((0,1,2), np.ones(10)).astype(np.int32)
sections = [["Axx", "Byy", "Czz"][k] for k in sections]
fig = dot_plot(points, lines=lines, styles=styles, sections=sections, ax=ax)
ax.set_title("Dotplot with sections")
close_or_save(pdf, fig)
# Vertical dotplot with sections
plt.clf()
ax = plt.axes([0.1,0.1,0.9,0.75])
points = range(30)
lines = np.kron(range(15), (1,1)).astype(np.int32)
styles = np.kron(np.ones(15), (0,1)).astype(np.int32)
sections = np.kron((0,1,2), np.ones(10)).astype(np.int32)
sections = [["Axx", "Byy", "Czz"][k] for k in sections]
fig = dot_plot(points, lines=lines, styles=styles,
sections=sections, ax=ax, horizontal=False)
txt = ax.set_title("Vertical dotplot with sections")
txt.set_position((0.5, 1.08))
close_or_save(pdf, fig)
# Reorder sections
plt.clf()
ax = plt.axes()
points = range(30)
lines = np.kron(range(15), (1,1)).astype(np.int32)
styles = np.kron(np.ones(15), (0,1)).astype(np.int32)
sections = np.kron((0,1,2), np.ones(10)).astype(np.int32)
sections = [["Axx", "Byy", "Czz"][k] for k in sections]
fig = dot_plot(points, lines=lines, styles=styles, sections=sections, ax=ax,
section_order=["Byy", "Axx", "Czz"])
ax.set_title("Dotplot with sections in specified order")
close_or_save(pdf, fig)
# Reorder the lines.
plt.figure()
ax = plt.axes()
points = np.arange(4)
lines = ["A", "B", "C", "D"]
line_order = ["B", "C", "A", "D"]
fig = dot_plot(points, lines=lines, line_order=line_order, ax=ax)
ax.set_title("Dotplot with reordered lines")
close_or_save(pdf, fig)
# Format labels
plt.clf()
points = range(20)
lines = ["%d::%d" % (i, 100+i) for i in range(20)]
fmt_left = lambda x : "lft_" + x
fmt_right = lambda x : "rgt_" + x
ax = plt.axes()
fig = dot_plot(points, lines=lines, ax=ax, split_names="::",
fmt_left_name=fmt_left, fmt_right_name=fmt_right)
ax.set_title("Horizontal dotplot with name formatting")
close_or_save(pdf, fig)
# Right names only
plt.clf()
points = range(20)
lines = ["%d::%d" % (i, 100+i) for i in range(20)]
ax = plt.axes()
fig = dot_plot(points, lines=lines, ax=ax, split_names="::",
show_names="right")
ax.set_title("Show right names only")
close_or_save(pdf, fig)
# Dotplot with different numbers of points per line
plt.clf()
ax = plt.axes([0.1, 0.1, 0.75, 0.8])
points = 5*np.random.normal(size=40)
lines = []
ii = 0
while len(lines) < 40:
for k in range(np.random.randint(1, 4)):
lines.append(ii)
ii += 1
styles = np.kron(np.ones(20), (0,1)).astype(np.int32)
styles = [["Cat", "Dog"][i] for i in styles]
fig = dot_plot(points, lines=lines, styles=styles,
ax=ax, stacked=True)
handles, labels = ax.get_legend_handles_labels()
leg = plt.figlegend(handles, labels, loc="center right", numpoints=1,
handletextpad=0.0001)
leg.draw_frame(False)
ax.set_title("Dotplot with different numbers of points per line")
close_or_save(pdf, fig)
if pdf_output:
pdf.close()
| bsd-3-clause | be9a1b285e04034d1e25e81615a23168 | 35.349398 | 84 | 0.607358 | 3.100082 | false | false | false | false |
statsmodels/statsmodels | statsmodels/sandbox/distributions/tests/test_transf.py | 3 | 6522 | # -*- coding: utf-8 -*-
"""
Created on Sun May 09 22:35:21 2010
Author: josef-pktd
License: BSD
todo:
change moment calculation, (currently uses default _ppf method - I think)
>>> lognormalg.moment(4)
Warning: The algorithm does not converge. Roundoff error is detected
in the extrapolation table. It is assumed that the requested tolerance
cannot be achieved, and that the returned result (if full_output = 1) is
the best which can be obtained.
array(2981.0032380193438)
"""
import warnings # for silencing, see above...
import numpy as np
from numpy.testing import assert_almost_equal
from scipy import stats, special
from statsmodels.sandbox.distributions.extras import (
squarenormalg, absnormalg, negsquarenormalg, squaretg)
# some patches to scipy.stats.distributions so tests work and pass
# this should be necessary only for older scipy
#patch frozen distributions with a name
stats.distributions.rv_frozen.name = property(lambda self: self.dist.name)
#patch f distribution, correct skew and maybe kurtosis
def f_stats(self, dfn, dfd):
arr, where, inf, sqrt, nan = np.array, np.where, np.inf, np.sqrt, np.nan
v2 = arr(dfd*1.0)
v1 = arr(dfn*1.0)
mu = where(v2 > 2, v2 / arr(v2 - 2), inf)
mu2 = 2*v2*v2*(v2+v1-2)/(v1*(v2-2)**2 * (v2-4))
mu2 = where(v2 > 4, mu2, inf)
#g1 = 2*(v2+2*v1-2)/(v2-6)*sqrt((2*v2-4)/(v1*(v2+v1-2)))
g1 = 2*(v2+2*v1-2.)/(v2-6.)*np.sqrt(2*(v2-4.)/(v1*(v2+v1-2.)))
g1 = where(v2 > 6, g1, nan)
#g2 = 3/(2*v2-16)*(8+g1*g1*(v2-6))
g2 = 3/(2.*v2-16)*(8+g1*g1*(v2-6.))
g2 = where(v2 > 8, g2, nan)
return mu, mu2, g1, g2
#stats.distributions.f_gen._stats = f_stats
stats.f.__class__._stats = f_stats
#correct kurtosis by subtracting 3 (Fisher)
#after this it matches halfnorm for arg close to zero
def foldnorm_stats(self, c):
arr, where, inf, sqrt, nan = np.array, np.where, np.inf, np.sqrt, np.nan
exp = np.exp
pi = np.pi
fac = special.erf(c/sqrt(2))
mu = sqrt(2.0/pi)*exp(-0.5*c*c)+c*fac
mu2 = c*c + 1 - mu*mu
c2 = c*c
g1 = sqrt(2/pi)*exp(-1.5*c2)*(4-pi*exp(c2)*(2*c2+1.0))
g1 += 2*c*fac*(6*exp(-c2) + 3*sqrt(2*pi)*c*exp(-c2/2.0)*fac + \
pi*c*(fac*fac-1))
g1 /= pi*mu2**1.5
g2 = c2*c2+6*c2+3+6*(c2+1)*mu*mu - 3*mu**4
g2 -= 4*exp(-c2/2.0)*mu*(sqrt(2.0/pi)*(c2+2)+c*(c2+3)*exp(c2/2.0)*fac)
g2 /= mu2**2.0
g2 -= 3.
return mu, mu2, g1, g2
#stats.distributions.foldnorm_gen._stats = foldnorm_stats
stats.foldnorm.__class__._stats = foldnorm_stats
#-----------------------------
DECIMAL = 5
class Test_Transf2:
@classmethod
def setup_class(cls):
cls.dist_equivalents = [
#transf, stats.lognorm(1))
#The below fails on the SPARC box with scipy 10.1
#(lognormalg, stats.lognorm(1)),
#transf2
(squarenormalg, stats.chi2(1)),
(absnormalg, stats.halfnorm),
(absnormalg, stats.foldnorm(1e-5)), #try frozen
#(negsquarenormalg, 1-stats.chi2), # will not work as distribution
(squaretg(10), stats.f(1, 10))
] #try both frozen
l,s = 0.0, 1.0
cls.ppfq = [0.1,0.5,0.9]
cls.xx = [0.95,1.0,1.1]
cls.nxx = [-0.95,-1.0,-1.1]
def test_equivalent(self):
xx, ppfq = self.xx, self.ppfq
for d1,d2 in self.dist_equivalents:
## print d1.name
assert_almost_equal(d1.cdf(xx), d2.cdf(xx), err_msg='cdf'+d1.name)
assert_almost_equal(d1.pdf(xx), d2.pdf(xx),
err_msg='pdf '+d1.name+d2.name)
assert_almost_equal(d1.sf(xx), d2.sf(xx),
err_msg='sf '+d1.name+d2.name)
assert_almost_equal(d1.ppf(ppfq), d2.ppf(ppfq),
err_msg='ppq '+d1.name+d2.name)
assert_almost_equal(d1.isf(ppfq), d2.isf(ppfq),
err_msg='isf '+d1.name+d2.name)
self.d1 = d1
self.d2 = d2
## print d1, d2
## print d1.moment(3)
## print d2.moment(3)
#work around bug#1293
if hasattr(d2, 'dist'):
d2mom = d2.dist.moment(3, *d2.args)
else:
d2mom = d2.moment(3)
assert_almost_equal(d1.moment(3), d2mom,
DECIMAL,
err_msg='moment '+d1.name+d2.name)
# silence warnings in scipy, works for versions
# after print changed to warning in scipy
orig_filter = warnings.filters[:]
warnings.simplefilter('ignore')
try:
s1 = d1.stats(moments='mvsk')
s2 = d2.stats(moments='mvsk')
finally:
warnings.filters = orig_filter
#stats(moments='k') prints warning for lognormalg
assert_almost_equal(s1[:2], s2[:2],
err_msg='stats '+d1.name+d2.name)
assert_almost_equal(s1[2:], s2[2:],
decimal=2, #lognorm for kurtosis
err_msg='stats '+d1.name+d2.name)
def test_equivalent_negsq(self):
#special case negsquarenormalg
#negsquarenormalg.cdf(x) == stats.chi2(1).cdf(-x), for x<=0
xx, nxx, ppfq = self.xx, self.nxx, self.ppfq
d1,d2 = (negsquarenormalg, stats.chi2(1))
#print d1.name
assert_almost_equal(d1.cdf(nxx), 1-d2.cdf(xx), err_msg='cdf'+d1.name)
assert_almost_equal(d1.pdf(nxx), d2.pdf(xx))
assert_almost_equal(d1.sf(nxx), 1-d2.sf(xx))
assert_almost_equal(d1.ppf(ppfq), -d2.ppf(ppfq)[::-1])
assert_almost_equal(d1.isf(ppfq), -d2.isf(ppfq)[::-1])
assert_almost_equal(d1.moment(3), -d2.moment(3))
ch2oddneg = [v*(-1)**(i+1) for i,v in
enumerate(d2.stats(moments='mvsk'))]
assert_almost_equal(d1.stats(moments='mvsk'), ch2oddneg,
err_msg='stats '+d1.name+d2.name)
if __name__ == '__main__':
tt = Test_Transf2()
tt.test_equivalent()
tt.test_equivalent_negsq()
debug = 0
if debug:
print(negsquarenormalg.ppf([0.1,0.5,0.9]))
print(stats.chi2.ppf([0.1,0.5,0.9],1))
print(negsquarenormalg.a)
print(negsquarenormalg.b)
print(absnormalg.stats( moments='mvsk'))
print(stats.foldnorm(1e-10).stats( moments='mvsk'))
print(stats.halfnorm.stats( moments='mvsk'))
| bsd-3-clause | 0bb2dfbd55440106f23c6ad279e00584 | 35.435754 | 79 | 0.553511 | 2.800343 | false | false | false | false |
statsmodels/statsmodels | statsmodels/regression/_prediction.py | 3 | 7055 | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 19 11:29:18 2014
Author: Josef Perktold
License: BSD-3
"""
import numpy as np
from scipy import stats
import pandas as pd
# this is similar to ContrastResults after t_test, copied and adjusted
class PredictionResults:
"""
Results class for predictions.
Parameters
----------
predicted_mean : ndarray
The array containing the prediction means.
var_pred_mean : ndarray
The array of the variance of the prediction means.
var_resid : ndarray
The array of residual variances.
df : int
The degree of freedom used if dist is 't'.
dist : {'norm', 't', object}
Either a string for the normal or t distribution or another object
that exposes a `ppf` method.
row_labels : list[str]
Row labels used in summary frame.
"""
def __init__(self, predicted_mean, var_pred_mean, var_resid,
df=None, dist=None, row_labels=None):
self.predicted = predicted_mean
self.var_pred = var_pred_mean
self.df = df
self.var_resid = var_resid
self.row_labels = row_labels
if dist is None or dist == 'norm':
self.dist = stats.norm
self.dist_args = ()
elif dist == 't':
self.dist = stats.t
self.dist_args = (self.df,)
else:
self.dist = dist
self.dist_args = ()
@property
def se_obs(self):
return np.sqrt(self.var_pred_mean + self.var_resid)
@property
def se_mean(self):
return self.se
@property
def predicted_mean(self):
# alias for backwards compatibility
return self.predicted
@property
def var_pred_mean(self):
# alias for backwards compatibility
return self.var_pred
@property
def se(self):
# alias for backwards compatibility
return np.sqrt(self.var_pred_mean)
def conf_int(self, obs=False, alpha=0.05):
"""
Returns the confidence interval of the value, `effect` of the
constraint.
This is currently only available for t and z tests.
Parameters
----------
alpha : float, optional
The significance level for the confidence interval.
ie., The default `alpha` = .05 returns a 95% confidence interval.
Returns
-------
ci : ndarray, (k_constraints, 2)
The array has the lower and the upper limit of the confidence
interval in the columns.
"""
se = self.se_obs if obs else self.se_mean
q = self.dist.ppf(1 - alpha / 2., *self.dist_args)
lower = self.predicted_mean - q * se
upper = self.predicted_mean + q * se
return np.column_stack((lower, upper))
def summary_frame(self, alpha=0.05):
# TODO: finish and cleanup
ci_obs = self.conf_int(alpha=alpha, obs=True) # need to split
ci_mean = self.conf_int(alpha=alpha, obs=False)
to_include = {}
to_include['mean'] = self.predicted_mean
to_include['mean_se'] = self.se_mean
to_include['mean_ci_lower'] = ci_mean[:, 0]
to_include['mean_ci_upper'] = ci_mean[:, 1]
to_include['obs_ci_lower'] = ci_obs[:, 0]
to_include['obs_ci_upper'] = ci_obs[:, 1]
self.table = to_include
# pandas dict does not handle 2d_array
# data = np.column_stack(list(to_include.values()))
# names = ....
res = pd.DataFrame(to_include, index=self.row_labels,
columns=to_include.keys())
return res
def get_prediction(self, exog=None, transform=True, weights=None,
row_labels=None, pred_kwds=None):
"""
Compute prediction results.
Parameters
----------
exog : array_like, optional
The values for which you want to predict.
transform : bool, optional
If the model was fit via a formula, do you want to pass
exog through the formula. Default is True. E.g., if you fit
a model y ~ log(x1) + log(x2), and transform is True, then
you can pass a data structure that contains x1 and x2 in
their original form. Otherwise, you'd need to log the data
first.
weights : array_like, optional
Weights interpreted as in WLS, used for the variance of the predicted
residual.
row_labels : list
A list of row labels to use. If not provided, read `exog` is
available.
**kwargs
Some models can take additional keyword arguments, see the predict
method of the model for the details.
Returns
-------
linear_model.PredictionResults
The prediction results instance contains prediction and prediction
variance and can on demand calculate confidence intervals and summary
tables for the prediction of the mean and of new observations.
"""
# prepare exog and row_labels, based on base Results.predict
if transform and hasattr(self.model, 'formula') and exog is not None:
from patsy import dmatrix
if isinstance(exog, pd.Series):
# GH-6509
exog = pd.DataFrame(exog)
exog = dmatrix(self.model.data.design_info, exog)
if exog is not None:
if row_labels is None:
row_labels = getattr(exog, 'index', None)
if callable(row_labels):
row_labels = None
exog = np.asarray(exog)
if exog.ndim == 1:
# Params informs whether a row or column vector
if self.params.shape[0] > 1:
exog = exog[None, :]
else:
exog = exog[:, None]
exog = np.atleast_2d(exog) # needed in count model shape[1]
else:
exog = self.model.exog
if weights is None:
weights = getattr(self.model, 'weights', None)
if row_labels is None:
row_labels = getattr(self.model.data, 'row_labels', None)
# need to handle other arrays, TODO: is delegating to model possible ?
if weights is not None:
weights = np.asarray(weights)
if (weights.size > 1 and
(weights.ndim != 1 or weights.shape[0] == exog.shape[1])):
raise ValueError('weights has wrong shape')
if pred_kwds is None:
pred_kwds = {}
predicted_mean = self.model.predict(self.params, exog, **pred_kwds)
covb = self.cov_params()
var_pred_mean = (exog * np.dot(covb, exog.T).T).sum(1)
var_resid = self.scale # self.mse_resid / weights
# TODO: check that we have correct scale, Refactor scale #???
# special case for now:
if self.cov_type == 'fixed scale':
var_resid = self.cov_kwds['scale']
if weights is not None:
var_resid /= weights
dist = ['norm', 't'][self.use_t]
return PredictionResults(predicted_mean, var_pred_mean, var_resid,
df=self.df_resid, dist=dist,
row_labels=row_labels)
| bsd-3-clause | f41428f736cd02f238073fd03bbd3042 | 31.662037 | 77 | 0.588094 | 3.963483 | false | false | false | false |
statsmodels/statsmodels | statsmodels/genmod/tests/results/glmnet_r_results.py | 6 | 1926 | import numpy as np
rslt_binomial_0 = np.array([
0, 6.618737, 0.004032037, 0.01433665, 0.01265635, 0.006173346, 0.01067706])
rslt_binomial_1 = np.array([
0, 1.029661, 0.02180239, 0.07769613, 0.06756466, 0.03156418, 0.05851878])
rslt_binomial_2 = np.array([
0, 0.1601819, 0.07111087, 0.2544921, 0.2110318, 0.08577924, 0.1984383])
rslt_binomial_3 = np.array([
0.5, 0.05343991, 0.004990061, 0.2838563, 0.2167881, 0.02370156, 0.2096612])
rslt_binomial_4 = np.array([
0.5, 0.02313286, 0.0708914, 0.3791042, 0.2938332, 0.07506391, 0.2982251])
rslt_binomial_5 = np.array([
0.5, 0.009124078, 0.106681, 0.4327268, 0.3362166, 0.1019452, 0.3479955])
rslt_binomial_6 = np.array([
1, 0.02932512, 0, 0.3085764, 0.2300801, 0.01143652, 0.2291531])
rslt_binomial_7 = np.array([
1, 0.01269414, 0.07022348, 0.396642, 0.3044255, 0.07151663, 0.31301])
rslt_binomial_8 = np.array([
1, 0.005494992, 0.1049623, 0.4385186, 0.3391729, 0.09907393, 0.3527401])
rslt_poisson_0 = np.array([
0, 23.5349, 0.009251658, 0.003730997, 0.01266164, 0.003439135, 0.0141719])
rslt_poisson_1 = np.array([
0, 3.661269, 0.04842557, 0.02095708, 0.06550316, 0.02029514, 0.07300782])
rslt_poisson_2 = np.array([
0, 0.5695749, 0.1440462, 0.07208017, 0.182649, 0.07511376, 0.2018242])
rslt_poisson_3 = np.array([
0.5, 0.1577593, 0.1247603, 0.02857521, 0.185693, 0.03840622, 0.2200925])
rslt_poisson_4 = np.array([
0.5, 0.05669575, 0.187629, 0.08842012, 0.2348627, 0.09736964, 0.2628845])
rslt_poisson_5 = np.array([
0.5, 0.0185653, 0.2118078, 0.1121067, 0.2534181, 0.1204543, 0.2784761])
rslt_poisson_6 = np.array([
1, 0.07887965, 0.1339927, 0.0322772, 0.1969884, 0.0439019, 0.2339252])
rslt_poisson_7 = np.array([
1, 0.02834788, 0.1927163, 0.09160406, 0.2398164, 0.1010126, 0.2682158])
rslt_poisson_8 = np.array([
1, 0.0101877, 0.2126847, 0.1123439, 0.2544153, 0.1208601, 0.2796794])
| bsd-3-clause | d08b333712148a0dbc467e94849f8014 | 34.018182 | 79 | 0.668224 | 1.997925 | false | false | true | false |
statsmodels/statsmodels | statsmodels/examples/ex_kernel_singleindex_dgp.py | 6 | 3400 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 06 09:50:54 2013
Author: Josef Perktold
"""
if __name__ == '__main__':
import numpy as np
import matplotlib.pyplot as plt
#from statsmodels.nonparametric.api import KernelReg
import statsmodels.sandbox.nonparametric.kernel_extras as smke
import statsmodels.sandbox.nonparametric.dgp_examples as dgp
class UnivariateFunc1a(dgp.UnivariateFunc1):
def het_scale(self, x):
return 0.5
seed = np.random.randint(999999)
#seed = 430973
#seed = 47829
seed = 648456 #good seed for het_scale = 0.5
print(seed)
np.random.seed(seed)
nobs, k_vars = 300, 3
x = np.random.uniform(-2, 2, size=(nobs, k_vars))
xb = x.sum(1) / 3 #beta = [1,1,1]
funcs = [#dgp.UnivariateFanGijbels1(),
#dgp.UnivariateFanGijbels2(),
#dgp.UnivariateFanGijbels1EU(),
#dgp.UnivariateFanGijbels2(distr_x=stats.uniform(-2, 4))
UnivariateFunc1a(x=xb)
]
res = []
fig = plt.figure()
for i,func in enumerate(funcs):
#f = func()
f = func
# mod0 = smke.SingleIndexModel(endog=[f.y], exog=[xb], #reg_type='ll',
# var_type='c')#, bw='cv_ls')
# mean0, mfx0 = mod0.fit()
model = smke.SingleIndexModel(endog=[f.y], exog=x, #reg_type='ll',
var_type='ccc')#, bw='cv_ls')
mean, mfx = model.fit()
ax = fig.add_subplot(1, 1, i+1)
f.plot(ax=ax)
xb_est = np.dot(model.exog, model.b)
sortidx = np.argsort(xb_est) #f.x)
ax.plot(f.x[sortidx], mean[sortidx], 'o', color='r', lw=2, label='est. mean')
# ax.plot(f.x, mean0, color='g', lw=2, label='est. mean')
ax.legend(loc='upper left')
res.append((model, mean, mfx))
fig.suptitle('Kernel Regression')
fig.show()
alpha = 0.7
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(f.x[sortidx], f.y[sortidx], 'o', color='b', lw=2, alpha=alpha, label='observed')
ax.plot(f.x[sortidx], f.y_true[sortidx], 'o', color='g', lw=2, alpha=alpha, label='dgp. mean')
ax.plot(f.x[sortidx], mean[sortidx], 'o', color='r', lw=2, alpha=alpha, label='est. mean')
ax.legend(loc='upper left')
fig = plt.figure()
# ax = fig.add_subplot(1, 2, 1)
# ax.plot(f.x, f.y, 'o', color='b', lw=2, alpha=alpha, label='observed')
# ax.plot(f.x, f.y_true, 'o', color='g', lw=2, alpha=alpha, label='dgp. mean')
# ax.plot(f.x, mean, 'o', color='r', lw=2, alpha=alpha, label='est. mean')
# ax.legend(loc='upper left')
sortidx0 = np.argsort(xb)
ax = fig.add_subplot(1, 2, 1)
ax.plot(f.y[sortidx0], 'o', color='b', lw=2, alpha=alpha, label='observed')
ax.plot(f.y_true[sortidx0], 'o', color='g', lw=2, alpha=alpha, label='dgp. mean')
ax.plot(mean[sortidx0], 'o', color='r', lw=2, alpha=alpha, label='est. mean')
ax.legend(loc='upper left')
ax.set_title('Single Index Model (sorted by true xb)')
ax = fig.add_subplot(1, 2, 2)
ax.plot(f.y[sortidx], 'o', color='b', lw=2, alpha=alpha, label='observed')
ax.plot(f.y_true[sortidx], 'o', color='g', lw=2, alpha=alpha, label='dgp. mean')
ax.plot(mean[sortidx], 'o', color='r', lw=2, alpha=alpha, label='est. mean')
ax.legend(loc='upper left')
ax.set_title('Single Index Model (sorted by estimated xb)')
plt.show()
| bsd-3-clause | e6c20874055bd20808ebc91bd5c1dc16 | 35.956522 | 98 | 0.577059 | 2.709163 | false | false | false | false |
statsmodels/statsmodels | statsmodels/regression/tests/results/lme_r_results.py | 6 | 15667 | import numpy as np
coef_ml_drf_0 = np.array([-0.9887517])
vcov_ml_drf_0 = np.array([0.001317148]).reshape(1, 1, order='F')
cov_re_ml_drf_0 = np.array([0.2522485]).reshape(1, 1, order='F')
scale_ml_drf_0 = np.array([0.2718486])
loglike_ml_drf_0 = np.array([-240.1254])
ranef_mean_ml_drf_0 = np.array([0.04977167])
ranef_condvar_ml_drf_0 = np.array([0.130841])
coef_reml_drf_0 = np.array([-0.9887533])
vcov_reml_drf_0 = np.array([0.001323559]).reshape(1, 1, order='F')
cov_re_reml_drf_0 = np.array([0.2524129]).reshape(1, 1, order='F')
scale_reml_drf_0 = np.array([0.2733467])
loglike_reml_drf_0 = np.array([-242.5214])
ranef_mean_reml_drf_0 = np.array([0.04964696])
ranef_condvar_reml_drf_0 = np.array([0.1312315])
coef_ml_drf_1 = np.array([-0.9115929])
vcov_ml_drf_1 = np.array([0.01340632]).reshape(1, 1, order='F')
cov_re_ml_drf_1 = np.array([0]).reshape(1, 1, order='F')
scale_ml_drf_1 = np.array([4.050921])
loglike_ml_drf_1 = np.array([-538.0763])
ranef_mean_ml_drf_1 = np.array([0])
ranef_condvar_ml_drf_1 = np.array([0])
coef_reml_drf_1 = np.array([-0.9115929])
vcov_reml_drf_1 = np.array([0.01345931]).reshape(1, 1, order='F')
cov_re_reml_drf_1 = np.array([2.839777e-14]).reshape(1, 1, order='F')
scale_reml_drf_1 = np.array([4.066932])
loglike_reml_drf_1 = np.array([-539.3124])
ranef_mean_reml_drf_1 = np.array([2.424384e-14])
ranef_condvar_reml_drf_1 = np.array([2.839777e-14])
coef_ml_drf_2 = np.array([-1.012044, 0.9789052])
vcov_ml_drf_2 = np.array([
0.00117849, 1.458744e-05,
1.458744e-05, 0.001054926]).reshape(2, 2, order='F')
cov_re_ml_drf_2 = np.array([0.1596058]).reshape(1, 1, order='F')
scale_ml_drf_2 = np.array([0.2129146])
loglike_ml_drf_2 = np.array([-200.319])
ranef_mean_ml_drf_2 = np.array([0.3197174])
ranef_condvar_ml_drf_2 = np.array([0.09122291])
coef_reml_drf_2 = np.array([-1.012137, 0.9790792])
vcov_reml_drf_2 = np.array([
0.001190455, 1.482666e-05,
1.482666e-05, 0.001066002]).reshape(2, 2, order='F')
cov_re_reml_drf_2 = np.array([0.1595015]).reshape(1, 1, order='F')
scale_reml_drf_2 = np.array([0.2154276])
loglike_reml_drf_2 = np.array([-205.275])
ranef_mean_reml_drf_2 = np.array([0.3172978])
ranef_condvar_reml_drf_2 = np.array([0.09164674])
coef_ml_drf_3 = np.array([-1.028053, 0.8602685])
vcov_ml_drf_3 = np.array([
0.01398831, 0.001592619, 0.001592619, 0.01602274]).reshape(2, 2, order='F')
cov_re_ml_drf_3 = np.array([0.8130996]).reshape(1, 1, order='F')
scale_ml_drf_3 = np.array([3.100447])
loglike_ml_drf_3 = np.array([-477.1707])
ranef_mean_ml_drf_3 = np.array([-0.2641747])
ranef_condvar_ml_drf_3 = np.array([0.6441656])
coef_reml_drf_3 = np.array([-1.027583, 0.8605714])
vcov_reml_drf_3 = np.array([
0.01411922, 0.001607343, 0.001607343, 0.01617574]).reshape(2, 2, order='F')
cov_re_reml_drf_3 = np.array([0.8117898]).reshape(1, 1, order='F')
scale_reml_drf_3 = np.array([3.13369])
loglike_reml_drf_3 = np.array([-479.5354])
ranef_mean_reml_drf_3 = np.array([-0.2614875])
ranef_condvar_reml_drf_3 = np.array([0.6447625])
coef_ml_drf_4 = np.array([-1.005151, -0.003657404, 1.054786])
vcov_ml_drf_4 = np.array([
0.001190639, -5.327162e-05, 5.992985e-05, -5.327162e-05,
0.001460303, -2.662532e-05, 5.992985e-05, -2.662532e-05,
0.00148609]).reshape(3, 3, order='F')
cov_re_ml_drf_4 = np.array([0.1703249]).reshape(1, 1, order='F')
scale_ml_drf_4 = np.array([0.251763])
loglike_ml_drf_4 = np.array([-231.6389])
ranef_mean_ml_drf_4 = np.array([-0.2063164])
ranef_condvar_ml_drf_4 = np.array([0.0459578])
coef_reml_drf_4 = np.array([-1.005067, -0.003496032, 1.054666])
vcov_reml_drf_4 = np.array([
0.001206925, -5.4182e-05, 6.073475e-05, -5.4182e-05,
0.001479871, -2.723494e-05, 6.073475e-05, -2.723494e-05,
0.001506198]).reshape(3, 3, order='F')
cov_re_reml_drf_4 = np.array([0.1705659]).reshape(1, 1, order='F')
scale_reml_drf_4 = np.array([0.2556394])
loglike_reml_drf_4 = np.array([-238.761])
ranef_mean_reml_drf_4 = np.array([-0.2055303])
ranef_condvar_reml_drf_4 = np.array([0.04649027])
coef_ml_drf_5 = np.array([-0.8949725, 0.08141558, 1.052529])
vcov_ml_drf_5 = np.array([
0.01677563, 0.0008077524, -0.001255011, 0.0008077524,
0.01719346, 0.0009266736, -0.001255011, 0.0009266736,
0.01608435]).reshape(3, 3, order='F')
cov_re_ml_drf_5 = np.array([0.3444677]).reshape(1, 1, order='F')
scale_ml_drf_5 = np.array([4.103944])
loglike_ml_drf_5 = np.array([-579.4568])
ranef_mean_ml_drf_5 = np.array([0.08254713])
ranef_condvar_ml_drf_5 = np.array([0.3177935])
coef_reml_drf_5 = np.array([-0.8946164, 0.08134261, 1.052486])
vcov_reml_drf_5 = np.array([
0.0169698, 0.0008162714, -0.001268635, 0.0008162714,
0.01739219, 0.0009345538, -0.001268635, 0.0009345538,
0.01627074]).reshape(3, 3, order='F')
cov_re_reml_drf_5 = np.array([0.3420993]).reshape(1, 1, order='F')
scale_reml_drf_5 = np.array([4.155737])
loglike_reml_drf_5 = np.array([-582.8377])
ranef_mean_reml_drf_5 = np.array([0.08111449])
ranef_condvar_reml_drf_5 = np.array([0.3160797])
coef_ml_drf_6 = np.array([-0.8885425])
vcov_ml_drf_6 = np.array([0.002443738]).reshape(1, 1, order='F')
cov_re_ml_drf_6 = np.array([
0.2595201, 0.04591071,
0.04591071, 2.204612]).reshape(2, 2, order='F')
scale_ml_drf_6 = np.array([0.243133])
loglike_ml_drf_6 = np.array([-382.551])
ranef_mean_ml_drf_6 = np.array([-0.0597406, 0.6037288])
ranef_condvar_ml_drf_6 = np.array([
0.2420741, 0.2222169,
0.2222169, 0.4228908]).reshape(2, 2, order='F')
coef_reml_drf_6 = np.array([-0.8883881])
vcov_reml_drf_6 = np.array([0.002461581]).reshape(1, 1, order='F')
cov_re_reml_drf_6 = np.array([
0.2595767, 0.04590012,
0.04590012, 2.204822]).reshape(2, 2, order='F')
scale_reml_drf_6 = np.array([0.2453537])
loglike_reml_drf_6 = np.array([-384.6373])
ranef_mean_reml_drf_6 = np.array([-0.05969892, 0.6031793])
ranef_condvar_reml_drf_6 = np.array([
0.2421365, 0.2221108,
0.2221108, 0.4244443]).reshape(2, 2, order='F')
coef_ml_irf_6 = np.array([-0.8874992])
vcov_ml_irf_6 = np.array([0.002445505]).reshape(1, 1, order='F')
cov_re_ml_irf_6 = np.array([
0.2587624, 0,
0, 2.188653]).reshape(2, 2, order='F')
scale_ml_irf_6 = np.array([0.2432694])
loglike_ml_irf_6 = np.array([-382.6581])
coef_reml_irf_6 = np.array([-0.8873394])
vcov_reml_irf_6 = np.array([0.002463375]).reshape(1, 1, order='F')
cov_re_reml_irf_6 = np.array([
0.2588157, 0,
0, 2.188876]).reshape(2, 2, order='F')
scale_reml_irf_6 = np.array([0.2454935])
loglike_reml_irf_6 = np.array([-384.7441])
coef_ml_drf_7 = np.array([-0.9645281])
vcov_ml_drf_7 = np.array([0.01994]).reshape(1, 1, order='F')
cov_re_ml_drf_7 = np.array([
0.2051329, 0.0734377,
0.0734377, 3.285381]).reshape(2, 2, order='F')
scale_ml_drf_7 = np.array([3.423247])
loglike_ml_drf_7 = np.array([-587.7101])
ranef_mean_ml_drf_7 = np.array([0.07007965, -0.2920284])
ranef_condvar_ml_drf_7 = np.array([
0.1823183, 0.02247519,
0.02247519, 1.125011]).reshape(2, 2, order='F')
coef_reml_drf_7 = np.array([-0.9647862])
vcov_reml_drf_7 = np.array([0.02002546]).reshape(1, 1, order='F')
cov_re_reml_drf_7 = np.array([
0.2056226, 0.0726139,
0.0726139, 3.2876]).reshape(2, 2, order='F')
scale_reml_drf_7 = np.array([3.440244])
loglike_reml_drf_7 = np.array([-588.7476])
ranef_mean_reml_drf_7 = np.array([0.07000628, -0.2916737])
ranef_condvar_reml_drf_7 = np.array([
0.1828266, 0.02229138,
0.02229138, 1.128947]).reshape(2, 2, order='F')
coef_ml_irf_7 = np.array([-0.9665524])
vcov_ml_irf_7 = np.array([0.01998144]).reshape(1, 1, order='F')
cov_re_ml_irf_7 = np.array([
0.2021561, 0, 0, 3.270735]).reshape(2, 2, order='F')
scale_ml_irf_7 = np.array([3.423186])
loglike_ml_irf_7 = np.array([-587.7456])
coef_reml_irf_7 = np.array([-0.9667854])
vcov_reml_irf_7 = np.array([0.02006657]).reshape(1, 1, order='F')
cov_re_reml_irf_7 = np.array([
0.2026938, 0, 0, 3.273129]).reshape(2, 2, order='F')
scale_reml_irf_7 = np.array([3.440197])
loglike_reml_irf_7 = np.array([-588.782])
coef_ml_drf_8 = np.array([-1.083882, 0.8955623])
vcov_ml_drf_8 = np.array([
0.002491643, 0.0001693531,
0.0001693531, 0.00253309]).reshape(2, 2, order='F')
cov_re_ml_drf_8 = np.array([
0.1506188, 0.126091, 0.126091, 2.485462]).reshape(2, 2, order='F')
scale_ml_drf_8 = np.array([0.2586519])
loglike_ml_drf_8 = np.array([-363.6234])
ranef_mean_ml_drf_8 = np.array([0.2852326, -0.5047804])
ranef_condvar_ml_drf_8 = np.array([
0.05400391, 0.002330104,
0.002330104, 0.122761]).reshape(2, 2, order='F')
coef_reml_drf_8 = np.array([-1.083938, 0.8956893])
vcov_reml_drf_8 = np.array([
0.002528969, 0.0001712206,
0.0001712206, 0.002573335]).reshape(2, 2, order='F')
cov_re_reml_drf_8 = np.array([
0.1505098, 0.1256311,
0.1256311, 2.484219]).reshape(2, 2, order='F')
scale_reml_drf_8 = np.array([0.2635901])
loglike_reml_drf_8 = np.array([-367.7667])
ranef_mean_reml_drf_8 = np.array([0.2829798, -0.5042857])
ranef_condvar_reml_drf_8 = np.array([
0.05463632, 0.002393538,
0.002393538, 0.1249828]).reshape(2, 2, order='F')
coef_ml_irf_8 = np.array([-1.079481, 0.898216])
vcov_ml_irf_8 = np.array([
0.002511536, 0.0001812511,
0.0001812511, 0.002573405]).reshape(2, 2, order='F')
cov_re_ml_irf_8 = np.array([
0.1498568, 0, 0, 2.403849]).reshape(2, 2, order='F')
scale_ml_irf_8 = np.array([0.2605245])
loglike_ml_irf_8 = np.array([-364.4824])
coef_reml_irf_8 = np.array([-1.07952, 0.8983678])
vcov_reml_irf_8 = np.array([
0.002549354, 0.0001833386,
0.0001833386, 0.002614672]).reshape(2, 2, order='F')
cov_re_reml_irf_8 = np.array([
0.1497193, 0, 0, 2.403076]).reshape(2, 2, order='F')
scale_reml_irf_8 = np.array([0.2655558])
loglike_reml_irf_8 = np.array([-368.6141])
coef_ml_drf_9 = np.array([-1.272698, 0.8617471])
vcov_ml_drf_9 = np.array([
0.02208544, 0.001527479, 0.001527479, 0.02597528]).reshape(2, 2, order='F')
cov_re_ml_drf_9 = np.array([
0.510175, 0.08826114, 0.08826114, 3.342888]).reshape(2, 2, order='F')
scale_ml_drf_9 = np.array([3.722112])
loglike_ml_drf_9 = np.array([-589.8274])
ranef_mean_ml_drf_9 = np.array([0.03253644, 0.224043])
ranef_condvar_ml_drf_9 = np.array([
0.3994872, 0.02478884, 0.02478884, 1.195077]).reshape(2, 2, order='F')
coef_reml_drf_9 = np.array([-1.272483, 0.861814])
vcov_reml_drf_9 = np.array([
0.02228589, 0.001535598, 0.001535598, 0.0262125]).reshape(2, 2, order='F')
cov_re_reml_drf_9 = np.array([
0.5123204, 0.08897376, 0.08897376, 3.341722]).reshape(2, 2, order='F')
scale_reml_drf_9 = np.array([3.764058])
loglike_reml_drf_9 = np.array([-591.7188])
ranef_mean_reml_drf_9 = np.array([0.03239688, 0.2230525])
ranef_condvar_reml_drf_9 = np.array([
0.401762, 0.02521271, 0.02521271, 1.203536]).reshape(2, 2, order='F')
coef_ml_irf_9 = np.array([-1.277018, 0.86395])
vcov_ml_irf_9 = np.array([
0.02205706, 0.001509887, 0.001509887, 0.02599941]).reshape(2, 2, order='F')
cov_re_ml_irf_9 = np.array([
0.5086816, 0, 0, 3.312757]).reshape(2, 2, order='F')
scale_ml_irf_9 = np.array([3.72105])
loglike_ml_irf_9 = np.array([-589.8628])
coef_reml_irf_9 = np.array([-1.276822, 0.8640243])
vcov_reml_irf_9 = np.array([
0.02225705, 0.001517774, 0.001517774, 0.02623682]).reshape(2, 2, order='F')
cov_re_reml_irf_9 = np.array([
0.5107725, 0, 0, 3.31152]).reshape(2, 2, order='F')
scale_reml_irf_9 = np.array([3.762967])
loglike_reml_irf_9 = np.array([-591.7543])
coef_ml_drf_10 = np.array([-0.9419566, -0.02359824, 1.085796])
vcov_ml_drf_10 = np.array([
0.001963536, -0.0003221793, 0.0001950186, -0.0003221793,
0.002534251, 0.0004107718, 0.0001950186, 0.0004107718,
0.002580736]).reshape(3, 3, order='F')
cov_re_ml_drf_10 = np.array([
0.2040541, 0.09038325, 0.09038325, 2.218903]).reshape(2, 2, order='F')
scale_ml_drf_10 = np.array([0.2558286])
loglike_ml_drf_10 = np.array([-379.6591])
ranef_mean_ml_drf_10 = np.array([0.03876325, -0.725853])
ranef_condvar_ml_drf_10 = np.array([
0.1988816, 0.1872403, 0.1872403, 0.4052274]).reshape(2, 2, order='F')
coef_reml_drf_10 = np.array([-0.9426367, -0.02336203, 1.085733])
vcov_reml_drf_10 = np.array([
0.002011348, -0.0003300612, 0.0002002948, -0.0003300612,
0.002589149, 0.000418987, 0.0002002948, 0.000418987,
0.002637433]).reshape(3, 3, order='F')
cov_re_reml_drf_10 = np.array([
0.2034827, 0.09063836, 0.09063836, 2.219191]).reshape(2, 2, order='F')
scale_reml_drf_10 = np.array([0.2630213])
loglike_reml_drf_10 = np.array([-386.0008])
ranef_mean_reml_drf_10 = np.array([0.03838686, -0.7240812])
ranef_condvar_reml_drf_10 = np.array([
0.1983981, 0.1865469, 0.1865469, 0.4100937]).reshape(2, 2, order='F')
coef_ml_irf_10 = np.array([-0.9441033, -0.01755913, 1.088568])
vcov_ml_irf_10 = np.array([
0.001960114, -0.0003215658, 0.0001944005, -0.0003215658,
0.00253441, 0.0004061179, 0.0001944005, 0.0004061179,
0.002589158]).reshape(3, 3, order='F')
cov_re_ml_irf_10 = np.array([
0.2032228, 0, 0, 2.192893]).reshape(2, 2, order='F')
scale_ml_irf_10 = np.array([0.2553399])
loglike_ml_irf_10 = np.array([-380.162])
coef_reml_irf_10 = np.array([-0.9448257, -0.01722993, 1.088557])
vcov_reml_irf_10 = np.array([
0.00200783, -0.0003294349, 0.0001996613, -0.0003294349,
0.00258937, 0.0004141667, 0.0001996613, 0.0004141667,
0.002646242]).reshape(3, 3, order='F')
cov_re_reml_irf_10 = np.array([
0.2026653, 0, 0, 2.193124]).reshape(2, 2, order='F')
scale_reml_irf_10 = np.array([0.2625147])
loglike_reml_irf_10 = np.array([-386.5024])
coef_ml_drf_11 = np.array([-1.36971, 0.1596278, 0.8588724])
vcov_ml_drf_11 = np.array([
0.0232326, 0.00172214, 0.002275343, 0.00172214,
0.02318941, 0.0004755663, 0.002275343, 0.0004755663,
0.02123474]).reshape(3, 3, order='F')
cov_re_ml_drf_11 = np.array([
0.3719096, 0.332198, 0.332198, 1.120588]).reshape(2, 2, order='F')
scale_ml_drf_11 = np.array([4.849781])
loglike_ml_drf_11 = np.array([-601.6432])
ranef_mean_ml_drf_11 = np.array([-0.4256917, -0.3907759])
ranef_condvar_ml_drf_11 = np.array([
0.2987928, 0.1992074, 0.1992074, 0.7477486]).reshape(2, 2, order='F')
coef_reml_drf_11 = np.array([-1.370236, 0.1597671, 0.8585994])
vcov_reml_drf_11 = np.array([
0.02351795, 0.001749756, 0.002301599, 0.001749756,
0.02346869, 0.0004785668, 0.002301599, 0.0004785668,
0.02149093]).reshape(3, 3, order='F')
cov_re_reml_drf_11 = np.array([
0.3680346, 0.3324419, 0.3324419, 1.118623]).reshape(2, 2, order='F')
scale_reml_drf_11 = np.array([4.922222])
loglike_reml_drf_11 = np.array([-604.5746])
ranef_mean_reml_drf_11 = np.array([-0.4168539, -0.3879533])
ranef_condvar_reml_drf_11 = np.array([
0.2965372, 0.2010191, 0.2010191, 0.7503986]).reshape(2, 2, order='F')
coef_ml_irf_11 = np.array([-1.370117, 0.1414964, 0.8466083])
vcov_ml_irf_11 = np.array([
0.02319951, 0.001705996, 0.002265252, 0.001705996,
0.02345623, 0.000514879, 0.002265252, 0.000514879,
0.02153162]).reshape(3, 3, order='F')
cov_re_ml_irf_11 = np.array([
0.4004789, 0, 0, 1.108087]).reshape(2, 2, order='F')
scale_ml_irf_11 = np.array([4.78776])
loglike_ml_irf_11 = np.array([-602.308])
coef_reml_irf_11 = np.array([-1.370663, 0.1417561, 0.8464232])
vcov_reml_irf_11 = np.array([
0.02348548, 0.001734072, 0.002291519, 0.001734072,
0.02373715, 0.0005177618, 0.002291519, 0.0005177618,
0.02178966]).reshape(3, 3, order='F')
cov_re_reml_irf_11 = np.array([
0.3966454, 0, 0, 1.106551]).reshape(2, 2, order='F')
scale_reml_irf_11 = np.array([4.860342])
loglike_reml_irf_11 = np.array([-605.2274])
| bsd-3-clause | 771ea7896656a34934c9179356f32110 | 26.976786 | 79 | 0.644986 | 1.994526 | false | false | true | false |
statsmodels/statsmodels | statsmodels/tools/linalg.py | 5 | 4805 | """
Linear Algebra solvers and other helpers
"""
import numpy as np
__all__ = ["logdet_symm", "stationary_solve", "transf_constraints",
"matrix_sqrt"]
def logdet_symm(m, check_symm=False):
"""
Return log(det(m)) asserting positive definiteness of m.
Parameters
----------
m : array_like
2d array that is positive-definite (and symmetric)
Returns
-------
logdet : float
The log-determinant of m.
"""
from scipy import linalg
if check_symm:
if not np.all(m == m.T): # would be nice to short-circuit check
raise ValueError("m is not symmetric.")
c, _ = linalg.cho_factor(m, lower=True)
return 2*np.sum(np.log(c.diagonal()))
def stationary_solve(r, b):
"""
Solve a linear system for a Toeplitz correlation matrix.
A Toeplitz correlation matrix represents the covariance of a
stationary series with unit variance.
Parameters
----------
r : array_like
A vector describing the coefficient matrix. r[0] is the first
band next to the diagonal, r[1] is the second band, etc.
b : array_like
The right-hand side for which we are solving, i.e. we solve
Tx = b and return b, where T is the Toeplitz coefficient matrix.
Returns
-------
The solution to the linear system.
"""
db = r[0:1]
dim = b.ndim
if b.ndim == 1:
b = b[:, None]
x = b[0:1, :]
for j in range(1, len(b)):
rf = r[0:j][::-1]
a = (b[j, :] - np.dot(rf, x)) / (1 - np.dot(rf, db[::-1]))
z = x - np.outer(db[::-1], a)
x = np.concatenate((z, a[None, :]), axis=0)
if j == len(b) - 1:
break
rn = r[j]
a = (rn - np.dot(rf, db)) / (1 - np.dot(rf, db[::-1]))
z = db - a*db[::-1]
db = np.concatenate((z, np.r_[a]))
if dim == 1:
x = x[:, 0]
return x
def transf_constraints(constraints):
"""use QR to get transformation matrix to impose constraint
Parameters
----------
constraints : ndarray, 2-D
restriction matrix with one constraints in rows
Returns
-------
transf : ndarray
transformation matrix to reparameterize so that constraint is
imposed
Notes
-----
This is currently and internal helper function for GAM.
API not stable and will most likely change.
The code for this function was taken from patsy spline handling, and
corresponds to the reparameterization used by Wood in R's mgcv package.
See Also
--------
statsmodels.base._constraints.TransformRestriction : class to impose
constraints by reparameterization used by `_fit_constrained`.
"""
from scipy import linalg
m = constraints.shape[0]
q, _ = linalg.qr(np.transpose(constraints))
transf = q[:, m:]
return transf
def matrix_sqrt(mat, inverse=False, full=False, nullspace=False,
threshold=1e-15):
"""matrix square root for symmetric matrices
Usage is for decomposing a covariance function S into a square root R
such that
R' R = S if inverse is False, or
R' R = pinv(S) if inverse is True
Parameters
----------
mat : array_like, 2-d square
symmetric square matrix for which square root or inverse square
root is computed.
There is no checking for whether the matrix is symmetric.
A warning is issued if some singular values are negative, i.e.
below the negative of the threshold.
inverse : bool
If False (default), then the matrix square root is returned.
If inverse is True, then the matrix square root of the inverse
matrix is returned.
full : bool
If full is False (default, then the square root has reduce number
of rows if the matrix is singular, i.e. has singular values below
the threshold.
nullspace : bool
If nullspace is true, then the matrix square root of the null space
of the matrix is returned.
threshold : float
Singular values below the threshold are dropped.
Returns
-------
msqrt : ndarray
matrix square root or square root of inverse matrix.
"""
# see also scipy.linalg null_space
u, s, v = np.linalg.svd(mat)
if np.any(s < -threshold):
import warnings
warnings.warn('some singular values are negative')
if not nullspace:
mask = s > threshold
s[s < threshold] = 0
else:
mask = s < threshold
s[s > threshold] = 0
sqrt_s = np.sqrt(s[mask])
if inverse:
sqrt_s = 1 / np.sqrt(s[mask])
if full:
b = np.dot(u[:, mask], np.dot(np.diag(sqrt_s), v[mask]))
else:
b = np.dot(np.diag(sqrt_s), v[mask])
return b
| bsd-3-clause | 27bcdfa9382ad98b456dc807791d1026 | 26.614943 | 75 | 0.593548 | 3.847078 | false | false | false | false |
statsmodels/statsmodels | statsmodels/genmod/tests/gee_poisson_simulation_check.py | 3 | 9115 | """
Assesment of Generalized Estimating Equations using simulation.
This script checks Poisson models.
See the generated file "gee_poisson_simulation_check.txt" for results.
"""
import numpy as np
from statsmodels.genmod.families import Poisson
from .gee_gaussian_simulation_check import GEE_simulator
from statsmodels.genmod.generalized_estimating_equations import GEE
from statsmodels.genmod.cov_struct import Exchangeable,Independence
class Exchangeable_simulator(GEE_simulator):
"""
Simulate exchangeable Poisson data.
The data within a cluster are simulated as y_i = z_c + z_i. The
z_c, and {z_i} are independent Poisson random variables with
expected values e_c and {e_i}, respectively. In order for the
pairwise correlation to be equal to `f` for all pairs, we need
e_c / sqrt((e_c + e_i) * (e_c + e_j)) = f for all i, j.
By setting all e_i = e within a cluster, these equations can be
satisfied. We thus need
e_c * (1 - f) = f * e,
which can be solved (non-uniquely) for e and e_c.
"""
scale_inv = 1.
def print_dparams(self, dparams_est):
OUT.write("Estimated common pairwise correlation: %8.4f\n" %
dparams_est[0])
OUT.write("True common pairwise correlation: %8.4f\n" %
self.dparams[0])
OUT.write("Estimated inverse scale parameter: %8.4f\n" %
dparams_est[1])
OUT.write("True inverse scale parameter: %8.4f\n" %
self.scale_inv)
OUT.write("\n")
def simulate(self):
endog, exog, group, time = [], [], [], []
# Get a basis for the orthogonal complement to params.
f = np.sum(self.params**2)
u,s,vt = np.linalg.svd(np.eye(len(self.params)) -
np.outer(self.params, self.params) / f)
params0 = u[:,np.flatnonzero(s > 1e-6)]
for i in range(self.ngroups):
gsize = np.random.randint(self.group_size_range[0],
self.group_size_range[1])
group.append([i,] * gsize)
time1 = np.random.normal(size=(gsize, 2))
time.append(time1)
e_c = np.random.uniform(low=1, high=10)
e = e_c * (1 - self.dparams[0]) / self.dparams[0]
common = np.random.poisson(e_c)
unique = np.random.poisson(e, gsize)
endog1 = common + unique
endog.append(endog1)
lpr = np.log(e_c + e) * np.ones(gsize)
# Create an exog matrix so that E[Y] = log(dot(exog1, params))
exog1 = np.outer(lpr, self.params) / np.sum(self.params**2)
emat = np.random.normal(size=(len(lpr), params0.shape[1]))
exog1 += np.dot(emat, params0.T)
exog.append(exog1)
self.exog = np.concatenate(exog, axis=0)
self.endog = np.concatenate(endog)
self.time = np.concatenate(time, axis=0)
self.group = np.concatenate(group)
class Overdispersed_simulator(GEE_simulator):
"""
Use the negative binomial distribution to check GEE estimation
using the overdispered Poisson model with independent dependence.
Simulating
X = np.random.negative_binomial(n, p, size)
then EX = (1 - p) * n / p
Var(X) = (1 - p) * n / p**2
These equations can be inverted as follows:
p = E / V
n = E * p / (1 - p)
dparams[0] is the common correlation coefficient
"""
def print_dparams(self, dparams_est):
OUT.write("Estimated inverse scale parameter: %8.4f\n" %
dparams_est[0])
OUT.write("True inverse scale parameter: %8.4f\n" %
self.scale_inv)
OUT.write("\n")
def simulate(self):
endog, exog, group, time = [], [], [], []
# Get a basis for the orthogonal complement to params.
f = np.sum(self.params**2)
u,s,vt = np.linalg.svd(np.eye(len(self.params)) -
np.outer(self.params, self.params) / f)
params0 = u[:,np.flatnonzero(s > 1e-6)]
for i in range(self.ngroups):
gsize = np.random.randint(self.group_size_range[0],
self.group_size_range[1])
group.append([i,] * gsize)
time1 = np.random.normal(size=(gsize, 2))
time.append(time1)
exog1 = np.random.normal(size=(gsize, len(self.params)))
exog.append(exog1)
E = np.exp(np.dot(exog1, self.params))
V = E * self.scale_inv
p = E / V
n = E * p / (1 - p)
endog1 = np.random.negative_binomial(n, p, gsize)
endog.append(endog1)
self.exog = np.concatenate(exog, axis=0)
self.endog = np.concatenate(endog)
self.time = np.concatenate(time, axis=0)
self.group = np.concatenate(group)
def gendat_exchangeable():
exs = Exchangeable_simulator()
exs.params = np.r_[2., 0.2, 0.2, -0.1, -0.2]
exs.ngroups = 200
exs.dparams = [0.3,]
exs.simulate()
return exs, Exchangeable()
def gendat_overdispersed():
exs = Overdispersed_simulator()
exs.params = np.r_[2., 0.2, 0.2, -0.1, -0.2]
exs.ngroups = 200
exs.scale_inv = 2.
exs.dparams = []
exs.simulate()
return exs, Independence()
if __name__ == "__main__":
np.set_printoptions(formatter={'all': lambda x: "%8.3f" % x},
suppress=True)
OUT = open("gee_poisson_simulation_check.txt", "w", encoding="utf-8")
nrep = 100
gendats = [gendat_exchangeable, gendat_overdispersed]
lhs = np.array([[0., 1, -1, 0, 0],])
rhs = np.r_[0.0,]
# Loop over data generating models
for gendat in gendats:
pvalues = []
params = []
std_errors = []
dparams = []
for j in range(nrep):
da, va = gendat()
ga = Poisson()
# Poisson seems to be more sensitive to starting values,
# so we run the independence model first.
md = GEE(da.endog, da.exog, da.group, da.time, ga,
Independence())
mdf = md.fit()
md = GEE(da.endog, da.exog, da.group, da.time, ga, va)
mdf = md.fit(start_params = mdf.params)
if mdf is None or (not mdf.converged):
print("Failed to converge")
continue
scale_inv = 1. / md.estimate_scale()
dparams.append(np.r_[va.dparams, scale_inv])
params.append(np.asarray(mdf.params))
std_errors.append(np.asarray(mdf.standard_errors))
da,va = gendat()
ga = Poisson()
md = GEE(da.endog, da.exog, da.group, da.time, ga, va,
constraint=(lhs, rhs))
mdf = md.fit()
if mdf is None or (not mdf.converged):
print("Failed to converge")
continue
score = md.score_test_results
pvalue = score["p-value"]
pvalues.append(pvalue)
dparams_mean = np.array(sum(dparams) / len(dparams))
OUT.write("Results based on %d successful fits out of %d data sets.\n\n"
% (len(dparams), nrep))
OUT.write("Checking dependence parameters:\n")
da.print_dparams(dparams_mean)
params = np.array(params)
eparams = params.mean(0)
sdparams = params.std(0)
std_errors = np.array(std_errors)
std_errors = std_errors.mean(0)
OUT.write("Checking parameter values:\n")
OUT.write("Observed: ")
OUT.write(np.array_str(eparams) + "\n")
OUT.write("Expected: ")
OUT.write(np.array_str(da.params) + "\n")
OUT.write("Absolute difference: ")
OUT.write(np.array_str(eparams - da.params) + "\n")
OUT.write("Relative difference: ")
OUT.write(np.array_str((eparams - da.params) / da.params)
+ "\n")
OUT.write("\n")
OUT.write("Checking standard errors\n")
OUT.write("Observed: ")
OUT.write(np.array_str(sdparams) + "\n")
OUT.write("Expected: ")
OUT.write(np.array_str(std_errors) + "\n")
OUT.write("Absolute difference: ")
OUT.write(np.array_str(sdparams - std_errors) + "\n")
OUT.write("Relative difference: ")
OUT.write(np.array_str((sdparams - std_errors) / std_errors)
+ "\n")
OUT.write("\n")
pvalues.sort()
OUT.write("Checking constrained estimation:\n")
OUT.write("Left hand side:\n")
OUT.write(np.array_str(lhs) + "\n")
OUT.write("Right hand side:\n")
OUT.write(np.array_str(rhs) + "\n")
OUT.write("Observed p-values Expected Null p-values\n")
for q in np.arange(0.1, 0.91, 0.1):
OUT.write("%20.3f %20.3f\n" %
(pvalues[int(q*len(pvalues))], q))
OUT.write("=" * 80 + "\n\n")
OUT.close()
| bsd-3-clause | 811dc05dda1edb6394e2e0d8d0ca5cd2 | 31.208481 | 80 | 0.544487 | 3.369686 | false | false | false | false |
conda-forge/conda-forge.github.io | scripts/tick_my_feedstocks.py | 1 | 33437 | #!/usr/bin/env conda-execute
# conda execute
# env:
# - python >=2.7
# - setuptools
# - beautifulsoup4
# - conda-smithy
# - gitpython
# - jinja2
# - pygithub >=1.29,<2
# - pyyaml
# - requests
# - tqdm
# channels:
# - conda-forge
# run_with: python
"""
Usage:
python tick_my_feedstocks.py [-h]
[--password GH_PASSWORD] [--user GH_USER]
[--no-regenerate] [--no-rerender] [--dry-run]
[--targetfile TARGETFILE]
[--target-feedstocks [TARGET_FEEDSTOCKS [TARGET_FEEDSTOCKS ...]]]
[--limit-feedstocks LIMIT_FEEDSTOCKS]
[--limit-outdated LIMIT_OUTDATED]
[--skipfile SKIPFILE]
[--skip-feedstocks [SKIP_FEEDSTOCKS [SKIP_FEEDSTOCKS ...]]]
or
conda execute tick_my_feedstocks.py [-h]
[--password GH_PASSWORD] [--user GH_USER]
[--no-regenerate] [--no-rerender] [--dry-run]
[--targetfile TARGETFILE]
[--target-feedstocks [TARGET_FEEDSTOCKS [TARGET_FEEDSTOCKS ...]]]
[--limit-feedstocks LIMIT_FEEDSTOCKS]
[--limit-outdated LIMIT_OUTDATED]
[--skipfile SKIPFILE]
[--skip-feedstocks [SKIP_FEEDSTOCKS [SKIP_FEEDSTOCKS ...]]]
NOTE that your oauth token should have these abilities:
* public_repo
* read:org
* delete_repo.
This script:
1. identifies all of the feedstocks maintained by a user
2. attempts to determine F, the subset of feedstocks that need updating
3. attempts to determine F_i, the subset of F that have no dependencies
on other members of F
4. attempts to patch each member of F_i with the new version number and hash
5. attempts to regenerate each member of F_i with the installed version
of conda-smithy
6. submits a pull request for each member of F_i to the appropriate
conda-forge repoository
IMPORTANT NOTES:
* We get version information from PyPI. If the feedstock isn't based on PyPI,
it will raise an error. (Execution will continue.)
* All feedstocks updated with this script SHOULD BE DOUBLE-CHECKED! Because
conda-forge tests are lightweight, even if the requirements have changed the
tests may still pass successfully.
"""
# TODO pass token/user to pygithub for push. (Currently uses system config.)
# TODO Modify --dry-run flag to list which repos need forks.
# TODO Modify --dry-run flag to list which forks are dirty.
# TODO Modify --dry-run to also cover regeneration
# TODO skip upgrading from a stable release to a dev release (e.g. ghost.py)
# (This is useful but not critical, since we can provide skip lists)
# TODO Deeper check of dependency changes in meta.yaml.
# TODO Check installed conda-smithy against current feedstock conda-smithy.
# TODO Check if already-forked feedstocks have open pulls.
# TODO maintainer_can_modify flag when submitting pull
# Note that this isn't supported by pygithub yet, so would require
# switching back to requests
# TODO Suppress regeneration text output
# TODO improve the tqdm progress bar during regeneration.
import argparse
from base64 import b64encode
from collections import defaultdict
from collections import namedtuple
from git import Actor
from git import Repo
from github import Github
from github import GithubException
from github import UnknownObjectException
import hashlib
from jinja2 import Template
from jinja2 import UndefinedError
import os
from pkg_resources import parse_version
import re
import requests
import shutil
import stat
import tempfile
from tqdm import tqdm
import urllib
import yaml
# Find places where Jinja variables are set
jinja_set_regex = re.compile('{% *set +([^ ]+) *= "?([^ "]+)"? *%}')
# Find places where YAML variables are assigned using Jinja variables
yaml_jinja_assign_regex = re.compile(' +([^:]+): *[^ ]*({{ .* }}.*)')
# Jinja template informaton
# Value being set and the setting string
# tpl(str, str)
jinja_var = namedtuple('jinja_var', ['value', 'string'])
# result tuple
# Success bool and any related data
# tpl(bool, None|str|status_data)
result_tuple = namedtuple('result_tuple', ['success', 'data'])
# status_data tuple
# data for updating a feedstock
# tpl(Feedstock_Meta_Yaml, str, str)
status_data = namedtuple('status_data', ['meta_yaml',
'version',
'blob_sha'])
# feedstock status tuple
# pairing of a feedstock and its status data
# tpl(github.Repository.Repository, status_data)
fs_status = namedtuple('fs_status', ['fs', 'sd'])
# Ordered list of acceptable ways source can be packaged.
source_bundle_types = ["tar.gz", "tar.bz2", "zip", "bz2"]
# stream_url_progress and hash_url are vendored from rever
def stream_url_progress(url, verb='downloading', chunksize=1024):
"""Generator yielding successive bytes from a URL.
Parameters
----------
url : str
URL to open and stream
verb : str
Verb to prefix the url downloading with, default 'downloading'
chunksize : int
Number of bytes to return, defaults to 1 kb.
Returns
-------
yields the bytes which is at most chunksize in length.
Copyright (c) 2017, Anthony Scopatz
"""
nbytes = 0
print(verb + ' ' + url)
with urllib.request.urlopen(url) as f:
totalbytes = f.length
while True:
b = f.read(chunksize)
lenbytes = len(b)
nbytes += lenbytes
if lenbytes == 0:
break
else:
yield b
if totalbytes is None:
totalbytes = f.length
def hash_url(url, hash='sha256'):
"""Hashes a URL and returns the hex representation
Copyright (c) 2017, Anthony Scopatz"""
hasher = getattr(hashlib, hash)()
for b in stream_url_progress(url, verb='Hashing'):
hasher.update(b)
return hasher.hexdigest()
def parse_feedstock_file(feedstock_fpath):
"""
Takes a file with space-separated feedstocks on each line and comments
after hashmarks, and returns a list of feedstocks
:param str feedstock_fpath:
:return: `list` -- list of feedstocks
"""
from itertools import chain
if not (isinstance(feedstock_fpath, str) and
os.path.exists(feedstock_fpath)):
return list()
try:
with open(feedstock_fpath, 'r') as infile:
feedstocks = list(
chain.from_iterable(x.split('#')[0].strip().split()
for x in infile)
)
except:
return list()
return feedstocks
class Feedstock_Meta_Yaml:
"""
A parser for and modifier of a feedstock's meta.yaml file.
Because many feedstocks use Jinja templates in their meta.yaml files
and because we'd like to minimize the number of changes to meta.yaml
when submitting a patch, this class can be used to help keep the
manage the file's content and keep changes small.
"""
def _parse_text(self):
"""
Extract different variables from the raw text
"""
try:
self._yaml_dict = yaml.load(Template(self._text).render(),
Loader=yaml.BaseLoader)
except UndefinedError:
# assume we hit a RECIPE_DIR reference in the vars
# and can't parse it.
# just erase for now
try:
self._yaml_dict = yaml.load(
Template(re.sub('{{ (environ\[")?RECIPE_DIR("])? }}/',
'',
self._text)
).render(),
Loader=yaml.BaseLoader)
except UndefinedError:
raise UndefinedError("Can't parse meta.yaml")
for x, y in [('package', 'version'),
('source', 'fn')]:
if y not in self._yaml_dict[x]:
raise KeyError('Missing meta.yaml key: [{}][{}]'.format(x, y))
if 'sha256' in self._yaml_dict['source']:
self.checksum_type = 'sha256'
elif 'md5' in self._yaml_dict['source']:
self.checksum_type = 'md5'
else:
raise KeyError('Missing meta.yaml key for checksum')
splitter = '-{}.'.format(self._yaml_dict['package']['version'])
self.package, self.bundle_type = \
self._yaml_dict['source']['fn'].split(splitter)
self.package_type = None
self.package_owner = None
self.package_url = None
if 'github' in self._yaml_dict['source']['url']:
self.package_type = 'github'
split_url = self._yaml_dict['source']['url'].lower().split('/')
self.package_owner = split_url[split_url.index('github.com') + 1]
self.package_url = self._yaml_dict['source']['url']
else:
self.package_type = 'pypi'
self.reqs = set()
for step in self._yaml_dict['requirements']:
self.reqs.update({x.split()[0]
for x in self._yaml_dict['requirements'][step]})
# Get variables defined in the Jinja template
self.jinja_vars = dict()
for j_v in re.finditer(jinja_set_regex, self._text):
grps = j_v.groups()
match_str = j_v.string[j_v.start(): j_v.end()]
self.jinja_vars[grps[0]] = jinja_var(grps[1], match_str)
# Get YAML variables assigned Jinja variables
self.yaml_jinja_refs = {y_j.groups()[0]: y_j.groups()[1]
for y_j in re.finditer(yaml_jinja_assign_regex,
self._text)}
def __init__(self, raw_text):
"""
:param str raw_text: The complete raw text of the meta.yaml file
"""
self._text = raw_text
self._parse_text()
def build(self):
"""
Get current build number.
:return: `str` -- the extracted build number
"""
return str(self._yaml_dict['build']['number'])
def version(self):
"""
Get the current version string.
A look up into a dictionary. Probably Unneeded.
:return: `str` -- the extracted version string
"""
return self._yaml_dict['package']['version']
def checksum(self):
"""
Get the current checksum.
A look up into a dictionary. Probably Unneeded.
:return: `str` -- the current checksum
"""
return self._yaml_dict['source'][self.checksum_type]
def find_replace_update(self, mapping):
"""
Find and replace values in the raw text.
:param dict mapping: keys are old values, values are new values
"""
for key in sorted(mapping.keys()):
self._text = self._text.replace(key, mapping[key])
self._parse_text()
def set_build_number(self, new_number):
"""
Reset the build number
:param int|str new_number: New build number
:return: `bool` -- True if replacement successful or unneeded, False if
failed
"""
if str(new_number) == self._yaml_dict['build']['number']:
# Nothing to do
return True
if 'number' in self.yaml_jinja_refs:
# We *assume* that 'number' is for assigning the build
# We *assume* that there's only one variable involved in the
# assignment
build_var = self.yaml_jinja_refs['number'].split()[1]
mapping = {self.jinja_vars[build_var].string:
'{{% set {key} = {val} %}}'.format(
key=build_var,
val=new_number)}
else:
build_num_regex = re.compile('number: *{}'.format(
self._yaml_dict['build']['number']))
matches = re.findall(build_num_regex, self._text)
if len(matches) != 1:
# Multiple number lines
# or no number lines
# So give up
return False
mapping = {matches[0]: 'number: {}'.format(new_number)}
self.find_replace_update(mapping)
return True
def encoded_text(self):
"""
Get the encoded version of the current raw text
:return: `str` -- the text encoded as a b64 string
"""
return b64encode(self._text.encode('utf-8')).decode('utf-8')
def pypi_legacy_json_sha(package_name, version):
"""
Use PyPI's legacy JSON API to get the SHA256 of the source bundle
:param str package_name: Name of package (PROPER case)
:param str version: version for which to get sha
:return: `tpl(str,str)|tpl(None,None)` -- bundle_type,SHA or None,None
"""
r = requests.get('https://pypi.org/pypi/{}/json'.format(package_name))
if not r.ok:
return None, None
jsn = r.json()
if version not in jsn['releases']:
return None, None
release = None
for bundle_type in source_bundle_types:
try:
release = next(x for x
in jsn['releases'][version]
if x['filename'].endswith('.' + bundle_type))
return bundle_type, release['digests']['sha256']
except StopIteration:
# No bundle of target type
continue
except KeyError:
# No key for the sha.
release = None
if release is None:
return None, None
def pypi_org_sha(package_name, version):
"""
Scrape pypi.org for SHA256 of the source bundle
:param str package_name: Name of package (PROPER case)
:param str version: version for which to get sha
:return: `str,str|None,None` -- bundle type,SHA for source, None,None if
can't be found
"""
import warnings
from bs4 import BeautifulSoup
warnings.filterwarnings("ignore", category=UserWarning, module='bs4')
r = requests.get('https://pypi.org/project/{}/{}/#files'.format(
package_name,
version))
bs = BeautifulSoup(r.text)
for bundle_type in source_bundle_types:
try:
url_pattern = re.compile(
'https://files.pythonhosted.org.*{}-{}.{}'.format(package_name,
version,
bundle_type))
sha_val = bs.find('a', {'href': url_pattern}
).next.next.next['data-clipboard-text']
return bundle_type, sha_val
except AttributeError:
# Bad parsing of page, couldn't get SHA256
continue
return None, None
def sha(package, version, package_type='pypi', package_url=None,
prior_version=None):
"""
:param str package: The name of the package in PyPI
:param str version: The version to be retrieved from PyPI.
:return: `str|None` -- SHA256 for a source bundle, None if can't be found
"""
if package_type == 'github':
package_url = package_url.replace(prior_version, version)
return hash_url(package_url)
else:
bundle_type, sha = pypi_legacy_json_sha(package, version)
if bundle_type is not None and sha is not None:
return bundle_type, sha
return pypi_org_sha(package, version)
def version_str(package_name, package_type='pypi', package_owner=None):
"""
Retrive the latest version of a package in PyPI
:param str package_name: The name of the package
:param str package_type: The type of package ('pypi' or 'github')
:return: `str|bool` -- Version string, False if unsuccessful
"""
if package_type == 'pypi':
r = requests.get('https://pypi.python.org/pypi/{}/json'.format(
package_name))
if not r.ok:
return False
return r.json()['info']['version'].strip()
elif package_type == 'github':
# get all the tags
refs = requests.get('https://api.github.com/repos/{owner}/'
'{repo}/git/refs/tags'.format(owner=package_owner,
repo=package_name))
if not refs.ok:
return False
# Extract all the non rc tags
tags = [parse_version(r['ref'].split('/')[-1]) for r in refs if
'rc' not in r['ref']]
# return the most recent tag
return max(tags)
def user_feedstocks(user, limit=-1, skips=None):
"""
:param github.AuthenticatedUser.AutheticatedUser user:
:param int limit: If greater than -1, max number of feedstocks to return
:param list|set skips: an iterable of the names of feedstocks that should
be skipped
:return: `tpl(int,list)` -- count of skipped feedstocks, list of
conda-forge feedstocks the user maintains
"""
if skips is None:
skips = set()
skip_count = 0
feedstocks = []
for team in tqdm(user.get_teams(), desc='Finding feedstock teams...'):
# Check if we've hit the feedstock limit
if limit > -1 and len(feedstocks) >= limit:
break
# Each conda-forge team manages one feedstock
# If a team has more than one repo, skip it.
if team.repos_count != 1:
continue
repo = list(team.get_repos())[0]
if not repo.full_name.startswith('conda-forge/') or \
not repo.full_name.endswith('-feedstock'):
continue
if repo.name in skips:
skip_count += 1
continue
feedstocks.append(repo)
return skip_count, feedstocks
def feedstock_status(feedstock):
"""
Return whether a feedstock is out of date and any information needed to
update it.
:param github.Repository.Repository feedstock:
:return: `tpl(bool,bool,None|status_data)` -- bools indicating success and
either None or a status_data tuple
"""
fs_contents = feedstock.get_contents('recipe/meta.yaml')
try:
meta_yaml = Feedstock_Meta_Yaml(
fs_contents.decoded_content.decode('utf-8'))
except (UndefinedError, KeyError) as e:
return result_tuple(False, e.args[0])
version = version_str(meta_yaml.package,
meta_yaml.package_type,
meta_yaml.package_owner)
if version is False:
return result_tuple(False, "Couldn't find package in PyPI")
if parse_version(meta_yaml.version()) >= parse_version(version):
return result_tuple(True, None)
return result_tuple(True,
status_data(meta_yaml,
version,
fs_contents.sha))
def even_feedstock_fork(user, feedstock):
"""
Return a fork that's even with the latest version of the feedstock
If the user has a fork that's ahead of the feedstock, do nothing
:param github.AuthenticatedUser.AuthenticatedUser user: GitHub user
:param github.Repository.Repository feedstock: conda-forge feedstock
:return: `None|github.Repository.Repository` -- None if no fork, else the
repository
"""
try:
fork = user.create_fork(feedstock)
except UnknownObjectException:
raise ValueError('Got 404 when creating fork')
try:
comparison = fork.compare(base='{}:master'.format(user.login),
head='conda-forge:master')
except UnknownObjectException:
raise ValueError('Got 404 when comparing forks, left new fork')
# TODO Solve the mystery of why github times are misbehaving
# and then check if a fork was just created and can be purged.
# from datetime import datetime
# seconds_since_creation = (
# datetime.now() - fork.created_at).total_seconds()
# print('seconds_since_creation = {}'.format(seconds_since_creation))
# if seconds_since_creation > 10:
# # Assume fork is old, so don't clean it up
# raise ValueError('Got 404 when comparing forks, left fork')
#
# try:
# fork.delete()
# except UnknownObjectException:
# raise ValueError(
# "Got 404 when comparing forks, couldn't clean up")
#
# raise ValueError(
# 'Got 404 when comparing forks, cleaned up fork')
if comparison.behind_by > 0:
# head is *behind* the base
# conda-forge is behind the fork
# leave everything alone - don't want a mess.
raise ValueError('local fork is ahead of conda-forge')
if comparison.ahead_by > 0:
# head is *ahead* of base
# conda-forge is ahead of the fork
# delete fork and clone from scratch
try:
fork.delete()
except GithubException:
# couldn't delete feedstock
# give up, don't want a mess.
raise ValueError("Couldn't delete outdated fork")
try:
fork = user.create_fork(feedstock)
except UnknownObjectException:
raise ValueError('Got 404 when re-creating fork')
return fork
def regenerate_fork(fork):
"""
:param github.Repository.Repository fork: fork of conda-forge feedstock
:return: `bool` -- True if regenerated, false otherwise
"""
import conda_smithy
import conda_smithy.configure_feedstock
# Would need me to pass gh_user, gh_password
# subprocess.run(["./renderer.sh", gh_user, gh_password, fork.name])
working_dir = tempfile.mkdtemp()
local_repo_dir = os.path.join(working_dir, fork.name)
r = Repo.clone_from(fork.clone_url, local_repo_dir)
conda_smithy.configure_feedstock.main(local_repo_dir)
if not r.is_dirty():
# No changes made during regeneration.
# Clean up and return
shutil.rmtree(working_dir, onerror=remove_readonly)
return False
commit_msg = \
'MNT: Updated the feedstock for conda-smithy version {}.'.format(
conda_smithy.__version__)
r.git.add('-A')
r.index.commit(commit_msg,
author=Actor(fork.owner.login, fork.owner.email))
r.git.push()
shutil.rmtree(working_dir, onerror=remove_readonly)
return True
def remove_readonly(func, path, excinfo):
os.chmod(path, stat.S_IWRITE)
func(path)
def tick_feedstocks(gh_password=None,
gh_user=None,
no_regenerate=False,
dry_run=False,
targetfile=None,
target_feedstocks=None,
limit_feedstocks=-1,
limit_outdated=-1,
skipfile=None,
skip_feedstocks=None):
"""
Finds all of the feedstocks a user maintains that can be updated without
a dependency conflict with other feedstocks the user maintains,
creates forks, ticks versions and hashes, and regenerates,
then submits a pull
:param str|None gh_password: GitHub password or OAuth token (if omitted,
check environment vars)
:param str|None gh_user: GitHub username (can be omitted with OAuth)
:param bool no_regenerate: If True, don't regenerate feedstocks before
submitting pull requests
:param bool dry_run: If True, do not apply generate patches, fork
feedstocks, or regenerate
:param str targetfile: path to file listing feedstocks to use
:param list|set target_feedstocks: list or set of feedstocks to use
:param int limit_feedstocks: If greater than -1, maximum number of
feedstocks to retrieve and check for updateds
:param int limit_outdated: If greater than -1, maximum number of outdated
feedstocks to check for patching
:param str skipfile: path to file listing feedstocks to skip
:param list|set skip_feedstocks: list or set of feedstocks to skip
"""
if gh_password is None:
gh_password = os.getenv('GH_TOKEN')
if gh_password is None:
raise ValueError('No password or OAuth token provided, '
'and no OAuthToken as GH_TOKEN in environment.')
if gh_user is None:
g = Github(gh_password)
user = g.get_user()
gh_user = user.login
else:
g = Github(gh_user, gh_password)
user = g.get_user()
targets = set()
if isinstance(target_feedstocks, (set, list)):
targets.update(target_feedstocks)
targets.update(parse_feedstock_file(targetfile))
skips = set()
if isinstance(skip_feedstocks, (set, list)):
skips.update(skip_feedstocks)
skips.update(parse_feedstock_file(skipfile))
if len(targets) > 0:
# If we have specific target feedstocks only retrieve those
skip_count = len(targets & skips)
feedstocks = []
for name in targets - skips:
repo = g.get_repo('conda-forge/{}'.format(name))
try:
repo.full_name
feedstocks.append(repo)
except UnknownObjectException:
# couldn't get repo, so error out
raise ValueError(
"Couldn't retrieve repository: {}".format(name))
else:
# If we have no specific targets
# review all teams and filter based on those
skip_count, feedstocks = user_feedstocks(user, limit_feedstocks, skips)
can_be_updated = list()
status_error_dict = defaultdict(list)
for feedstock in tqdm(feedstocks, desc='Checking feedstock statuses...'):
status = feedstock_status(feedstock)
if status.success and status.data is not None:
can_be_updated.append(fs_status(feedstock, status.data))
elif not status.success:
status_error_dict[status.data].append(feedstock.name)
if limit_outdated > -1 and len(can_be_updated) >= limit_outdated:
break
package_names = set([x.fs.name[:-10] for x in can_be_updated])
indep_updates = [x for x in can_be_updated
if len(x.sd.meta_yaml.reqs & package_names) < 1]
successful_forks = list()
successful_updates = list()
patch_error_dict = defaultdict(list)
fork_error_dict = defaultdict(list)
error_dict = defaultdict(list)
for update in tqdm(indep_updates, desc='Updating feedstocks'):
new_bundle_type, new_sha = sha(
update.sd.meta_yaml.package,
update.sd.version,
update.sd.meta_yaml.package_type,
update.sd.meta_yaml.package_url,
update.sd.meta_yaml.version()
)
if new_bundle_type is None and new_sha is None:
patch_error_dict["Couldn't get SHA from PyPI"].append(
update.fs.name)
continue
# generate basic patch
mapping = {update.sd.meta_yaml.version():
update.sd.version,
update.sd.meta_yaml.checksum(): new_sha}
if update.sd.meta_yaml.checksum_type != 'sha256':
mapping[update.sd.meta_yaml.checksum_type] = 'sha256'
if new_bundle_type != update.sd.meta_yaml.bundle_type:
mapping[update.sd.meta_yaml.bundle_type] = new_bundle_type
update.sd.meta_yaml.find_replace_update(mapping)
if update.sd.meta_yaml.build() != '0':
update.sd.meta_yaml.set_build_number(0)
if dry_run:
# Skip additional processing here.
continue
# make fork
try:
fork = even_feedstock_fork(user, update.fs)
except ValueError as e:
fork_error_dict[e.args[0]].append(update.fs.name)
continue
if fork is None:
fork_error_dict["Unspecified failure"].append(update.fs.name)
continue
# patch fork
r = requests.put(
'https://api.github.com/repos/{}/contents/recipe/meta.yaml'.format(
fork.full_name),
json={'message':
'Tick version to {}'.format(update.sd.version),
'content': update.sd.meta_yaml.encoded_text(),
'sha': update.sd.blob_sha
},
auth=(gh_user, gh_password))
if not r.ok:
error_dict["Couldn't apply patch"].append(update.fs.name)
continue
successful_updates.append(update)
successful_forks.append(fork)
if no_regenerate:
print('Skipping regenerating feedstocks.')
else:
for fork in tqdm(successful_forks, desc='Regenerating feedstocks...'):
regenerate_fork(fork)
pull_count = 0
for update in tqdm(successful_updates, desc='Submitting pulls...'):
try:
update.fs.create_pull(title='Ticked version, '
'regenerated if needed. '
'(Double-check reqs!)',
body='Made using `tick_my_feedstocks.py`!\n'
'- [ ] **I have vetted this recipe**',
head='{}:master'.format(gh_user),
base='master')
except GithubException:
error_dict["Couldn't create pull"].append(update.fs.name)
continue
pull_count += 1
print('{} feedstock(s) skipped.'.format(skip_count))
print('{} feedstock(s) checked.'.format(len(feedstocks)))
print(' {} feedstock(s) '
'were out-of-date.'.format(len(can_be_updated)))
print(' {} feedstock(s) '
'were independent of other out-of-date feedstocks'.format(
len(indep_updates)))
print(' {} feedstock(s) '
'had pulls submitted.'.format(pull_count))
print('-----')
for msg, cur_dict in [("Couldn't check status", status_error_dict),
("Couldn't create patch", patch_error_dict),
("Error when forking", fork_error_dict)]:
if len(cur_dict) < 1:
continue
print('{}:'.format(msg))
for error_msg in cur_dict:
print(' {} ({}):'.format(error_msg,
len(cur_dict[error_msg])))
for name in cur_dict[error_msg]:
print(' {}'.format(name))
for error_msg in ["Couldn't apply patch",
"Couldn't create pull"]:
if error_msg not in error_dict:
continue
print('{} ({}):'.format(error_msg, len(error_dict[error_msg])))
for name in error_dict[error_msg]:
print(' {}'.format(name))
def main():
"""
Parse command-line arguments and run tick_feedstocks()
"""
parser = argparse.ArgumentParser()
parser.add_argument('--password',
default=None,
dest='gh_password',
help='GitHub password or oauth token')
parser.add_argument('--user',
default=None,
dest='gh_user',
help='GitHub username')
parser.add_argument('--no-regenerate',
action='store_true',
dest='no_regenerate',
help="If present, don't regenerate feedstocks "
'after updating')
parser.add_argument('--no-rerender',
action='store_true',
dest='no_rerender',
help="If present, don't regenerate feedstocks "
'after updating')
parser.add_argument('--dry-run',
action='store_true',
dest='dry_run',
help='If present, skip applying patches, forking, '
'and regenerating feedstocks')
parser.add_argument('--target-feedstocks-file',
default=None,
dest='targetfile',
help='File listing feedstocks to check')
parser.add_argument('--target-feedstocks',
default=None,
dest='target_feedstocks',
nargs='*',
help='List of feedstocks to update')
parser.add_argument('--limit-feedstocks',
type=int,
default=-1,
dest='limit_feedstocks',
help='Maximum number of feedstocks to retrieve')
parser.add_argument('--limit-outdated',
type=int,
default=-1,
dest='limit_outdated',
help='Maximum number of outdated feedstocks to try '
'and patch')
parser.add_argument('--skip-feedstocks-file',
default=None,
dest='skipfile',
help='File listing feedstocks to skip')
parser.add_argument('--skip-feedstocks',
default=None,
dest='skip_feedstocks',
nargs='*',
help='List of feedstocks to skip updating')
args = parser.parse_args()
tick_feedstocks(args.gh_password,
args.gh_user,
args.no_regenerate or args.no_rerender,
args.dry_run,
args.targetfile,
args.target_feedstocks,
args.limit_feedstocks,
args.limit_outdated,
args.skipfile,
args.skip_feedstocks)
if __name__ == "__main__":
main()
| bsd-3-clause | 3ada80949789efce164c2b8bf69af057 | 34.992465 | 79 | 0.578072 | 4.081665 | false | false | false | false |
mozilla/firefox-flicks | vendor-local/lib/python/celery/worker/heartbeat.py | 1 | 1643 | # -*- coding: utf-8 -*-
"""
celery.worker.heartbeat
~~~~~~~~~~~~~~~~~~~~~~~
This is the internal thread that sends heartbeat events
at regular intervals.
"""
from __future__ import absolute_import
from .state import SOFTWARE_INFO, active_requests, total_count
class Heart(object):
"""Timer sending heartbeats at regular intervals.
:param timer: Timer instance.
:param eventer: Event dispatcher used to send the event.
:keyword interval: Time in seconds between heartbeats.
Default is 30 seconds.
"""
def __init__(self, timer, eventer, interval=None):
self.timer = timer
self.eventer = eventer
self.interval = float(interval or 5.0)
self.tref = None
# Make event dispatcher start/stop us when it's
# enabled/disabled.
self.eventer.on_enabled.add(self.start)
self.eventer.on_disabled.add(self.stop)
def _send(self, event):
return self.eventer.send(event, freq=self.interval,
active=len(active_requests),
processed=sum(total_count.itervalues()),
**SOFTWARE_INFO)
def start(self):
if self.eventer.enabled:
self._send('worker-online')
self.tref = self.timer.apply_interval(
self.interval * 1000.0, self._send, ('worker-heartbeat', ),
)
def stop(self):
if self.tref is not None:
self.timer.cancel(self.tref)
self.tref = None
if self.eventer.enabled:
self._send('worker-offline')
| bsd-3-clause | e531a22939d8e61a297d393ccd2b314f | 29.425926 | 75 | 0.572733 | 4.180662 | false | false | false | false |
mozilla/firefox-flicks | vendor-local/lib/python/celery/tests/config.py | 1 | 1764 | from __future__ import absolute_import
import os
from kombu import Queue
BROKER_URL = 'memory://'
#: warn if config module not found
os.environ['C_WNOCONF'] = 'yes'
#: Don't want log output when running suite.
CELERYD_HIJACK_ROOT_LOGGER = False
CELERY_RESULT_BACKEND = 'cache'
CELERY_CACHE_BACKEND = 'memory'
CELERY_RESULT_DBURI = 'sqlite:///test.db'
CELERY_SEND_TASK_ERROR_EMAILS = False
CELERY_DEFAULT_QUEUE = 'testcelery'
CELERY_DEFAULT_EXCHANGE = 'testcelery'
CELERY_DEFAULT_ROUTING_KEY = 'testcelery'
CELERY_QUEUES = (
Queue('testcelery', routing_key='testcelery'),
)
CELERY_ENABLE_UTC = True
CELERY_TIMEZONE = 'UTC'
CELERYD_LOG_COLOR = False
# Tyrant results tests (only executed if installed and running)
TT_HOST = os.environ.get('TT_HOST') or 'localhost'
TT_PORT = int(os.environ.get('TT_PORT') or 1978)
# Redis results tests (only executed if installed and running)
CELERY_REDIS_HOST = os.environ.get('REDIS_HOST') or 'localhost'
CELERY_REDIS_PORT = int(os.environ.get('REDIS_PORT') or 6379)
CELERY_REDIS_DB = os.environ.get('REDIS_DB') or 0
CELERY_REDIS_PASSWORD = os.environ.get('REDIS_PASSWORD')
# Mongo results tests (only executed if installed and running)
CELERY_MONGODB_BACKEND_SETTINGS = {
'host': os.environ.get('MONGO_HOST') or 'localhost',
'port': os.environ.get('MONGO_PORT') or 27017,
'database': os.environ.get('MONGO_DB') or 'celery_unittests',
'taskmeta_collection': (os.environ.get('MONGO_TASKMETA_COLLECTION')
or 'taskmeta_collection'),
}
if os.environ.get('MONGO_USER'):
CELERY_MONGODB_BACKEND_SETTINGS['user'] = os.environ.get('MONGO_USER')
if os.environ.get('MONGO_PASSWORD'):
CELERY_MONGODB_BACKEND_SETTINGS['password'] = \
os.environ.get('MONGO_PASSWORD')
| bsd-3-clause | 7258e378987520acc242d41d412ccdb5 | 31.666667 | 74 | 0.70805 | 3.073171 | false | true | true | false |
mozilla/firefox-flicks | vendor-local/lib/python/celery/app/base.py | 1 | 17166 | # -*- coding: utf-8 -*-
"""
celery.app.base
~~~~~~~~~~~~~~~
Actual App instance implementation.
"""
from __future__ import absolute_import
from __future__ import with_statement
import os
import threading
import warnings
from collections import deque
from contextlib import contextmanager
from copy import deepcopy
from functools import wraps
from billiard.util import register_after_fork
from kombu.clocks import LamportClock
from kombu.utils import cached_property
from celery import platforms
from celery.exceptions import AlwaysEagerIgnored
from celery.loaders import get_loader_cls
from celery.local import PromiseProxy, maybe_evaluate
from celery._state import _task_stack, _tls, get_current_app, _register_app
from celery.utils.functional import first
from celery.utils.imports import instantiate, symbol_by_name
from .annotations import prepare as prepare_annotations
from .builtins import shared_task, load_shared_tasks
from .defaults import DEFAULTS, find_deprecated_settings
from .registry import TaskRegistry
from .utils import AppPickler, Settings, bugreport, _unpickle_app
_EXECV = os.environ.get('FORKED_BY_MULTIPROCESSING')
def _unpickle_appattr(reverse_name, args):
"""Given an attribute name and a list of args, gets
the attribute from the current app and calls it."""
return get_current_app()._rgetattr(reverse_name)(*args)
class Celery(object):
Pickler = AppPickler
SYSTEM = platforms.SYSTEM
IS_OSX, IS_WINDOWS = platforms.IS_OSX, platforms.IS_WINDOWS
amqp_cls = 'celery.app.amqp:AMQP'
backend_cls = None
events_cls = 'celery.events:Events'
loader_cls = 'celery.loaders.app:AppLoader'
log_cls = 'celery.app.log:Logging'
control_cls = 'celery.app.control:Control'
registry_cls = TaskRegistry
_pool = None
def __init__(self, main=None, loader=None, backend=None,
amqp=None, events=None, log=None, control=None,
set_as_current=True, accept_magic_kwargs=False,
tasks=None, broker=None, include=None, **kwargs):
self.clock = LamportClock()
self.main = main
self.amqp_cls = amqp or self.amqp_cls
self.backend_cls = backend or self.backend_cls
self.events_cls = events or self.events_cls
self.loader_cls = loader or self.loader_cls
self.log_cls = log or self.log_cls
self.control_cls = control or self.control_cls
self.set_as_current = set_as_current
self.registry_cls = symbol_by_name(self.registry_cls)
self.accept_magic_kwargs = accept_magic_kwargs
self.configured = False
self._pending_defaults = deque()
self.finalized = False
self._finalize_mutex = threading.Lock()
self._pending = deque()
self._tasks = tasks
if not isinstance(self._tasks, TaskRegistry):
self._tasks = TaskRegistry(self._tasks or {})
# these options are moved to the config to
# simplify pickling of the app object.
self._preconf = {}
if broker:
self._preconf['BROKER_URL'] = broker
if include:
self._preconf['CELERY_IMPORTS'] = include
if self.set_as_current:
self.set_current()
self.on_init()
_register_app(self)
def set_current(self):
_tls.current_app = self
def __enter__(self):
return self
def __exit__(self, *exc_info):
self.close()
def close(self):
self._maybe_close_pool()
def on_init(self):
"""Optional callback called at init."""
pass
def start(self, argv=None):
return instantiate(
'celery.bin.celery:CeleryCommand',
app=self).execute_from_commandline(argv)
def worker_main(self, argv=None):
return instantiate(
'celery.bin.celeryd:WorkerCommand',
app=self).execute_from_commandline(argv)
def task(self, *args, **opts):
"""Creates new task class from any callable."""
if _EXECV and not opts.get('_force_evaluate'):
# When using execv the task in the original module will point to a
# different app, so doing things like 'add.request' will point to
# a differnt task instance. This makes sure it will always use
# the task instance from the current app.
# Really need a better solution for this :(
from . import shared_task as proxies_to_curapp
opts['_force_evaluate'] = True # XXX Py2.5
return proxies_to_curapp(*args, **opts)
def inner_create_task_cls(shared=True, filter=None, **opts):
def _create_task_cls(fun):
if shared:
cons = lambda app: app._task_from_fun(fun, **opts)
cons.__name__ = fun.__name__
shared_task(cons)
if self.accept_magic_kwargs: # compat mode
task = self._task_from_fun(fun, **opts)
if filter:
task = filter(task)
return task
# return a proxy object that is only evaluated when first used
promise = PromiseProxy(self._task_from_fun, (fun, ), opts)
self._pending.append(promise)
if filter:
return filter(promise)
return promise
return _create_task_cls
if len(args) == 1 and callable(args[0]):
return inner_create_task_cls(**opts)(*args)
return inner_create_task_cls(**opts)
def _task_from_fun(self, fun, **options):
base = options.pop('base', None) or self.Task
T = type(fun.__name__, (base, ), dict({
'app': self,
'accept_magic_kwargs': False,
'run': staticmethod(fun),
'__doc__': fun.__doc__,
'__module__': fun.__module__}, **options))()
task = self._tasks[T.name] # return global instance.
task.bind(self)
return task
def finalize(self):
with self._finalize_mutex:
if not self.finalized:
self.finalized = True
load_shared_tasks(self)
pending = self._pending
while pending:
maybe_evaluate(pending.popleft())
for task in self._tasks.itervalues():
task.bind(self)
def add_defaults(self, fun):
if not callable(fun):
d, fun = fun, lambda: d
if self.configured:
return self.conf.add_defaults(fun())
self._pending_defaults.append(fun)
def config_from_object(self, obj, silent=False):
del(self.conf)
return self.loader.config_from_object(obj, silent=silent)
def config_from_envvar(self, variable_name, silent=False):
del(self.conf)
return self.loader.config_from_envvar(variable_name, silent=silent)
def config_from_cmdline(self, argv, namespace='celery'):
self.conf.update(self.loader.cmdline_config_parser(argv, namespace))
def send_task(self, name, args=None, kwargs=None, countdown=None,
eta=None, task_id=None, producer=None, connection=None,
result_cls=None, expires=None, queues=None, publisher=None,
**options):
producer = producer or publisher # XXX compat
if self.conf.CELERY_ALWAYS_EAGER: # pragma: no cover
warnings.warn(AlwaysEagerIgnored(
'CELERY_ALWAYS_EAGER has no effect on send_task'))
result_cls = result_cls or self.AsyncResult
router = self.amqp.Router(queues)
options.setdefault('compression',
self.conf.CELERY_MESSAGE_COMPRESSION)
options = router.route(options, name, args, kwargs)
with self.producer_or_acquire(producer) as producer:
return result_cls(producer.publish_task(
name, args, kwargs,
task_id=task_id,
countdown=countdown, eta=eta,
expires=expires, **options
))
def connection(self, hostname=None, userid=None,
password=None, virtual_host=None, port=None, ssl=None,
insist=None, connect_timeout=None, transport=None,
transport_options=None, heartbeat=None, **kwargs):
conf = self.conf
return self.amqp.Connection(
hostname or conf.BROKER_HOST,
userid or conf.BROKER_USER,
password or conf.BROKER_PASSWORD,
virtual_host or conf.BROKER_VHOST,
port or conf.BROKER_PORT,
transport=transport or conf.BROKER_TRANSPORT,
insist=self.either('BROKER_INSIST', insist),
ssl=self.either('BROKER_USE_SSL', ssl),
connect_timeout=self.either(
'BROKER_CONNECTION_TIMEOUT', connect_timeout),
heartbeat=heartbeat,
transport_options=dict(conf.BROKER_TRANSPORT_OPTIONS,
**transport_options or {}))
broker_connection = connection
@contextmanager
def connection_or_acquire(self, connection=None, pool=True,
*args, **kwargs):
if connection:
yield connection
else:
if pool:
with self.pool.acquire(block=True) as connection:
yield connection
else:
with self.connection() as connection:
yield connection
default_connection = connection_or_acquire # XXX compat
@contextmanager
def producer_or_acquire(self, producer=None):
if producer:
yield producer
else:
with self.amqp.producer_pool.acquire(block=True) as producer:
yield producer
default_producer = producer_or_acquire # XXX compat
def with_default_connection(self, fun):
"""With any function accepting a `connection`
keyword argument, establishes a default connection if one is
not already passed to it.
Any automatically established connection will be closed after
the function returns.
**Deprecated**
Use ``with app.connection_or_acquire(connection)`` instead.
"""
@wraps(fun)
def _inner(*args, **kwargs):
connection = kwargs.pop('connection', None)
with self.connection_or_acquire(connection) as c:
return fun(*args, **dict(kwargs, connection=c))
return _inner
def prepare_config(self, c):
"""Prepare configuration before it is merged with the defaults."""
return find_deprecated_settings(c)
def now(self):
return self.loader.now(utc=self.conf.CELERY_ENABLE_UTC)
def mail_admins(self, subject, body, fail_silently=False):
if self.conf.ADMINS:
to = [admin_email for _, admin_email in self.conf.ADMINS]
return self.loader.mail_admins(
subject, body, fail_silently, to=to,
sender=self.conf.SERVER_EMAIL,
host=self.conf.EMAIL_HOST,
port=self.conf.EMAIL_PORT,
user=self.conf.EMAIL_HOST_USER,
password=self.conf.EMAIL_HOST_PASSWORD,
timeout=self.conf.EMAIL_TIMEOUT,
use_ssl=self.conf.EMAIL_USE_SSL,
use_tls=self.conf.EMAIL_USE_TLS,
)
def select_queues(self, queues=None):
return self.amqp.queues.select_subset(queues)
def either(self, default_key, *values):
"""Fallback to the value of a configuration key if none of the
`*values` are true."""
return first(None, values) or self.conf.get(default_key)
def bugreport(self):
return bugreport(self)
def _get_backend(self):
from celery.backends import get_backend_by_url
backend, url = get_backend_by_url(
self.backend_cls or self.conf.CELERY_RESULT_BACKEND,
self.loader)
return backend(app=self, url=url)
def _get_config(self):
self.configured = True
s = Settings({}, [self.prepare_config(self.loader.conf),
deepcopy(DEFAULTS)])
# load lazy config dict initializers.
pending = self._pending_defaults
while pending:
s.add_defaults(pending.popleft()())
if self._preconf:
for key, value in self._preconf.iteritems():
setattr(s, key, value)
return s
def _after_fork(self, obj_):
self._maybe_close_pool()
def _maybe_close_pool(self):
if self._pool:
self._pool.force_close_all()
self._pool = None
amqp = self.amqp
if amqp._producer_pool:
amqp._producer_pool.force_close_all()
amqp._producer_pool = None
def create_task_cls(self):
"""Creates a base task class using default configuration
taken from this app."""
return self.subclass_with_self('celery.app.task:Task', name='Task',
attribute='_app', abstract=True)
def subclass_with_self(self, Class, name=None, attribute='app',
reverse=None, **kw):
"""Subclass an app-compatible class by setting its app attribute
to be this app instance.
App-compatible means that the class has a class attribute that
provides the default app it should use, e.g.
``class Foo: app = None``.
:param Class: The app-compatible class to subclass.
:keyword name: Custom name for the target class.
:keyword attribute: Name of the attribute holding the app,
default is 'app'.
"""
Class = symbol_by_name(Class)
reverse = reverse if reverse else Class.__name__
def __reduce__(self):
return _unpickle_appattr, (reverse, self.__reduce_args__())
attrs = dict({attribute: self}, __module__=Class.__module__,
__doc__=Class.__doc__, __reduce__=__reduce__, **kw)
return type(name or Class.__name__, (Class, ), attrs)
def _rgetattr(self, path):
return reduce(getattr, [self] + path.split('.'))
def __repr__(self):
return '<%s %s:0x%x>' % (self.__class__.__name__,
self.main or '__main__', id(self), )
def __reduce__(self):
# Reduce only pickles the configuration changes,
# so the default configuration doesn't have to be passed
# between processes.
return (
_unpickle_app,
(self.__class__, self.Pickler) + self.__reduce_args__(),
)
def __reduce_args__(self):
return (self.main, self.conf.changes, self.loader_cls,
self.backend_cls, self.amqp_cls, self.events_cls,
self.log_cls, self.control_cls, self.accept_magic_kwargs)
@cached_property
def Worker(self):
return self.subclass_with_self('celery.apps.worker:Worker')
@cached_property
def WorkController(self, **kwargs):
return self.subclass_with_self('celery.worker:WorkController')
@cached_property
def Beat(self, **kwargs):
return self.subclass_with_self('celery.apps.beat:Beat')
@cached_property
def TaskSet(self):
return self.subclass_with_self('celery.task.sets:TaskSet')
@cached_property
def Task(self):
return self.create_task_cls()
@cached_property
def annotations(self):
return prepare_annotations(self.conf.CELERY_ANNOTATIONS)
@cached_property
def AsyncResult(self):
return self.subclass_with_self('celery.result:AsyncResult')
@cached_property
def GroupResult(self):
return self.subclass_with_self('celery.result:GroupResult')
@cached_property
def TaskSetResult(self): # XXX compat
return self.subclass_with_self('celery.result:TaskSetResult')
@property
def pool(self):
if self._pool is None:
register_after_fork(self, self._after_fork)
limit = self.conf.BROKER_POOL_LIMIT
self._pool = self.connection().Pool(limit=limit)
return self._pool
@property
def current_task(self):
return _task_stack.top
@cached_property
def amqp(self):
return instantiate(self.amqp_cls, app=self)
@cached_property
def backend(self):
return self._get_backend()
@cached_property
def conf(self):
return self._get_config()
@cached_property
def control(self):
return instantiate(self.control_cls, app=self)
@cached_property
def events(self):
return instantiate(self.events_cls, app=self)
@cached_property
def loader(self):
return get_loader_cls(self.loader_cls)(app=self)
@cached_property
def log(self):
return instantiate(self.log_cls, app=self)
@cached_property
def tasks(self):
self.finalize()
return self._tasks
App = Celery # compat
| bsd-3-clause | 45f1687fac40be3084086798960061f7 | 33.678788 | 78 | 0.594955 | 4.127434 | false | false | false | false |
mozilla/firefox-flicks | vendor-local/lib/python/celery/tests/utilities/test_imports.py | 1 | 2006 | from __future__ import absolute_import
from __future__ import with_statement
from mock import Mock, patch
from celery.utils.imports import (
qualname,
symbol_by_name,
reload_from_cwd,
module_file,
find_module,
NotAPackage,
)
from celery.tests.utils import Case
class test_import_utils(Case):
def test_find_module(self):
self.assertTrue(find_module('celery'))
imp = Mock()
imp.return_value = None
with self.assertRaises(NotAPackage):
find_module('foo.bar.baz', imp=imp)
def test_qualname(self):
Class = type('Fox', (object, ), {'__module__': 'quick.brown'})
self.assertEqual(qualname(Class), 'quick.brown.Fox')
self.assertEqual(qualname(Class()), 'quick.brown.Fox')
def test_symbol_by_name__instance_returns_instance(self):
instance = object()
self.assertIs(symbol_by_name(instance), instance)
def test_symbol_by_name_returns_default(self):
default = object()
self.assertIs(
symbol_by_name('xyz.ryx.qedoa.weq:foz', default=default),
default,
)
def test_symbol_by_name_package(self):
from celery.worker import WorkController
self.assertIs(
symbol_by_name('.worker:WorkController', package='celery'),
WorkController,
)
self.assertTrue(symbol_by_name(':group', package='celery'))
@patch('celery.utils.imports.reload')
def test_reload_from_cwd(self, reload):
reload_from_cwd('foo')
self.assertTrue(reload.called)
def test_reload_from_cwd_custom_reloader(self):
reload = Mock()
reload_from_cwd('foo', reload)
self.assertTrue(reload.called)
def test_module_file(self):
m1 = Mock()
m1.__file__ = '/opt/foo/xyz.pyc'
self.assertEqual(module_file(m1), '/opt/foo/xyz.py')
m2 = Mock()
m2.__file__ = '/opt/foo/xyz.py'
self.assertEqual(module_file(m1), '/opt/foo/xyz.py')
| bsd-3-clause | 73136b7616754e12d84d176e222a0585 | 28.940299 | 71 | 0.612662 | 3.569395 | false | true | false | false |
mozilla/firefox-flicks | vendor-local/lib/python/requests/packages/urllib3/poolmanager.py | 15 | 5354 | # urllib3/poolmanager.py
# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import logging
from ._collections import RecentlyUsedContainer
from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool
from .connectionpool import connection_from_url, port_by_scheme
from .request import RequestMethods
from .util import parse_url
__all__ = ['PoolManager', 'ProxyManager', 'proxy_from_url']
pool_classes_by_scheme = {
'http': HTTPConnectionPool,
'https': HTTPSConnectionPool,
}
log = logging.getLogger(__name__)
class PoolManager(RequestMethods):
"""
Allows for arbitrary requests while transparently keeping track of
necessary connection pools for you.
:param num_pools:
Number of connection pools to cache before discarding the least
recently used pool.
:param headers:
Headers to include with all requests, unless other headers are given
explicitly.
:param \**connection_pool_kw:
Additional parameters are used to create fresh
:class:`urllib3.connectionpool.ConnectionPool` instances.
Example: ::
>>> manager = PoolManager(num_pools=2)
>>> r = manager.request('GET', 'http://google.com/')
>>> r = manager.request('GET', 'http://google.com/mail')
>>> r = manager.request('GET', 'http://yahoo.com/')
>>> len(manager.pools)
2
"""
def __init__(self, num_pools=10, headers=None, **connection_pool_kw):
RequestMethods.__init__(self, headers)
self.connection_pool_kw = connection_pool_kw
self.pools = RecentlyUsedContainer(num_pools,
dispose_func=lambda p: p.close())
def clear(self):
"""
Empty our store of pools and direct them all to close.
This will not affect in-flight connections, but they will not be
re-used after completion.
"""
self.pools.clear()
def connection_from_host(self, host, port=None, scheme='http'):
"""
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``.
"""
port = port or port_by_scheme.get(scheme, 80)
pool_key = (scheme, host, port)
# If the scheme, host, or port doesn't match existing open connections,
# open a new ConnectionPool.
pool = self.pools.get(pool_key)
if pool:
return pool
# Make a fresh ConnectionPool of the desired type
pool_cls = pool_classes_by_scheme[scheme]
pool = pool_cls(host, port, **self.connection_pool_kw)
self.pools[pool_key] = pool
return pool
def connection_from_url(self, url):
"""
Similar to :func:`urllib3.connectionpool.connection_from_url` but
doesn't pass any additional parameters to the
:class:`urllib3.connectionpool.ConnectionPool` constructor.
Additional parameters are taken from the :class:`.PoolManager`
constructor.
"""
u = parse_url(url)
return self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
def urlopen(self, method, url, redirect=True, **kw):
"""
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.
"""
u = parse_url(url)
conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
kw['assert_same_host'] = False
kw['redirect'] = False
if 'headers' not in kw:
kw['headers'] = self.headers
response = conn.urlopen(method, u.request_uri, **kw)
redirect_location = redirect and response.get_redirect_location()
if not redirect_location:
return response
if response.status == 303:
method = 'GET'
log.info("Redirecting %s -> %s" % (url, redirect_location))
kw['retries'] = kw.get('retries', 3) - 1 # Persist retries countdown
return self.urlopen(method, redirect_location, **kw)
class ProxyManager(RequestMethods):
"""
Given a ConnectionPool to a proxy, the ProxyManager's ``urlopen`` method
will make requests to any url through the defined proxy.
"""
def __init__(self, proxy_pool):
self.proxy_pool = proxy_pool
def _set_proxy_headers(self, headers=None):
headers_ = {'Accept': '*/*'}
if headers:
headers_.update(headers)
return headers_
def urlopen(self, method, url, **kw):
"Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
kw['assert_same_host'] = False
kw['headers'] = self._set_proxy_headers(kw.get('headers'))
return self.proxy_pool.urlopen(method, url, **kw)
def proxy_from_url(url, **pool_kw):
proxy_pool = connection_from_url(url, **pool_kw)
return ProxyManager(proxy_pool)
| bsd-3-clause | c52448f308d1881fdc3734df6cb01829 | 31.846626 | 79 | 0.632051 | 4.049924 | false | false | false | false |
mozilla/firefox-flicks | vendor-local/lib/python/celery/tests/contrib/test_migrate.py | 1 | 3725 | from __future__ import absolute_import
from __future__ import with_statement
from kombu import Connection, Producer, Queue, Exchange
from kombu.exceptions import StdChannelError
from mock import patch
from celery.contrib.migrate import (
State,
migrate_task,
migrate_tasks,
)
from celery.utils.encoding import bytes_t, ensure_bytes
from celery.tests.utils import AppCase, Case, Mock
def Message(body, exchange='exchange', routing_key='rkey',
compression=None, content_type='application/json',
content_encoding='utf-8'):
return Mock(
attrs={
'body': body,
'delivery_info': {
'exchange': exchange,
'routing_key': routing_key,
},
'headers': {
'compression': compression,
},
'content_type': content_type,
'content_encoding': content_encoding,
'properties': {}
},
)
class test_State(Case):
def test_strtotal(self):
x = State()
self.assertEqual(x.strtotal, u'?')
x.total_apx = 100
self.assertEqual(x.strtotal, u'100')
class test_migrate_task(Case):
def test_removes_compression_header(self):
x = Message('foo', compression='zlib')
producer = Mock()
migrate_task(producer, x.body, x)
self.assertTrue(producer.publish.called)
args, kwargs = producer.publish.call_args
self.assertIsInstance(args[0], bytes_t)
self.assertNotIn('compression', kwargs['headers'])
self.assertEqual(kwargs['compression'], 'zlib')
self.assertEqual(kwargs['content_type'], 'application/json')
self.assertEqual(kwargs['content_encoding'], 'utf-8')
self.assertEqual(kwargs['exchange'], 'exchange')
self.assertEqual(kwargs['routing_key'], 'rkey')
class test_migrate_tasks(AppCase):
def test_migrate(self, name='testcelery'):
x = Connection('memory://foo')
y = Connection('memory://foo')
# use separate state
x.default_channel.queues = {}
y.default_channel.queues = {}
ex = Exchange(name, 'direct')
q = Queue(name, exchange=ex, routing_key=name)
q(x.default_channel).declare()
Producer(x).publish('foo', exchange=name, routing_key=name)
Producer(x).publish('bar', exchange=name, routing_key=name)
Producer(x).publish('baz', exchange=name, routing_key=name)
self.assertTrue(x.default_channel.queues)
self.assertFalse(y.default_channel.queues)
migrate_tasks(x, y)
yq = q(y.default_channel)
self.assertEqual(yq.get().body, ensure_bytes('foo'))
self.assertEqual(yq.get().body, ensure_bytes('bar'))
self.assertEqual(yq.get().body, ensure_bytes('baz'))
Producer(x).publish('foo', exchange=name, routing_key=name)
callback = Mock()
migrate_tasks(x, y, callback=callback)
self.assertTrue(callback.called)
migrate = Mock()
Producer(x).publish('baz', exchange=name, routing_key=name)
migrate_tasks(x, y, callback=callback, migrate=migrate)
self.assertTrue(migrate.called)
with patch('kombu.transport.virtual.Channel.queue_declare') as qd:
def effect(*args, **kwargs):
if kwargs.get('passive'):
raise StdChannelError()
return 0, 3, 0
qd.side_effect = effect
migrate_tasks(x, y)
x = Connection('memory://')
x.default_channel.queues = {}
y.default_channel.queues = {}
callback = Mock()
migrate_tasks(x, y, callback=callback)
self.assertFalse(callback.called)
| bsd-3-clause | 491de373fad557d17026e1edda431fa4 | 32.558559 | 74 | 0.60349 | 3.950159 | false | true | false | false |
mozilla/firefox-flicks | vendor-local/lib/python/celery/utils/timer2.py | 1 | 10044 | # -*- coding: utf-8 -*-
"""
timer2
~~~~~~
Scheduler for Python functions.
"""
from __future__ import absolute_import
from __future__ import with_statement
import atexit
import heapq
import os
import sys
import threading
from datetime import datetime
from functools import wraps
from itertools import count
from time import time, sleep
from celery.utils.compat import THREAD_TIMEOUT_MAX
from celery.utils.timeutils import timedelta_seconds, timezone
from kombu.log import get_logger
VERSION = (1, 0, 0)
__version__ = '.'.join(map(str, VERSION))
__author__ = 'Ask Solem'
__contact__ = 'ask@celeryproject.org'
__homepage__ = 'http://github.com/ask/timer2/'
__docformat__ = 'restructuredtext'
DEFAULT_MAX_INTERVAL = 2
TIMER_DEBUG = os.environ.get('TIMER_DEBUG')
EPOCH = datetime.utcfromtimestamp(0).replace(tzinfo=timezone.utc)
logger = get_logger('timer2')
class Entry(object):
cancelled = False
def __init__(self, fun, args=None, kwargs=None):
self.fun = fun
self.args = args or []
self.kwargs = kwargs or {}
self.tref = self
def __call__(self):
return self.fun(*self.args, **self.kwargs)
def cancel(self):
self.tref.cancelled = True
def __repr__(self):
return '<TimerEntry: %s(*%r, **%r)' % (
self.fun.__name__, self.args, self.kwargs)
if sys.version_info[0] == 3: # pragma: no cover
def __hash__(self):
return hash('|'.join(map(repr, (self.fun, self.args,
self.kwargs))))
def __lt__(self, other):
return hash(self) < hash(other)
def __gt__(self, other):
return hash(self) > hash(other)
def __eq__(self, other):
return hash(self) == hash(other)
def to_timestamp(d, default_timezone=timezone.utc):
if isinstance(d, datetime):
if d.tzinfo is None:
d = d.replace(tzinfo=default_timezone)
return timedelta_seconds(d - EPOCH)
return d
class Schedule(object):
"""ETA scheduler."""
Entry = Entry
on_error = None
def __init__(self, max_interval=None, on_error=None, **kwargs):
self.max_interval = float(max_interval or DEFAULT_MAX_INTERVAL)
self.on_error = on_error or self.on_error
self._queue = []
def apply_entry(self, entry):
try:
entry()
except Exception, exc:
if not self.handle_error(exc):
logger.error('Error in timer: %r', exc, exc_info=True)
def handle_error(self, exc_info):
if self.on_error:
self.on_error(exc_info)
return True
def stop(self):
pass
def enter(self, entry, eta=None, priority=0):
"""Enter function into the scheduler.
:param entry: Item to enter.
:keyword eta: Scheduled time as a :class:`datetime.datetime` object.
:keyword priority: Unused.
"""
if eta is None:
eta = time()
if isinstance(eta, datetime):
try:
eta = to_timestamp(eta)
except Exception, exc:
if not self.handle_error(exc):
raise
return
return self._enter(eta, priority, entry)
def _enter(self, eta, priority, entry):
heapq.heappush(self._queue, (eta, priority, entry))
return entry
def apply_at(self, eta, fun, args=(), kwargs={}, priority=0):
return self.enter(self.Entry(fun, args, kwargs), eta, priority)
def enter_after(self, msecs, entry, priority=0):
return self.enter(entry, time() + (msecs / 1000.0), priority)
def apply_after(self, msecs, fun, args=(), kwargs={}, priority=0):
return self.enter_after(msecs, self.Entry(fun, args, kwargs), priority)
def apply_interval(self, msecs, fun, args=(), kwargs={}, priority=0):
tref = self.Entry(fun, args, kwargs)
secs = msecs * 1000.0
@wraps(fun)
def _reschedules(*args, **kwargs):
last, now = tref._last_run, time()
lsince = (now - tref._last_run) * 1000.0 if last else msecs
try:
if lsince and lsince >= msecs:
tref._last_run = now
return fun(*args, **kwargs)
finally:
if not tref.cancelled:
last = tref._last_run
next = secs - (now - last) if last else secs
self.enter_after(next / 1000.0, tref, priority)
tref.fun = _reschedules
tref._last_run = None
return self.enter_after(msecs, tref, priority)
@property
def schedule(self):
return self
def __iter__(self):
"""The iterator yields the time to sleep for between runs."""
# localize variable access
nowfun = time
pop = heapq.heappop
max_interval = self.max_interval
queue = self._queue
while 1:
if queue:
eta, priority, entry = verify = queue[0]
now = nowfun()
if now < eta:
yield min(eta - now, max_interval), None
else:
event = pop(queue)
if event is verify:
if not entry.cancelled:
yield None, entry
continue
else:
heapq.heappush(queue, event)
else:
yield None, None
def empty(self):
"""Is the schedule empty?"""
return not self._queue
def clear(self):
self._queue[:] = [] # used because we can't replace the object
# and the operation is atomic.
def info(self):
return ({'eta': eta, 'priority': priority, 'item': item}
for eta, priority, item in self.queue)
def cancel(self, tref):
tref.cancel()
@property
def queue(self):
events = list(self._queue)
return map(heapq.heappop, [events] * len(events))
class Timer(threading.Thread):
Entry = Entry
Schedule = Schedule
running = False
on_tick = None
_timer_count = count(1).next
if TIMER_DEBUG: # pragma: no cover
def start(self, *args, **kwargs):
import traceback
print('- Timer starting')
traceback.print_stack()
super(Timer, self).start(*args, **kwargs)
def __init__(self, schedule=None, on_error=None, on_tick=None,
max_interval=None, **kwargs):
self.schedule = schedule or self.Schedule(on_error=on_error,
max_interval=max_interval)
self.on_tick = on_tick or self.on_tick
threading.Thread.__init__(self)
self._is_shutdown = threading.Event()
self._is_stopped = threading.Event()
self.mutex = threading.Lock()
self.not_empty = threading.Condition(self.mutex)
self.setDaemon(True)
self.setName('Timer-%s' % (self._timer_count(), ))
def _next_entry(self):
with self.not_empty:
delay, entry = self.scheduler.next()
if entry is None:
if delay is None:
self.not_empty.wait(1.0)
return delay
return self.schedule.apply_entry(entry)
__next__ = next = _next_entry # for 2to3
def run(self):
try:
self.running = True
self.scheduler = iter(self.schedule)
while not self._is_shutdown.isSet():
delay = self._next_entry()
if delay:
if self.on_tick:
self.on_tick(delay)
if sleep is None: # pragma: no cover
break
sleep(delay)
try:
self._is_stopped.set()
except TypeError: # pragma: no cover
# we lost the race at interpreter shutdown,
# so gc collected built-in modules.
pass
except Exception, exc:
logger.error('Thread Timer crashed: %r', exc, exc_info=True)
os._exit(1)
def stop(self):
if self.running:
self._is_shutdown.set()
self._is_stopped.wait()
self.join(THREAD_TIMEOUT_MAX)
self.running = False
def ensure_started(self):
if not self.running and not self.isAlive():
self.start()
def _do_enter(self, meth, *args, **kwargs):
self.ensure_started()
with self.mutex:
entry = getattr(self.schedule, meth)(*args, **kwargs)
self.not_empty.notify()
return entry
def enter(self, entry, eta, priority=None):
return self._do_enter('enter', entry, eta, priority=priority)
def apply_at(self, *args, **kwargs):
return self._do_enter('apply_at', *args, **kwargs)
def enter_after(self, *args, **kwargs):
return self._do_enter('enter_after', *args, **kwargs)
def apply_after(self, *args, **kwargs):
return self._do_enter('apply_after', *args, **kwargs)
def apply_interval(self, *args, **kwargs):
return self._do_enter('apply_interval', *args, **kwargs)
def exit_after(self, msecs, priority=10):
self.apply_after(msecs, sys.exit, priority)
def cancel(self, tref):
tref.cancel()
def clear(self):
self.schedule.clear()
def empty(self):
return self.schedule.empty()
@property
def queue(self):
return self.schedule.queue
default_timer = _default_timer = Timer()
apply_after = _default_timer.apply_after
apply_at = _default_timer.apply_at
apply_interval = _default_timer.apply_interval
enter_after = _default_timer.enter_after
enter = _default_timer.enter
exit_after = _default_timer.exit_after
cancel = _default_timer.cancel
clear = _default_timer.clear
atexit.register(_default_timer.stop)
| bsd-3-clause | ad74caaaf824a5e7d8dd31b917ff2308 | 28.715976 | 79 | 0.551772 | 3.949666 | false | false | false | false |
mozilla/firefox-flicks | vendor-local/lib/python/celery/app/builtins.py | 1 | 12278 | # -*- coding: utf-8 -*-
"""
celery.app.builtins
~~~~~~~~~~~~~~~~~~~
Built-in tasks that are always available in all
app instances. E.g. chord, group and xmap.
"""
from __future__ import absolute_import
from __future__ import with_statement
from collections import deque
from itertools import starmap
from celery._state import get_current_worker_task
from celery.utils import uuid
#: global list of functions defining tasks that should be
#: added to all apps.
_shared_tasks = []
def shared_task(constructor):
"""Decorator that specifies that the decorated function is a function
that generates a built-in task.
The function will then be called for every new app instance created
(lazily, so more exactly when the task registry for that app is needed).
"""
_shared_tasks.append(constructor)
return constructor
def load_shared_tasks(app):
"""Loads the built-in tasks for an app instance."""
for constructor in _shared_tasks:
constructor(app)
@shared_task
def add_backend_cleanup_task(app):
"""The backend cleanup task can be used to clean up the default result
backend.
This task is also added do the periodic task schedule so that it is
run every day at midnight, but :program:`celerybeat` must be running
for this to be effective.
Note that not all backends do anything for this, what needs to be
done at cleanup is up to each backend, and some backends
may even clean up in realtime so that a periodic cleanup is not necessary.
"""
@app.task(name='celery.backend_cleanup', _force_evaluate=True)
def backend_cleanup():
app.backend.cleanup()
return backend_cleanup
@shared_task
def add_unlock_chord_task(app):
"""The unlock chord task is used by result backends that doesn't
have native chord support.
It creates a task chain polling the header for completion.
"""
from celery.canvas import subtask
from celery import result as _res
@app.task(name='celery.chord_unlock', max_retries=None,
default_retry_delay=1, ignore_result=True, _force_evaluate=True)
def unlock_chord(group_id, callback, interval=None, propagate=False,
max_retries=None, result=None):
if interval is None:
interval = unlock_chord.default_retry_delay
result = _res.GroupResult(group_id, map(_res.AsyncResult, result))
j = result.join_native if result.supports_native_join else result.join
if result.ready():
subtask(callback).delay(j(propagate=propagate))
else:
return unlock_chord.retry(countdown=interval,
max_retries=max_retries)
return unlock_chord
@shared_task
def add_map_task(app):
from celery.canvas import subtask
@app.task(name='celery.map', _force_evaluate=True)
def xmap(task, it):
task = subtask(task).type
return list(map(task, it))
return xmap
@shared_task
def add_starmap_task(app):
from celery.canvas import subtask
@app.task(name='celery.starmap', _force_evaluate=True)
def xstarmap(task, it):
task = subtask(task).type
return list(starmap(task, it))
return xstarmap
@shared_task
def add_chunk_task(app):
from celery.canvas import chunks as _chunks
@app.task(name='celery.chunks', _force_evaluate=True)
def chunks(task, it, n):
return _chunks.apply_chunks(task, it, n)
return chunks
@shared_task
def add_group_task(app):
_app = app
from celery.canvas import maybe_subtask, subtask
from celery.result import from_serializable
class Group(app.Task):
app = _app
name = 'celery.group'
accept_magic_kwargs = False
def run(self, tasks, result, group_id, partial_args):
app = self.app
result = from_serializable(result)
# any partial args are added to all tasks in the group
taskit = (subtask(task).clone(partial_args)
for i, task in enumerate(tasks))
if self.request.is_eager or app.conf.CELERY_ALWAYS_EAGER:
return app.GroupResult(
result.id,
[task.apply(group_id=group_id) for task in taskit],
)
with app.producer_or_acquire() as pub:
[task.apply_async(group_id=group_id, publisher=pub,
add_to_parent=False) for task in taskit]
parent = get_current_worker_task()
if parent:
parent.request.children.append(result)
return result
def prepare(self, options, tasks, args, **kwargs):
AsyncResult = self.AsyncResult
options['group_id'] = group_id = (
options.setdefault('task_id', uuid()))
def prepare_member(task):
task = maybe_subtask(task)
opts = task.options
opts['group_id'] = group_id
try:
tid = opts['task_id']
except KeyError:
tid = opts['task_id'] = uuid()
return task, AsyncResult(tid)
try:
tasks, results = zip(*[prepare_member(task) for task in tasks])
except ValueError: # tasks empty
tasks, results = [], []
return (tasks, self.app.GroupResult(group_id, results),
group_id, args)
def apply_async(self, partial_args=(), kwargs={}, **options):
if self.app.conf.CELERY_ALWAYS_EAGER:
return self.apply(partial_args, kwargs, **options)
tasks, result, gid, args = self.prepare(
options, args=partial_args, **kwargs
)
super(Group, self).apply_async((
list(tasks), result.serializable(), gid, args), **options
)
return result
def apply(self, args=(), kwargs={}, **options):
return super(Group, self).apply(
self.prepare(options, args=args, **kwargs),
**options).get()
return Group
@shared_task
def add_chain_task(app):
from celery.canvas import Signature, chord, group, maybe_subtask
_app = app
class Chain(app.Task):
app = _app
name = 'celery.chain'
accept_magic_kwargs = False
def prepare_steps(self, args, tasks):
steps = deque(tasks)
next_step = prev_task = prev_res = None
tasks, results = [], []
i = 0
while steps:
# First task get partial args from chain.
task = maybe_subtask(steps.popleft())
task = task.clone() if i else task.clone(args)
res = task._freeze()
i += 1
if isinstance(task, group):
# automatically upgrade group(..) | s to chord(group, s)
try:
next_step = steps.popleft()
# for chords we freeze by pretending it's a normal
# task instead of a group.
res = Signature._freeze(task)
task = chord(task, body=next_step, task_id=res.task_id)
except IndexError:
pass
if prev_task:
# link previous task to this task.
prev_task.link(task)
# set the results parent attribute.
res.parent = prev_res
results.append(res)
tasks.append(task)
prev_task, prev_res = task, res
return tasks, results
def apply_async(self, args=(), kwargs={}, group_id=None, chord=None,
task_id=None, **options):
if self.app.conf.CELERY_ALWAYS_EAGER:
return self.apply(args, kwargs, **options)
options.pop('publisher', None)
tasks, results = self.prepare_steps(args, kwargs['tasks'])
result = results[-1]
if group_id:
tasks[-1].set(group_id=group_id)
if chord:
tasks[-1].set(chord=chord)
if task_id:
tasks[-1].set(task_id=task_id)
result = tasks[-1].type.AsyncResult(task_id)
tasks[0].apply_async()
return result
def apply(self, args=(), kwargs={}, subtask=maybe_subtask, **options):
last, fargs = None, args # fargs passed to first task only
for task in kwargs['tasks']:
res = subtask(task).clone(fargs).apply(last and (last.get(), ))
res.parent, last, fargs = last, res, None
return last
return Chain
@shared_task
def add_chord_task(app):
"""Every chord is executed in a dedicated task, so that the chord
can be used as a subtask, and this generates the task
responsible for that."""
from celery import group
from celery.canvas import maybe_subtask
_app = app
class Chord(app.Task):
app = _app
name = 'celery.chord'
accept_magic_kwargs = False
ignore_result = False
def run(self, header, body, partial_args=(), interval=1,
max_retries=None, propagate=False, eager=False, **kwargs):
group_id = uuid()
AsyncResult = self.app.AsyncResult
prepare_member = self._prepare_member
# - convert back to group if serialized
tasks = header.tasks if isinstance(header, group) else header
header = group([maybe_subtask(s).clone() for s in tasks])
# - eager applies the group inline
if eager:
return header.apply(args=partial_args, task_id=group_id)
results = [AsyncResult(prepare_member(task, body, group_id))
for task in header.tasks]
# - fallback implementations schedules the chord_unlock task here
app.backend.on_chord_apply(group_id, body,
interval=interval,
max_retries=max_retries,
propagate=propagate,
result=results)
# - call the header group, returning the GroupResult.
# XXX Python 2.5 doesn't allow kwargs after star-args.
return header(*partial_args, **{'task_id': group_id})
def _prepare_member(self, task, body, group_id):
opts = task.options
# d.setdefault would work but generating uuid's are expensive
try:
task_id = opts['task_id']
except KeyError:
task_id = opts['task_id'] = uuid()
opts.update(chord=body, group_id=group_id)
return task_id
def apply_async(self, args=(), kwargs={}, task_id=None, **options):
if self.app.conf.CELERY_ALWAYS_EAGER:
return self.apply(args, kwargs, **options)
group_id = options.pop('group_id', None)
chord = options.pop('chord', None)
header = kwargs.pop('header')
body = kwargs.pop('body')
header, body = (list(maybe_subtask(header)),
maybe_subtask(body))
if group_id:
body.set(group_id=group_id)
if chord:
body.set(chord=chord)
callback_id = body.options.setdefault('task_id', task_id or uuid())
parent = super(Chord, self).apply_async((header, body, args),
kwargs, **options)
body_result = self.AsyncResult(callback_id)
body_result.parent = parent
return body_result
def apply(self, args=(), kwargs={}, propagate=True, **options):
body = kwargs['body']
res = super(Chord, self).apply(args, dict(kwargs, eager=True),
**options)
return maybe_subtask(body).apply(
args=(res.get(propagate=propagate).get(), ))
return Chord
| bsd-3-clause | f03cd460a1c7fc7a8de8c83e681fdec3 | 35.325444 | 79 | 0.558153 | 4.28402 | false | false | false | false |
mozilla/firefox-flicks | vendor-local/lib/python/celery/worker/mediator.py | 1 | 2304 | # -*- coding: utf-8 -*-
"""
celery.worker.mediator
~~~~~~~~~~~~~~~~~~~~~~
The mediator is an internal thread that moves tasks
from an internal :class:`Queue` to the worker pool.
This is only used if rate limits are enabled, as it moves
messages from the rate limited queue (which holds tasks
that are allowed to be processed) to the pool. Disabling
rate limits will also disable this machinery,
and can improve performance.
"""
from __future__ import absolute_import
import logging
from Queue import Empty
from celery.app import app_or_default
from celery.utils.threads import bgThread
from celery.utils.log import get_logger
from .bootsteps import StartStopComponent
logger = get_logger(__name__)
class WorkerComponent(StartStopComponent):
name = 'worker.mediator'
requires = ('pool', 'queues', )
def __init__(self, w, **kwargs):
w.mediator = None
def include_if(self, w):
return w.start_mediator
def create(self, w):
m = w.mediator = self.instantiate(w.mediator_cls, w.ready_queue,
app=w.app, callback=w.process_task)
return m
class Mediator(bgThread):
"""Mediator thread."""
#: The task queue, a :class:`~Queue.Queue` instance.
ready_queue = None
#: Callback called when a task is obtained.
callback = None
def __init__(self, ready_queue, callback, app=None, **kw):
self.app = app_or_default(app)
self.ready_queue = ready_queue
self.callback = callback
self._does_debug = logger.isEnabledFor(logging.DEBUG)
super(Mediator, self).__init__()
def body(self):
try:
task = self.ready_queue.get(timeout=1.0)
except Empty:
return
if self._does_debug:
logger.debug('Mediator: Running callback for task: %s[%s]',
task.name, task.id)
try:
self.callback(task)
except Exception, exc:
logger.error('Mediator callback raised exception %r',
exc, exc_info=True,
extra={'data': {'id': task.id,
'name': task.name,
'hostname': task.hostname}})
| bsd-3-clause | a88f3e22c667b0447700ef8e0067e78c | 27.8 | 77 | 0.582031 | 4.121646 | false | false | false | false |
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_1_0_6/models/communicationrequest.py | 1 | 6718 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 1.0.2.7202 (http://hl7.org/fhir/StructureDefinition/CommunicationRequest) on 2016-06-23.
# 2016, SMART Health IT.
from . import domainresource
class CommunicationRequest(domainresource.DomainResource):
""" A request for information to be sent to a receiver.
A request to convey information; e.g. the CDS system proposes that an alert
be sent to a responsible provider, the CDS system proposes that the public
health agency be notified about a reportable condition.
"""
resource_name = "CommunicationRequest"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.category = None
""" Message category.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.encounter = None
""" Encounter leading to message.
Type `FHIRReference` referencing `Encounter` (represented as `dict` in JSON). """
self.identifier = None
""" Unique identifier.
List of `Identifier` items (represented as `dict` in JSON). """
self.medium = None
""" A channel of communication.
List of `CodeableConcept` items (represented as `dict` in JSON). """
self.payload = None
""" Message payload.
List of `CommunicationRequestPayload` items (represented as `dict` in JSON). """
self.priority = None
""" Message urgency.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.reason = None
""" Indication for message.
List of `CodeableConcept` items (represented as `dict` in JSON). """
self.recipient = None
""" Message recipient.
List of `FHIRReference` items referencing `Device, Organization, Patient, Practitioner, RelatedPerson` (represented as `dict` in JSON). """
self.requestedOn = None
""" When ordered or proposed.
Type `FHIRDate` (represented as `str` in JSON). """
self.requester = None
""" An individual who requested a communication.
Type `FHIRReference` referencing `Practitioner, Patient, RelatedPerson` (represented as `dict` in JSON). """
self.scheduledDateTime = None
""" When scheduled.
Type `FHIRDate` (represented as `str` in JSON). """
self.scheduledPeriod = None
""" When scheduled.
Type `Period` (represented as `dict` in JSON). """
self.sender = None
""" Message sender.
Type `FHIRReference` referencing `Device, Organization, Patient, Practitioner, RelatedPerson` (represented as `dict` in JSON). """
self.status = None
""" proposed | planned | requested | received | accepted | in-progress
| completed | suspended | rejected | failed.
Type `str`. """
self.subject = None
""" Focus of message.
Type `FHIRReference` referencing `Patient` (represented as `dict` in JSON). """
super(CommunicationRequest, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(CommunicationRequest, self).elementProperties()
js.extend([
("category", "category", codeableconcept.CodeableConcept, False, None, False),
("encounter", "encounter", fhirreference.FHIRReference, False, None, False),
("identifier", "identifier", identifier.Identifier, True, None, False),
("medium", "medium", codeableconcept.CodeableConcept, True, None, False),
("payload", "payload", CommunicationRequestPayload, True, None, False),
("priority", "priority", codeableconcept.CodeableConcept, False, None, False),
("reason", "reason", codeableconcept.CodeableConcept, True, None, False),
("recipient", "recipient", fhirreference.FHIRReference, True, None, False),
("requestedOn", "requestedOn", fhirdate.FHIRDate, False, None, False),
("requester", "requester", fhirreference.FHIRReference, False, None, False),
("scheduledDateTime", "scheduledDateTime", fhirdate.FHIRDate, False, "scheduled", False),
("scheduledPeriod", "scheduledPeriod", period.Period, False, "scheduled", False),
("sender", "sender", fhirreference.FHIRReference, False, None, False),
("status", "status", str, False, None, False),
("subject", "subject", fhirreference.FHIRReference, False, None, False),
])
return js
from . import backboneelement
class CommunicationRequestPayload(backboneelement.BackboneElement):
""" Message payload.
Text, attachment(s), or resource(s) to be communicated to the recipient.
"""
resource_name = "CommunicationRequestPayload"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.contentAttachment = None
""" Message part content.
Type `Attachment` (represented as `dict` in JSON). """
self.contentReference = None
""" Message part content.
Type `FHIRReference` referencing `Resource` (represented as `dict` in JSON). """
self.contentString = None
""" Message part content.
Type `str`. """
super(CommunicationRequestPayload, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(CommunicationRequestPayload, self).elementProperties()
js.extend([
("contentAttachment", "contentAttachment", attachment.Attachment, False, "content", True),
("contentReference", "contentReference", fhirreference.FHIRReference, False, "content", True),
("contentString", "contentString", str, False, "content", True),
])
return js
from . import attachment
from . import codeableconcept
from . import fhirdate
from . import fhirreference
from . import identifier
from . import period
| bsd-3-clause | b5b5dd5b5e03037dd7f832b359b47526 | 40.9875 | 147 | 0.625484 | 4.487642 | false | false | false | false |
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_1_0_6/models/medicationorder.py | 1 | 14548 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 1.0.2.7202 (http://hl7.org/fhir/StructureDefinition/MedicationOrder) on 2016-06-23.
# 2016, SMART Health IT.
from . import domainresource
class MedicationOrder(domainresource.DomainResource):
""" Prescription of medication to for patient.
An order for both supply of the medication and the instructions for
administration of the medication to a patient. The resource is called
"MedicationOrder" rather than "MedicationPrescription" to generalize the
use across inpatient and outpatient settings as well as for care plans,
etc.
"""
resource_name = "MedicationOrder"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.dateEnded = None
""" When prescription was stopped.
Type `FHIRDate` (represented as `str` in JSON). """
self.dateWritten = None
""" When prescription was authorized.
Type `FHIRDate` (represented as `str` in JSON). """
self.dispenseRequest = None
""" Medication supply authorization.
Type `MedicationOrderDispenseRequest` (represented as `dict` in JSON). """
self.dosageInstruction = None
""" How medication should be taken.
List of `MedicationOrderDosageInstruction` items (represented as `dict` in JSON). """
self.encounter = None
""" Created during encounter/admission/stay.
Type `FHIRReference` referencing `Encounter` (represented as `dict` in JSON). """
self.identifier = None
""" External identifier.
List of `Identifier` items (represented as `dict` in JSON). """
self.medicationCodeableConcept = None
""" Medication to be taken.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.medicationReference = None
""" Medication to be taken.
Type `FHIRReference` referencing `Medication` (represented as `dict` in JSON). """
self.note = None
""" Information about the prescription.
Type `str`. """
self.patient = None
""" Who prescription is for.
Type `FHIRReference` referencing `Patient` (represented as `dict` in JSON). """
self.prescriber = None
""" Who ordered the medication(s).
Type `FHIRReference` referencing `Practitioner` (represented as `dict` in JSON). """
self.priorPrescription = None
""" An order/prescription that this supersedes.
Type `FHIRReference` referencing `MedicationOrder` (represented as `dict` in JSON). """
self.reasonCodeableConcept = None
""" Reason or indication for writing the prescription.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.reasonEnded = None
""" Why prescription was stopped.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.reasonReference = None
""" Reason or indication for writing the prescription.
Type `FHIRReference` referencing `Condition` (represented as `dict` in JSON). """
self.status = None
""" active | on-hold | completed | entered-in-error | stopped | draft.
Type `str`. """
self.substitution = None
""" Any restrictions on medication substitution.
Type `MedicationOrderSubstitution` (represented as `dict` in JSON). """
super(MedicationOrder, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(MedicationOrder, self).elementProperties()
js.extend([
("dateEnded", "dateEnded", fhirdate.FHIRDate, False, None, False),
("dateWritten", "dateWritten", fhirdate.FHIRDate, False, None, False),
("dispenseRequest", "dispenseRequest", MedicationOrderDispenseRequest, False, None, False),
("dosageInstruction", "dosageInstruction", MedicationOrderDosageInstruction, True, None, False),
("encounter", "encounter", fhirreference.FHIRReference, False, None, False),
("identifier", "identifier", identifier.Identifier, True, None, False),
("medicationCodeableConcept", "medicationCodeableConcept", codeableconcept.CodeableConcept, False, "medication", True),
("medicationReference", "medicationReference", fhirreference.FHIRReference, False, "medication", True),
("note", "note", str, False, None, False),
("patient", "patient", fhirreference.FHIRReference, False, None, False),
("prescriber", "prescriber", fhirreference.FHIRReference, False, None, False),
("priorPrescription", "priorPrescription", fhirreference.FHIRReference, False, None, False),
("reasonCodeableConcept", "reasonCodeableConcept", codeableconcept.CodeableConcept, False, "reason", False),
("reasonEnded", "reasonEnded", codeableconcept.CodeableConcept, False, None, False),
("reasonReference", "reasonReference", fhirreference.FHIRReference, False, "reason", False),
("status", "status", str, False, None, False),
("substitution", "substitution", MedicationOrderSubstitution, False, None, False),
])
return js
from . import backboneelement
class MedicationOrderDispenseRequest(backboneelement.BackboneElement):
""" Medication supply authorization.
Indicates the specific details for the dispense or medication supply part
of a medication order (also known as a Medication Prescription). Note that
this information is NOT always sent with the order. There may be in some
settings (e.g. hospitals) institutional or system support for completing
the dispense details in the pharmacy department.
"""
resource_name = "MedicationOrderDispenseRequest"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.expectedSupplyDuration = None
""" Number of days supply per dispense.
Type `Quantity` referencing `Duration` (represented as `dict` in JSON). """
self.medicationCodeableConcept = None
""" Product to be supplied.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.medicationReference = None
""" Product to be supplied.
Type `FHIRReference` referencing `Medication` (represented as `dict` in JSON). """
self.numberOfRepeatsAllowed = None
""" Number of refills authorized.
Type `int`. """
self.quantity = None
""" Amount of medication to supply per dispense.
Type `Quantity` referencing `SimpleQuantity` (represented as `dict` in JSON). """
self.validityPeriod = None
""" Time period supply is authorized for.
Type `Period` (represented as `dict` in JSON). """
super(MedicationOrderDispenseRequest, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(MedicationOrderDispenseRequest, self).elementProperties()
js.extend([
("expectedSupplyDuration", "expectedSupplyDuration", quantity.Quantity, False, None, False),
("medicationCodeableConcept", "medicationCodeableConcept", codeableconcept.CodeableConcept, False, "medication", False),
("medicationReference", "medicationReference", fhirreference.FHIRReference, False, "medication", False),
("numberOfRepeatsAllowed", "numberOfRepeatsAllowed", int, False, None, False),
("quantity", "quantity", quantity.Quantity, False, None, False),
("validityPeriod", "validityPeriod", period.Period, False, None, False),
])
return js
class MedicationOrderDosageInstruction(backboneelement.BackboneElement):
""" How medication should be taken.
Indicates how the medication is to be used by the patient.
"""
resource_name = "MedicationOrderDosageInstruction"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.additionalInstructions = None
""" Supplemental instructions - e.g. "with meals".
Type `CodeableConcept` (represented as `dict` in JSON). """
self.asNeededBoolean = None
""" Take "as needed" (for x).
Type `bool`. """
self.asNeededCodeableConcept = None
""" Take "as needed" (for x).
Type `CodeableConcept` (represented as `dict` in JSON). """
self.doseQuantity = None
""" Amount of medication per dose.
Type `Quantity` referencing `SimpleQuantity` (represented as `dict` in JSON). """
self.doseRange = None
""" Amount of medication per dose.
Type `Range` (represented as `dict` in JSON). """
self.maxDosePerPeriod = None
""" Upper limit on medication per unit of time.
Type `Ratio` (represented as `dict` in JSON). """
self.method = None
""" Technique for administering medication.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.rateRange = None
""" Amount of medication per unit of time.
Type `Range` (represented as `dict` in JSON). """
self.rateRatio = None
""" Amount of medication per unit of time.
Type `Ratio` (represented as `dict` in JSON). """
self.route = None
""" How drug should enter body.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.siteCodeableConcept = None
""" Body site to administer to.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.siteReference = None
""" Body site to administer to.
Type `FHIRReference` referencing `BodySite` (represented as `dict` in JSON). """
self.text = None
""" Dosage instructions expressed as text.
Type `str`. """
self.timing = None
""" When medication should be administered.
Type `Timing` (represented as `dict` in JSON). """
super(MedicationOrderDosageInstruction, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(MedicationOrderDosageInstruction, self).elementProperties()
js.extend([
("additionalInstructions", "additionalInstructions", codeableconcept.CodeableConcept, False, None, False),
("asNeededBoolean", "asNeededBoolean", bool, False, "asNeeded", False),
("asNeededCodeableConcept", "asNeededCodeableConcept", codeableconcept.CodeableConcept, False, "asNeeded", False),
("doseQuantity", "doseQuantity", quantity.Quantity, False, "dose", False),
("doseRange", "doseRange", range.Range, False, "dose", False),
("maxDosePerPeriod", "maxDosePerPeriod", ratio.Ratio, False, None, False),
("method", "method", codeableconcept.CodeableConcept, False, None, False),
("rateRange", "rateRange", range.Range, False, "rate", False),
("rateRatio", "rateRatio", ratio.Ratio, False, "rate", False),
("route", "route", codeableconcept.CodeableConcept, False, None, False),
("siteCodeableConcept", "siteCodeableConcept", codeableconcept.CodeableConcept, False, "site", False),
("siteReference", "siteReference", fhirreference.FHIRReference, False, "site", False),
("text", "text", str, False, None, False),
("timing", "timing", timing.Timing, False, None, False),
])
return js
class MedicationOrderSubstitution(backboneelement.BackboneElement):
""" Any restrictions on medication substitution.
Indicates whether or not substitution can or should be part of the
dispense. In some cases substitution must happen, in other cases
substitution must not happen, and in others it does not matter. This block
explains the prescriber's intent. If nothing is specified substitution may
be done.
"""
resource_name = "MedicationOrderSubstitution"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.reason = None
""" Why should (not) substitution be made.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.type = None
""" generic | formulary +.
Type `CodeableConcept` (represented as `dict` in JSON). """
super(MedicationOrderSubstitution, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(MedicationOrderSubstitution, self).elementProperties()
js.extend([
("reason", "reason", codeableconcept.CodeableConcept, False, None, False),
("type", "type", codeableconcept.CodeableConcept, False, None, True),
])
return js
from . import codeableconcept
from . import fhirdate
from . import fhirreference
from . import identifier
from . import period
from . import quantity
from . import range
from . import ratio
from . import timing
| bsd-3-clause | 4ece6e8df29f17b3d34318b90c7653fa | 43.489297 | 132 | 0.635001 | 4.387214 | false | false | false | false |
django/django-localflavor | tests/test_ch.py | 4 | 2928 | from django.test import SimpleTestCase
from django.utils.translation import gettext as _
from django.utils.translation import override
from localflavor.ch.forms import CHIdentityCardNumberField, CHSocialSecurityNumberField, CHStateSelect, CHZipCodeField
class CHLocalFlavorTests(SimpleTestCase):
def test_CHStateSelect(self):
with override('en'):
f = CHStateSelect()
out = '''<select name="state">
<option value="AG" selected="selected">Aargau</option>
<option value="AI">Appenzell Innerrhoden</option>
<option value="AR">Appenzell Ausserrhoden</option>
<option value="BS">Basel-Stadt</option>
<option value="BL">Basel-Land</option>
<option value="BE">Berne</option>
<option value="FR">Fribourg</option>
<option value="GE">Geneva</option>
<option value="GL">Glarus</option>
<option value="GR">Graubuenden</option>
<option value="JU">Jura</option>
<option value="LU">Lucerne</option>
<option value="NE">Neuchatel</option>
<option value="NW">Nidwalden</option>
<option value="OW">Obwalden</option>
<option value="SH">Schaffhausen</option>
<option value="SZ">Schwyz</option>
<option value="SO">Solothurn</option>
<option value="SG">St. Gallen</option>
<option value="TG">Thurgau</option>
<option value="TI">Ticino</option>
<option value="UR">Uri</option>
<option value="VS">Valais</option>
<option value="VD">Vaud</option>
<option value="ZG">Zug</option>
<option value="ZH">Zurich</option>
</select>'''
self.assertHTMLEqual(f.render('state', 'AG'), out)
def test_CHZipCodeField(self):
error_format = [_('Enter a valid postal code in the range and format 1XXX - 9XXX.')]
valid = {
'1234': '1234',
'9999': '9999',
}
invalid = {
'0000': error_format,
'800x': error_format,
'80 00': error_format,
'99990': error_format,
}
self.assertFieldOutput(CHZipCodeField, valid, invalid)
def test_CHIdentityCardNumberField(self):
error_format = [_('Enter a valid Swiss identity or passport card number in X1234567<0 or 1234567890 format.')]
valid = {
'C1234567<0': 'C1234567<0',
'2123456700': '2123456700',
}
invalid = {
'C1234567<1': error_format,
'2123456701': error_format,
}
self.assertFieldOutput(CHIdentityCardNumberField, valid, invalid)
def test_CHSocialSecurityNumberField(self):
error_format = [_('Enter a valid Swiss Social Security number in 756.XXXX.XXXX.XX format.')]
valid = {
'756.1234.5678.97': '756.1234.5678.97',
'756.9217.0769.85': '756.9217.0769.85',
}
invalid = {
'756.1234.5678.96': error_format,
'757.1234.5678.97': error_format,
'756.1234.5678': error_format,
}
self.assertFieldOutput(CHSocialSecurityNumberField, valid, invalid)
| bsd-3-clause | 5ee47419a7b8e7e414f400e4c3273abc | 35.6 | 118 | 0.641735 | 3.388889 | false | true | false | false |
all-of-us/raw-data-repository | rdr_service/alembic/versions/fbd2991cb316_add_created_from_metric_id_to_results_.py | 1 | 1841 | """add created_from_metric_id to results viewed and report states tables
Revision ID: fbd2991cb316
Revises: 2ea1a8e0acb0, 2d70a82af09b, 42428d88dd1d
Create Date: 2022-10-06 14:50:49.973035
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'fbd2991cb316'
down_revision = ('2ea1a8e0acb0', '2d70a82af09b', '42428d88dd1d')
branch_labels = None
depends_on = None
def upgrade(engine_name):
globals()["upgrade_%s" % engine_name]()
def downgrade(engine_name):
globals()["downgrade_%s" % engine_name]()
def upgrade_rdr():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('genomic_member_report_state', sa.Column('created_from_metric_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'genomic_member_report_state', 'user_event_metrics', ['created_from_metric_id'], ['id'])
op.add_column('genomic_result_viewed', sa.Column('created_from_metric_id', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'genomic_result_viewed', 'user_event_metrics', ['created_from_metric_id'], ['id'])
# ### end Alembic commands ###
def downgrade_rdr():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'genomic_result_viewed', type_='foreignkey')
op.drop_column('genomic_result_viewed', 'created_from_metric_id')
op.drop_constraint(None, 'genomic_member_report_state', type_='foreignkey')
op.drop_column('genomic_member_report_state', 'created_from_metric_id')
# ### end Alembic commands ###
def upgrade_metrics():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
def downgrade_metrics():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
| bsd-3-clause | 5f7497a69409f0ec0ce92cfb95c890b8 | 33.092593 | 120 | 0.687127 | 3.17962 | false | false | false | false |
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_4_0_0/models/medicinalproductauthorization.py | 1 | 10780 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/MedicinalProductAuthorization) on 2019-05-07.
# 2019, SMART Health IT.
from . import domainresource
class MedicinalProductAuthorization(domainresource.DomainResource):
""" The regulatory authorization of a medicinal product.
"""
resource_type = "MedicinalProductAuthorization"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.country = None
""" The country in which the marketing authorization has been granted.
List of `CodeableConcept` items (represented as `dict` in JSON). """
self.dataExclusivityPeriod = None
""" A period of time after authorization before generic product
applicatiosn can be submitted.
Type `Period` (represented as `dict` in JSON). """
self.dateOfFirstAuthorization = None
""" The date when the first authorization was granted by a Medicines
Regulatory Agency.
Type `FHIRDate` (represented as `str` in JSON). """
self.holder = None
""" Marketing Authorization Holder.
Type `FHIRReference` (represented as `dict` in JSON). """
self.identifier = None
""" Business identifier for the marketing authorization, as assigned by
a regulator.
List of `Identifier` items (represented as `dict` in JSON). """
self.internationalBirthDate = None
""" Date of first marketing authorization for a company's new medicinal
product in any country in the World.
Type `FHIRDate` (represented as `str` in JSON). """
self.jurisdiction = None
""" Jurisdiction within a country.
List of `CodeableConcept` items (represented as `dict` in JSON). """
self.jurisdictionalAuthorization = None
""" Authorization in areas within a country.
List of `MedicinalProductAuthorizationJurisdictionalAuthorization` items (represented as `dict` in JSON). """
self.legalBasis = None
""" The legal framework against which this authorization is granted.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.procedure = None
""" The regulatory procedure for granting or amending a marketing
authorization.
Type `MedicinalProductAuthorizationProcedure` (represented as `dict` in JSON). """
self.regulator = None
""" Medicines Regulatory Agency.
Type `FHIRReference` (represented as `dict` in JSON). """
self.restoreDate = None
""" The date when a suspended the marketing or the marketing
authorization of the product is anticipated to be restored.
Type `FHIRDate` (represented as `str` in JSON). """
self.status = None
""" The status of the marketing authorization.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.statusDate = None
""" The date at which the given status has become applicable.
Type `FHIRDate` (represented as `str` in JSON). """
self.subject = None
""" The medicinal product that is being authorized.
Type `FHIRReference` (represented as `dict` in JSON). """
self.validityPeriod = None
""" The beginning of the time period in which the marketing
authorization is in the specific status shall be specified A
complete date consisting of day, month and year shall be specified
using the ISO 8601 date format.
Type `Period` (represented as `dict` in JSON). """
super(MedicinalProductAuthorization, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(MedicinalProductAuthorization, self).elementProperties()
js.extend([
("country", "country", codeableconcept.CodeableConcept, True, None, False),
("dataExclusivityPeriod", "dataExclusivityPeriod", period.Period, False, None, False),
("dateOfFirstAuthorization", "dateOfFirstAuthorization", fhirdate.FHIRDate, False, None, False),
("holder", "holder", fhirreference.FHIRReference, False, None, False),
("identifier", "identifier", identifier.Identifier, True, None, False),
("internationalBirthDate", "internationalBirthDate", fhirdate.FHIRDate, False, None, False),
("jurisdiction", "jurisdiction", codeableconcept.CodeableConcept, True, None, False),
("jurisdictionalAuthorization", "jurisdictionalAuthorization", MedicinalProductAuthorizationJurisdictionalAuthorization, True, None, False),
("legalBasis", "legalBasis", codeableconcept.CodeableConcept, False, None, False),
("procedure", "procedure", MedicinalProductAuthorizationProcedure, False, None, False),
("regulator", "regulator", fhirreference.FHIRReference, False, None, False),
("restoreDate", "restoreDate", fhirdate.FHIRDate, False, None, False),
("status", "status", codeableconcept.CodeableConcept, False, None, False),
("statusDate", "statusDate", fhirdate.FHIRDate, False, None, False),
("subject", "subject", fhirreference.FHIRReference, False, None, False),
("validityPeriod", "validityPeriod", period.Period, False, None, False),
])
return js
from . import backboneelement
class MedicinalProductAuthorizationJurisdictionalAuthorization(backboneelement.BackboneElement):
""" Authorization in areas within a country.
"""
resource_type = "MedicinalProductAuthorizationJurisdictionalAuthorization"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.country = None
""" Country of authorization.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.identifier = None
""" The assigned number for the marketing authorization.
List of `Identifier` items (represented as `dict` in JSON). """
self.jurisdiction = None
""" Jurisdiction within a country.
List of `CodeableConcept` items (represented as `dict` in JSON). """
self.legalStatusOfSupply = None
""" The legal status of supply in a jurisdiction or region.
Type `CodeableConcept` (represented as `dict` in JSON). """
self.validityPeriod = None
""" The start and expected end date of the authorization.
Type `Period` (represented as `dict` in JSON). """
super(MedicinalProductAuthorizationJurisdictionalAuthorization, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(MedicinalProductAuthorizationJurisdictionalAuthorization, self).elementProperties()
js.extend([
("country", "country", codeableconcept.CodeableConcept, False, None, False),
("identifier", "identifier", identifier.Identifier, True, None, False),
("jurisdiction", "jurisdiction", codeableconcept.CodeableConcept, True, None, False),
("legalStatusOfSupply", "legalStatusOfSupply", codeableconcept.CodeableConcept, False, None, False),
("validityPeriod", "validityPeriod", period.Period, False, None, False),
])
return js
class MedicinalProductAuthorizationProcedure(backboneelement.BackboneElement):
""" The regulatory procedure for granting or amending a marketing authorization.
"""
resource_type = "MedicinalProductAuthorizationProcedure"
def __init__(self, jsondict=None, strict=True):
""" Initialize all valid properties.
:raises: FHIRValidationError on validation errors, unless strict is False
:param dict jsondict: A JSON dictionary to use for initialization
:param bool strict: If True (the default), invalid variables will raise a TypeError
"""
self.application = None
""" Applcations submitted to obtain a marketing authorization.
List of `MedicinalProductAuthorizationProcedure` items (represented as `dict` in JSON). """
self.dateDateTime = None
""" Date of procedure.
Type `FHIRDate` (represented as `str` in JSON). """
self.datePeriod = None
""" Date of procedure.
Type `Period` (represented as `dict` in JSON). """
self.identifier = None
""" Identifier for this procedure.
Type `Identifier` (represented as `dict` in JSON). """
self.type = None
""" Type of procedure.
Type `CodeableConcept` (represented as `dict` in JSON). """
super(MedicinalProductAuthorizationProcedure, self).__init__(jsondict=jsondict, strict=strict)
def elementProperties(self):
js = super(MedicinalProductAuthorizationProcedure, self).elementProperties()
js.extend([
("application", "application", MedicinalProductAuthorizationProcedure, True, None, False),
("dateDateTime", "dateDateTime", fhirdate.FHIRDate, False, "date", False),
("datePeriod", "datePeriod", period.Period, False, "date", False),
("identifier", "identifier", identifier.Identifier, False, None, False),
("type", "type", codeableconcept.CodeableConcept, False, None, True),
])
return js
import sys
try:
from . import codeableconcept
except ImportError:
codeableconcept = sys.modules[__package__ + '.codeableconcept']
try:
from . import fhirdate
except ImportError:
fhirdate = sys.modules[__package__ + '.fhirdate']
try:
from . import fhirreference
except ImportError:
fhirreference = sys.modules[__package__ + '.fhirreference']
try:
from . import identifier
except ImportError:
identifier = sys.modules[__package__ + '.identifier']
try:
from . import period
except ImportError:
period = sys.modules[__package__ + '.period']
| bsd-3-clause | f34d012e6b8268de50e5d5e44a25b8ee | 43.916667 | 152 | 0.648609 | 4.45823 | false | false | false | false |
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_4_0_0/models/testreport_tests.py | 1 | 6848 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b on 2019-05-07.
# 2019, SMART Health IT.
import os
import io
import unittest
import json
from . import testreport
from .fhirdate import FHIRDate
class TestReportTests(unittest.TestCase):
def instantiate_from(self, filename):
datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or ''
with io.open(os.path.join(datadir, filename), 'r', encoding='utf-8') as handle:
js = json.load(handle)
self.assertEqual("TestReport", js["resourceType"])
return testreport.TestReport(js)
def testTestReport1(self):
inst = self.instantiate_from("testreport-example.json")
self.assertIsNotNone(inst, "Must have instantiated a TestReport instance")
self.implTestReport1(inst)
js = inst.as_json()
self.assertEqual("TestReport", js["resourceType"])
inst2 = testreport.TestReport(js)
self.implTestReport1(inst2)
def implTestReport1(self, inst):
self.assertEqual(inst.id, "testreport-example")
self.assertEqual(inst.identifier.system, "urn:ietf:rfc:3986")
self.assertEqual(inst.identifier.value, "urn:oid:1.3.6.1.4.1.21367.2005.3.7.9878")
self.assertEqual(inst.issued.date, FHIRDate("2016-10-07T08:25:34-05:00").date)
self.assertEqual(inst.issued.as_json(), "2016-10-07T08:25:34-05:00")
self.assertEqual(inst.meta.tag[0].code, "HTEST")
self.assertEqual(inst.meta.tag[0].display, "test health data")
self.assertEqual(inst.meta.tag[0].system, "http://terminology.hl7.org/CodeSystem/v3-ActReason")
self.assertEqual(inst.name, "TestReport Example for TestScript Example")
self.assertEqual(inst.participant[0].display, "Crucible")
self.assertEqual(inst.participant[0].type, "test-engine")
self.assertEqual(inst.participant[0].uri, "http://projectcrucible.org")
self.assertEqual(inst.participant[1].display, "HealthIntersections STU3")
self.assertEqual(inst.participant[1].type, "server")
self.assertEqual(inst.participant[1].uri, "http://fhir3.healthintersections.com.au/open")
self.assertEqual(inst.result, "pass")
self.assertEqual(inst.score, 100.0)
self.assertEqual(inst.setup.action[0].operation.detail, "http://projectcrucible.org/permalink/1")
self.assertEqual(inst.setup.action[0].operation.message, "DELETE Patient")
self.assertEqual(inst.setup.action[0].operation.result, "pass")
self.assertEqual(inst.setup.action[1].assert_fhir.detail, "http://projectcrucible.org/permalink/1")
self.assertEqual(inst.setup.action[1].assert_fhir.message, "HTTP 204")
self.assertEqual(inst.setup.action[1].assert_fhir.result, "pass")
self.assertEqual(inst.setup.action[2].operation.detail, "http://projectcrucible.org/permalink/1")
self.assertEqual(inst.setup.action[2].operation.message, "POST Patient/fixture-patient-create")
self.assertEqual(inst.setup.action[2].operation.result, "pass")
self.assertEqual(inst.setup.action[3].assert_fhir.detail, "http://projectcrucible.org/permalink/1")
self.assertEqual(inst.setup.action[3].assert_fhir.message, "HTTP 201")
self.assertEqual(inst.setup.action[3].assert_fhir.result, "pass")
self.assertEqual(inst.status, "completed")
self.assertEqual(inst.teardown.action[0].operation.detail, "http://projectcrucible.org/permalink/3")
self.assertEqual(inst.teardown.action[0].operation.message, "DELETE Patient/fixture-patient-create.")
self.assertEqual(inst.teardown.action[0].operation.result, "pass")
self.assertEqual(inst.test[0].action[0].operation.detail, "http://projectcrucible.org/permalink/2")
self.assertEqual(inst.test[0].action[0].operation.message, "GET Patient/fixture-patient-create")
self.assertEqual(inst.test[0].action[0].operation.result, "pass")
self.assertEqual(inst.test[0].action[1].assert_fhir.detail, "http://projectcrucible.org/permalink/2")
self.assertEqual(inst.test[0].action[1].assert_fhir.message, "HTTP 200")
self.assertEqual(inst.test[0].action[1].assert_fhir.result, "pass")
self.assertEqual(inst.test[0].action[2].assert_fhir.detail, "http://projectcrucible.org/permalink/2")
self.assertEqual(inst.test[0].action[2].assert_fhir.message, "Last-Modified Present")
self.assertEqual(inst.test[0].action[2].assert_fhir.result, "pass")
self.assertEqual(inst.test[0].action[3].assert_fhir.detail, "http://projectcrucible.org/permalink/2")
self.assertEqual(inst.test[0].action[3].assert_fhir.message, "Response is Patient")
self.assertEqual(inst.test[0].action[3].assert_fhir.result, "pass")
self.assertEqual(inst.test[0].action[4].assert_fhir.detail, "http://projectcrucible.org/permalink/2")
self.assertEqual(inst.test[0].action[4].assert_fhir.message, "Response validates")
self.assertEqual(inst.test[0].action[4].assert_fhir.result, "pass")
self.assertEqual(inst.test[0].action[5].assert_fhir.detail, "http://projectcrucible.org/permalink/2")
self.assertEqual(inst.test[0].action[5].assert_fhir.message, "Patient.name.family 'Chalmers'")
self.assertEqual(inst.test[0].action[5].assert_fhir.result, "pass")
self.assertEqual(inst.test[0].action[6].assert_fhir.detail, "http://projectcrucible.org/permalink/2")
self.assertEqual(inst.test[0].action[6].assert_fhir.message, "Patient.name.given 'Peter'")
self.assertEqual(inst.test[0].action[6].assert_fhir.result, "pass")
self.assertEqual(inst.test[0].action[7].assert_fhir.detail, "http://projectcrucible.org/permalink/2")
self.assertEqual(inst.test[0].action[7].assert_fhir.message, "Patient.name.family 'Chalmers'")
self.assertEqual(inst.test[0].action[7].assert_fhir.result, "pass")
self.assertEqual(inst.test[0].action[8].assert_fhir.detail, "http://projectcrucible.org/permalink/2")
self.assertEqual(inst.test[0].action[8].assert_fhir.message, "Patient.name.family 'Chalmers'")
self.assertEqual(inst.test[0].action[8].assert_fhir.result, "pass")
self.assertEqual(inst.test[0].action[9].assert_fhir.detail, "http://projectcrucible.org/permalink/2")
self.assertEqual(inst.test[0].action[9].assert_fhir.message, "Patient expected values.")
self.assertEqual(inst.test[0].action[9].assert_fhir.result, "pass")
self.assertEqual(inst.test[0].description, "Read a Patient and validate response.")
self.assertEqual(inst.test[0].id, "01-ReadPatient")
self.assertEqual(inst.test[0].name, "Read Patient")
self.assertEqual(inst.tester, "HL7 Execution Engine")
self.assertEqual(inst.text.status, "generated")
| bsd-3-clause | 88f7fdbf34c092a646d7bb9619e353b5 | 65.485437 | 109 | 0.696554 | 3.213515 | false | true | false | false |
all-of-us/raw-data-repository | rdr_service/singletons.py | 1 | 1699 | import threading
from datetime import timedelta
from rdr_service.clock import CLOCK
singletons_lock = threading.RLock()
singletons_map = {}
CODE_CACHE_INDEX = 0
HPO_CACHE_INDEX = 1
SITE_CACHE_INDEX = 2
SQL_DATABASE_INDEX = 3
ORGANIZATION_CACHE_INDEX = 4
GENERIC_SQL_DATABASE_INDEX = 5
MAIN_CONFIG_INDEX = 6
DB_CONFIG_INDEX = 7
BACKUP_SQL_DATABASE_INDEX = 8
ALEMBIC_SQL_DATABASE_INDEX = 9
READ_UNCOMMITTED_DATABASE_INDEX = 10
BASICS_PROFILE_UPDATE_CODES_CACHE_INDEX = 11
def reset_for_tests():
with singletons_lock:
singletons_map.clear()
def _get(cache_index):
existing_pair = singletons_map.get(cache_index)
if existing_pair and (existing_pair[1] is None or existing_pair[1] >= CLOCK.now()):
return existing_pair[0]
return None
def get(cache_index, constructor, cache_ttl_seconds=None, **kwargs):
"""Get a cache with a specified index from the list above. If not initialized, use
constructor to initialize it; if cache_ttl_seconds is set, reload it after that period."""
# First try without a lock
result = _get(cache_index)
if result:
return result
# Then grab the lock and try again
with singletons_lock:
result = _get(cache_index)
if result:
return result
else:
new_instance = constructor(**kwargs)
expiration_time = None
if cache_ttl_seconds is not None:
expiration_time = CLOCK.now() + timedelta(seconds=cache_ttl_seconds)
singletons_map[cache_index] = (new_instance, expiration_time)
return new_instance
def invalidate(cache_index):
with singletons_lock:
singletons_map[cache_index] = None
| bsd-3-clause | 343a0b2f145b521c93146ecfc803d6fa | 27.79661 | 92 | 0.675103 | 3.614894 | false | false | false | false |
all-of-us/raw-data-repository | rdr_service/resource/tasks.py | 1 | 8792 | #
# This file is subject to the terms and conditions defined in the
# file 'LICENSE', which is part of this source code package.
#
# import json
import logging
from datetime import datetime
import rdr_service.config as config
from rdr_service.resource.constants import SKIP_TEST_PIDS_FOR_PDR
from rdr_service.dao.bigquery_sync_dao import BigQuerySyncDao
from rdr_service.dao.bq_participant_summary_dao import BQParticipantSummaryGenerator, rebuild_bq_participant
from rdr_service.dao.bq_pdr_participant_summary_dao import BQPDRParticipantSummaryGenerator
from rdr_service.dao.bq_questionnaire_dao import BQPDRQuestionnaireResponseGenerator
from rdr_service.model.bq_questionnaires import PDR_MODULE_LIST
from rdr_service.cloud_utils.gcp_cloud_tasks import GCPCloudTask
from rdr_service.resource import generators
from rdr_service.resource.generators.participant import rebuild_participant_summary_resource
from rdr_service.resource.generators.consent_metrics import ConsentErrorReportGenerator
from rdr_service.services.system_utils import list_chunks
def batch_rebuild_participants_task(payload, project_id=None):
"""
Loop through all participants in batch and generate the BQ participant summary data and
store it in the biguqery_sync table.
Warning: this will force a rebuild and eventually a re-sync for every participant record.
:param payload: Dict object with list of participants to work on.
:param project_id: String identifier for the GAE project
"""
res_gen = generators.ParticipantSummaryGenerator()
ps_bqgen = BQParticipantSummaryGenerator()
pdr_bqgen = BQPDRParticipantSummaryGenerator()
mod_bqgen = BQPDRQuestionnaireResponseGenerator()
count = 0
batch = payload['batch']
# Boolean/flag fields indicating which elements to rebuild. Default to True if not specified in payload
# This is intended to improve performance/efficiency for targeted PDR rebuilds which may only affect (for example)
# the participant summary data but do not require all the module response data to be rebuilt (or vice versa)
# TODO: Pass a list of specific modules to build (empty if skipping all modules) instead of a flag
build_participant_summary = payload.get('build_participant_summary', True)
build_modules = payload.get('build_modules', True)
logging.info(f'Start time: {datetime.utcnow()}, batch size: {len(batch)}')
# logging.info(json.dumps(batch, indent=2))
if not build_participant_summary:
logging.info('Skipping rebuild of participant_summary data')
if not build_modules:
logging.info('Skipping rebuild of participant module responses')
for item in batch:
p_id = item['pid']
patch_data = item.get('patch', None)
count += 1
if int(p_id) in SKIP_TEST_PIDS_FOR_PDR:
logging.warning(f'Skipping rebuild of test pid {p_id} data')
continue
if build_participant_summary:
rebuild_participant_summary_resource(p_id, res_gen=res_gen, patch_data=patch_data)
ps_bqr = rebuild_bq_participant(p_id, ps_bqgen=ps_bqgen, pdr_bqgen=pdr_bqgen, patch_data=patch_data,
project_id=project_id)
# Test to see if participant record has been filtered or we are just patching.
if not ps_bqr or patch_data:
continue
if build_modules:
# Generate participant questionnaire module response data
for module in PDR_MODULE_LIST:
mod = module()
table, mod_bqrs = mod_bqgen.make_bqrecord(p_id, mod.get_schema().get_module_name())
if not table:
continue
# TODO: Switch this to ResourceDataDAO, but make sure we don't break anything when the switch is made.
w_dao = BigQuerySyncDao()
with w_dao.session() as w_session:
for mod_bqr in mod_bqrs:
mod_bqgen.save_bqrecord(mod_bqr.questionnaire_response_id, mod_bqr, bqtable=table,
w_dao=w_dao, w_session=w_session, project_id=project_id)
logging.info(f'End time: {datetime.utcnow()}, rebuilt BigQuery data for {count} participants.')
def batch_rebuild_retention_metrics_task(payload):
"""
Rebuild all or a batch of Retention Eligible Metrics
:param payload: Dict object with list of participants to work on.
"""
res_gen = generators.RetentionEligibleMetricGenerator()
batch = payload.get('batch')
count = 0
for pid in batch:
res = res_gen.make_resource(pid)
res.save()
count += 1
logging.info(f'End time: {datetime.utcnow()}, rebuilt {count} Retention Metrics records.')
def check_consent_errors_task(payload):
"""
Review previously unreported consent errors and generate an automated error report
"""
origin = payload.get('participant_origin', 'vibrent')
# DA-2611: Generate a list of all previously unreported errors, based on ConsentErrorReport table content
gen = ConsentErrorReportGenerator()
id_list = gen.get_unreported_error_ids()
if id_list and len(id_list):
gen.create_error_reports(participant_origin=origin, id_list=id_list)
else:
logging.info(f'No unreported consent errors found for participants with origin {origin}')
def batch_rebuild_consent_metrics_task(payload):
"""
Rebuild a batch of consent metrics records based on ids from the consent_file table
:param payload: Dict object with list of ids to work on.
"""
res_gen = generators.ConsentMetricGenerator()
batch = payload.get('batch')
# Retrieve the consent_file table records by id
results = res_gen.get_consent_validation_records(id_list=batch)
for row in results:
res = res_gen.make_resource(row.id, consent_validation_rec=row)
res.save()
logging.info(f'End time: {datetime.utcnow()}, rebuilt {len(results)} ConsentMetric records.')
def batch_rebuild_user_event_metrics_task(payload):
"""
Rebuild a batch of user event metrics records based on ids
:param payload: Dict object with list of ids to work on.
"""
res_gen = generators.GenomicUserEventMetricsSchemaGenerator()
batch = payload.get('batch')
count = 0
for id_ in batch:
res = res_gen.make_resource(id_)
res.save()
count += 1
logging.info(f'End time: {datetime.utcnow()}, rebuilt {count} User Event Metrics records.')
# TODO: Look at consolidating dispatch_participant_rebuild_tasks() from offline/bigquery_sync.py and this into a
# generic dispatch routine also available for other resource type rebuilds. May need to have
# endpoint-specific logic and/or some fancy code to dynamically populate the task.execute() args (or to allow for
# local rebuilds vs. cloud tasks)
def dispatch_rebuild_consent_metrics_tasks(id_list, in_seconds=30, quiet=True, batch_size=150,
project_id=None, build_locally=False):
"""
Helper method to handle queuing batch rebuild requests for rebuilding consent metrics resource data
"""
if project_id is None:
project_id = config.GAE_PROJECT
if not all(isinstance(id, int) for id in id_list):
raise (ValueError, "Invalid id list; must be a list that contains only integer consent_file ids")
if build_locally or project_id == 'localhost':
batch_rebuild_consent_metrics_task({'batch': id_list})
else:
completed_batches = 0
task = GCPCloudTask()
for batch in list_chunks(id_list, batch_size):
payload = {'batch': batch}
task.execute('batch_rebuild_consent_metrics_task', payload=payload, in_seconds=in_seconds,
queue='resource-rebuild', quiet=quiet, project_id=project_id)
completed_batches += 1
logging.info(f'Dispatched {completed_batches} batch_rebuild_consent_metrics tasks of max size {batch_size}')
def dispatch_check_consent_errors_task(in_seconds=30, quiet=True, origin=None,
project_id=config.GAE_PROJECT, build_locally=False):
"""
Create / queue a task that will check for unreported validation errors and generate error reports
"""
payload = {'participant_origin': origin}
if build_locally or project_id == 'localhost':
check_consent_errors_task(payload)
else:
task = GCPCloudTask()
task.execute('check_consent_errors_task', payload=payload, in_seconds=in_seconds,
queue='resource-tasks', quiet=quiet, project_id=project_id)
logging.info(f'Dispatched consent error reporting task to run in {in_seconds} seconds')
| bsd-3-clause | 6b81e00bcb7fb69a2b433823dad5b9b7 | 44.319588 | 118 | 0.685282 | 3.90582 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.