repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
getsentry/raven-python
raven/contrib/tornado/__init__.py
SentryMixin.get_sentry_data_from_request
def get_sentry_data_from_request(self): """ Extracts the data required for 'sentry.interfaces.Http' from the current request being handled by the request handler :param return: A dictionary. """ return { 'request': { 'url': self.request.full_url(), 'method': self.request.method, 'data': self.request.body, 'query_string': self.request.query, 'cookies': self.request.headers.get('Cookie', None), 'headers': dict(self.request.headers), } }
python
def get_sentry_data_from_request(self): """ Extracts the data required for 'sentry.interfaces.Http' from the current request being handled by the request handler :param return: A dictionary. """ return { 'request': { 'url': self.request.full_url(), 'method': self.request.method, 'data': self.request.body, 'query_string': self.request.query, 'cookies': self.request.headers.get('Cookie', None), 'headers': dict(self.request.headers), } }
[ "def", "get_sentry_data_from_request", "(", "self", ")", ":", "return", "{", "'request'", ":", "{", "'url'", ":", "self", ".", "request", ".", "full_url", "(", ")", ",", "'method'", ":", "self", ".", "request", ".", "method", ",", "'data'", ":", "self", ...
Extracts the data required for 'sentry.interfaces.Http' from the current request being handled by the request handler :param return: A dictionary.
[ "Extracts", "the", "data", "required", "for", "sentry", ".", "interfaces", ".", "Http", "from", "the", "current", "request", "being", "handled", "by", "the", "request", "handler" ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/tornado/__init__.py#L147-L163
train
227,600
getsentry/raven-python
raven/base.py
Client.get_public_dsn
def get_public_dsn(self, scheme=None): """ Returns a public DSN which is consumable by raven-js >>> # Return scheme-less DSN >>> print client.get_public_dsn() >>> # Specify a scheme to use (http or https) >>> print client.get_public_dsn('https') """ if self.is_enabled(): url = self.remote.get_public_dsn() if scheme: return '%s:%s' % (scheme, url) return url
python
def get_public_dsn(self, scheme=None): """ Returns a public DSN which is consumable by raven-js >>> # Return scheme-less DSN >>> print client.get_public_dsn() >>> # Specify a scheme to use (http or https) >>> print client.get_public_dsn('https') """ if self.is_enabled(): url = self.remote.get_public_dsn() if scheme: return '%s:%s' % (scheme, url) return url
[ "def", "get_public_dsn", "(", "self", ",", "scheme", "=", "None", ")", ":", "if", "self", ".", "is_enabled", "(", ")", ":", "url", "=", "self", ".", "remote", ".", "get_public_dsn", "(", ")", "if", "scheme", ":", "return", "'%s:%s'", "%", "(", "schem...
Returns a public DSN which is consumable by raven-js >>> # Return scheme-less DSN >>> print client.get_public_dsn() >>> # Specify a scheme to use (http or https) >>> print client.get_public_dsn('https')
[ "Returns", "a", "public", "DSN", "which", "is", "consumable", "by", "raven", "-", "js" ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L330-L345
train
227,601
getsentry/raven-python
raven/base.py
Client.capture
def capture(self, event_type, data=None, date=None, time_spent=None, extra=None, stack=None, tags=None, sample_rate=None, **kwargs): """ Captures and processes an event and pipes it off to SentryClient.send. To use structured data (interfaces) with capture: >>> capture('raven.events.Message', message='foo', data={ >>> 'request': { >>> 'url': '...', >>> 'data': {}, >>> 'query_string': '...', >>> 'method': 'POST', >>> }, >>> 'logger': 'logger.name', >>> }, extra={ >>> 'key': 'value', >>> }) The finalized ``data`` structure contains the following (some optional) builtin values: >>> { >>> # the culprit and version information >>> 'culprit': 'full.module.name', # or /arbitrary/path >>> >>> # all detectable installed modules >>> 'modules': { >>> 'full.module.name': 'version string', >>> }, >>> >>> # arbitrary data provided by user >>> 'extra': { >>> 'key': 'value', >>> } >>> } :param event_type: the module path to the Event class. Builtins can use shorthand class notation and exclude the full module path. :param data: the data base, useful for specifying structured data interfaces. Any key which contains a '.' will be assumed to be a data interface. :param date: the datetime of this event :param time_spent: a integer value representing the duration of the event (in milliseconds) :param extra: a dictionary of additional standard metadata :param stack: a stacktrace for the event :param tags: dict of extra tags :param sample_rate: a float in the range [0, 1] to sample this message :return: a 32-length string identifying this event """ if not self.is_enabled(): return exc_info = kwargs.get('exc_info') if exc_info is not None: if self.skip_error_for_logging(exc_info): return elif not self.should_capture(exc_info): self.logger.info( 'Not capturing exception due to filters: %s', exc_info[0], exc_info=sys.exc_info()) return self.record_exception_seen(exc_info) data = self.build_msg( event_type, data, date, time_spent, extra, stack, tags=tags, **kwargs) # should this event be sampled? if sample_rate is None: sample_rate = self.sample_rate if self._random.random() < sample_rate: self.send(**data) self._local_state.last_event_id = data['event_id'] return data['event_id']
python
def capture(self, event_type, data=None, date=None, time_spent=None, extra=None, stack=None, tags=None, sample_rate=None, **kwargs): """ Captures and processes an event and pipes it off to SentryClient.send. To use structured data (interfaces) with capture: >>> capture('raven.events.Message', message='foo', data={ >>> 'request': { >>> 'url': '...', >>> 'data': {}, >>> 'query_string': '...', >>> 'method': 'POST', >>> }, >>> 'logger': 'logger.name', >>> }, extra={ >>> 'key': 'value', >>> }) The finalized ``data`` structure contains the following (some optional) builtin values: >>> { >>> # the culprit and version information >>> 'culprit': 'full.module.name', # or /arbitrary/path >>> >>> # all detectable installed modules >>> 'modules': { >>> 'full.module.name': 'version string', >>> }, >>> >>> # arbitrary data provided by user >>> 'extra': { >>> 'key': 'value', >>> } >>> } :param event_type: the module path to the Event class. Builtins can use shorthand class notation and exclude the full module path. :param data: the data base, useful for specifying structured data interfaces. Any key which contains a '.' will be assumed to be a data interface. :param date: the datetime of this event :param time_spent: a integer value representing the duration of the event (in milliseconds) :param extra: a dictionary of additional standard metadata :param stack: a stacktrace for the event :param tags: dict of extra tags :param sample_rate: a float in the range [0, 1] to sample this message :return: a 32-length string identifying this event """ if not self.is_enabled(): return exc_info = kwargs.get('exc_info') if exc_info is not None: if self.skip_error_for_logging(exc_info): return elif not self.should_capture(exc_info): self.logger.info( 'Not capturing exception due to filters: %s', exc_info[0], exc_info=sys.exc_info()) return self.record_exception_seen(exc_info) data = self.build_msg( event_type, data, date, time_spent, extra, stack, tags=tags, **kwargs) # should this event be sampled? if sample_rate is None: sample_rate = self.sample_rate if self._random.random() < sample_rate: self.send(**data) self._local_state.last_event_id = data['event_id'] return data['event_id']
[ "def", "capture", "(", "self", ",", "event_type", ",", "data", "=", "None", ",", "date", "=", "None", ",", "time_spent", "=", "None", ",", "extra", "=", "None", ",", "stack", "=", "None", ",", "tags", "=", "None", ",", "sample_rate", "=", "None", "...
Captures and processes an event and pipes it off to SentryClient.send. To use structured data (interfaces) with capture: >>> capture('raven.events.Message', message='foo', data={ >>> 'request': { >>> 'url': '...', >>> 'data': {}, >>> 'query_string': '...', >>> 'method': 'POST', >>> }, >>> 'logger': 'logger.name', >>> }, extra={ >>> 'key': 'value', >>> }) The finalized ``data`` structure contains the following (some optional) builtin values: >>> { >>> # the culprit and version information >>> 'culprit': 'full.module.name', # or /arbitrary/path >>> >>> # all detectable installed modules >>> 'modules': { >>> 'full.module.name': 'version string', >>> }, >>> >>> # arbitrary data provided by user >>> 'extra': { >>> 'key': 'value', >>> } >>> } :param event_type: the module path to the Event class. Builtins can use shorthand class notation and exclude the full module path. :param data: the data base, useful for specifying structured data interfaces. Any key which contains a '.' will be assumed to be a data interface. :param date: the datetime of this event :param time_spent: a integer value representing the duration of the event (in milliseconds) :param extra: a dictionary of additional standard metadata :param stack: a stacktrace for the event :param tags: dict of extra tags :param sample_rate: a float in the range [0, 1] to sample this message :return: a 32-length string identifying this event
[ "Captures", "and", "processes", "an", "event", "and", "pipes", "it", "off", "to", "SentryClient", ".", "send", "." ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L577-L657
train
227,602
getsentry/raven-python
raven/base.py
Client._log_failed_submission
def _log_failed_submission(self, data): """ Log a reasonable representation of an event that should have been sent to Sentry """ message = data.pop('message', '<no message value>') output = [message] if 'exception' in data and 'stacktrace' in data['exception']['values'][-1]: # try to reconstruct a reasonable version of the exception for frame in data['exception']['values'][-1]['stacktrace'].get('frames', []): output.append(' File "%(fn)s", line %(lineno)s, in %(func)s' % { 'fn': frame.get('filename', 'unknown_filename'), 'lineno': frame.get('lineno', -1), 'func': frame.get('function', 'unknown_function'), }) self.uncaught_logger.error(output)
python
def _log_failed_submission(self, data): """ Log a reasonable representation of an event that should have been sent to Sentry """ message = data.pop('message', '<no message value>') output = [message] if 'exception' in data and 'stacktrace' in data['exception']['values'][-1]: # try to reconstruct a reasonable version of the exception for frame in data['exception']['values'][-1]['stacktrace'].get('frames', []): output.append(' File "%(fn)s", line %(lineno)s, in %(func)s' % { 'fn': frame.get('filename', 'unknown_filename'), 'lineno': frame.get('lineno', -1), 'func': frame.get('function', 'unknown_function'), }) self.uncaught_logger.error(output)
[ "def", "_log_failed_submission", "(", "self", ",", "data", ")", ":", "message", "=", "data", ".", "pop", "(", "'message'", ",", "'<no message value>'", ")", "output", "=", "[", "message", "]", "if", "'exception'", "in", "data", "and", "'stacktrace'", "in", ...
Log a reasonable representation of an event that should have been sent to Sentry
[ "Log", "a", "reasonable", "representation", "of", "an", "event", "that", "should", "have", "been", "sent", "to", "Sentry" ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L696-L712
train
227,603
getsentry/raven-python
raven/base.py
Client.send_encoded
def send_encoded(self, message, auth_header=None, **kwargs): """ Given an already serialized message, signs the message and passes the payload off to ``send_remote``. """ client_string = 'raven-python/%s' % (raven.VERSION,) if not auth_header: timestamp = time.time() auth_header = get_auth_header( protocol=self.protocol_version, timestamp=timestamp, client=client_string, api_key=self.remote.public_key, api_secret=self.remote.secret_key, ) headers = { 'User-Agent': client_string, 'X-Sentry-Auth': auth_header, 'Content-Encoding': self.get_content_encoding(), 'Content-Type': 'application/octet-stream', } return self.send_remote( url=self.remote.store_endpoint, data=message, headers=headers, **kwargs )
python
def send_encoded(self, message, auth_header=None, **kwargs): """ Given an already serialized message, signs the message and passes the payload off to ``send_remote``. """ client_string = 'raven-python/%s' % (raven.VERSION,) if not auth_header: timestamp = time.time() auth_header = get_auth_header( protocol=self.protocol_version, timestamp=timestamp, client=client_string, api_key=self.remote.public_key, api_secret=self.remote.secret_key, ) headers = { 'User-Agent': client_string, 'X-Sentry-Auth': auth_header, 'Content-Encoding': self.get_content_encoding(), 'Content-Type': 'application/octet-stream', } return self.send_remote( url=self.remote.store_endpoint, data=message, headers=headers, **kwargs )
[ "def", "send_encoded", "(", "self", ",", "message", ",", "auth_header", "=", "None", ",", "*", "*", "kwargs", ")", ":", "client_string", "=", "'raven-python/%s'", "%", "(", "raven", ".", "VERSION", ",", ")", "if", "not", "auth_header", ":", "timestamp", ...
Given an already serialized message, signs the message and passes the payload off to ``send_remote``.
[ "Given", "an", "already", "serialized", "message", "signs", "the", "message", "and", "passes", "the", "payload", "off", "to", "send_remote", "." ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L752-L781
train
227,604
getsentry/raven-python
raven/base.py
Client.captureQuery
def captureQuery(self, query, params=(), engine=None, **kwargs): """ Creates an event for a SQL query. >>> client.captureQuery('SELECT * FROM foo') """ return self.capture( 'raven.events.Query', query=query, params=params, engine=engine, **kwargs)
python
def captureQuery(self, query, params=(), engine=None, **kwargs): """ Creates an event for a SQL query. >>> client.captureQuery('SELECT * FROM foo') """ return self.capture( 'raven.events.Query', query=query, params=params, engine=engine, **kwargs)
[ "def", "captureQuery", "(", "self", ",", "query", ",", "params", "=", "(", ")", ",", "engine", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "capture", "(", "'raven.events.Query'", ",", "query", "=", "query", ",", "params", "...
Creates an event for a SQL query. >>> client.captureQuery('SELECT * FROM foo')
[ "Creates", "an", "event", "for", "a", "SQL", "query", "." ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L892-L900
train
227,605
getsentry/raven-python
raven/base.py
Client.captureBreadcrumb
def captureBreadcrumb(self, *args, **kwargs): """ Records a breadcrumb with the current context. They will be sent with the next event. """ # Note: framework integration should not call this method but # instead use the raven.breadcrumbs.record_breadcrumb function # which will record to the correct client automatically. self.context.breadcrumbs.record(*args, **kwargs)
python
def captureBreadcrumb(self, *args, **kwargs): """ Records a breadcrumb with the current context. They will be sent with the next event. """ # Note: framework integration should not call this method but # instead use the raven.breadcrumbs.record_breadcrumb function # which will record to the correct client automatically. self.context.breadcrumbs.record(*args, **kwargs)
[ "def", "captureBreadcrumb", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Note: framework integration should not call this method but", "# instead use the raven.breadcrumbs.record_breadcrumb function", "# which will record to the correct client automatically.", ...
Records a breadcrumb with the current context. They will be sent with the next event.
[ "Records", "a", "breadcrumb", "with", "the", "current", "context", ".", "They", "will", "be", "sent", "with", "the", "next", "event", "." ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/base.py#L908-L916
train
227,606
getsentry/raven-python
raven/transport/registry.py
TransportRegistry.register_scheme
def register_scheme(self, scheme, cls): """ It is possible to inject new schemes at runtime """ if scheme in self._schemes: raise DuplicateScheme() urlparse.register_scheme(scheme) # TODO (vng): verify the interface of the new class self._schemes[scheme] = cls
python
def register_scheme(self, scheme, cls): """ It is possible to inject new schemes at runtime """ if scheme in self._schemes: raise DuplicateScheme() urlparse.register_scheme(scheme) # TODO (vng): verify the interface of the new class self._schemes[scheme] = cls
[ "def", "register_scheme", "(", "self", ",", "scheme", ",", "cls", ")", ":", "if", "scheme", "in", "self", ".", "_schemes", ":", "raise", "DuplicateScheme", "(", ")", "urlparse", ".", "register_scheme", "(", "scheme", ")", "# TODO (vng): verify the interface of t...
It is possible to inject new schemes at runtime
[ "It", "is", "possible", "to", "inject", "new", "schemes", "at", "runtime" ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/transport/registry.py#L40-L49
train
227,607
getsentry/raven-python
raven/contrib/flask.py
Sentry.get_http_info
def get_http_info(self, request): """ Determine how to retrieve actual data by using request.mimetype. """ if self.is_json_type(request.mimetype): retriever = self.get_json_data else: retriever = self.get_form_data return self.get_http_info_with_retriever(request, retriever)
python
def get_http_info(self, request): """ Determine how to retrieve actual data by using request.mimetype. """ if self.is_json_type(request.mimetype): retriever = self.get_json_data else: retriever = self.get_form_data return self.get_http_info_with_retriever(request, retriever)
[ "def", "get_http_info", "(", "self", ",", "request", ")", ":", "if", "self", ".", "is_json_type", "(", "request", ".", "mimetype", ")", ":", "retriever", "=", "self", ".", "get_json_data", "else", ":", "retriever", "=", "self", ".", "get_form_data", "retur...
Determine how to retrieve actual data by using request.mimetype.
[ "Determine", "how", "to", "retrieve", "actual", "data", "by", "using", "request", ".", "mimetype", "." ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/flask.py#L194-L202
train
227,608
getsentry/raven-python
raven/conf/__init__.py
setup_logging
def setup_logging(handler, exclude=EXCLUDE_LOGGER_DEFAULTS): """ Configures logging to pipe to Sentry. - ``exclude`` is a list of loggers that shouldn't go to Sentry. For a typical Python install: >>> from raven.handlers.logging import SentryHandler >>> client = Sentry(...) >>> setup_logging(SentryHandler(client)) Within Django: >>> from raven.contrib.django.handlers import SentryHandler >>> setup_logging(SentryHandler()) Returns a boolean based on if logging was configured or not. """ logger = logging.getLogger() if handler.__class__ in map(type, logger.handlers): return False logger.addHandler(handler) # Add StreamHandler to sentry's default so you can catch missed exceptions for logger_name in exclude: logger = logging.getLogger(logger_name) logger.propagate = False logger.addHandler(logging.StreamHandler()) return True
python
def setup_logging(handler, exclude=EXCLUDE_LOGGER_DEFAULTS): """ Configures logging to pipe to Sentry. - ``exclude`` is a list of loggers that shouldn't go to Sentry. For a typical Python install: >>> from raven.handlers.logging import SentryHandler >>> client = Sentry(...) >>> setup_logging(SentryHandler(client)) Within Django: >>> from raven.contrib.django.handlers import SentryHandler >>> setup_logging(SentryHandler()) Returns a boolean based on if logging was configured or not. """ logger = logging.getLogger() if handler.__class__ in map(type, logger.handlers): return False logger.addHandler(handler) # Add StreamHandler to sentry's default so you can catch missed exceptions for logger_name in exclude: logger = logging.getLogger(logger_name) logger.propagate = False logger.addHandler(logging.StreamHandler()) return True
[ "def", "setup_logging", "(", "handler", ",", "exclude", "=", "EXCLUDE_LOGGER_DEFAULTS", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", ")", "if", "handler", ".", "__class__", "in", "map", "(", "type", ",", "logger", ".", "handlers", ")", ":", ...
Configures logging to pipe to Sentry. - ``exclude`` is a list of loggers that shouldn't go to Sentry. For a typical Python install: >>> from raven.handlers.logging import SentryHandler >>> client = Sentry(...) >>> setup_logging(SentryHandler(client)) Within Django: >>> from raven.contrib.django.handlers import SentryHandler >>> setup_logging(SentryHandler()) Returns a boolean based on if logging was configured or not.
[ "Configures", "logging", "to", "pipe", "to", "Sentry", "." ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/conf/__init__.py#L26-L57
train
227,609
getsentry/raven-python
raven/utils/stacks.py
to_dict
def to_dict(dictish): """ Given something that closely resembles a dictionary, we attempt to coerce it into a propery dictionary. """ if hasattr(dictish, 'iterkeys'): m = dictish.iterkeys elif hasattr(dictish, 'keys'): m = dictish.keys else: raise ValueError(dictish) return dict((k, dictish[k]) for k in m())
python
def to_dict(dictish): """ Given something that closely resembles a dictionary, we attempt to coerce it into a propery dictionary. """ if hasattr(dictish, 'iterkeys'): m = dictish.iterkeys elif hasattr(dictish, 'keys'): m = dictish.keys else: raise ValueError(dictish) return dict((k, dictish[k]) for k in m())
[ "def", "to_dict", "(", "dictish", ")", ":", "if", "hasattr", "(", "dictish", ",", "'iterkeys'", ")", ":", "m", "=", "dictish", ".", "iterkeys", "elif", "hasattr", "(", "dictish", ",", "'keys'", ")", ":", "m", "=", "dictish", ".", "keys", "else", ":",...
Given something that closely resembles a dictionary, we attempt to coerce it into a propery dictionary.
[ "Given", "something", "that", "closely", "resembles", "a", "dictionary", "we", "attempt", "to", "coerce", "it", "into", "a", "propery", "dictionary", "." ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/stacks.py#L96-L108
train
227,610
getsentry/raven-python
raven/utils/stacks.py
slim_frame_data
def slim_frame_data(frames, frame_allowance=25): """ Removes various excess metadata from middle frames which go beyond ``frame_allowance``. Returns ``frames``. """ frames_len = 0 app_frames = [] system_frames = [] for frame in frames: frames_len += 1 if frame.get('in_app'): app_frames.append(frame) else: system_frames.append(frame) if frames_len <= frame_allowance: return frames remaining = frames_len - frame_allowance app_count = len(app_frames) system_allowance = max(frame_allowance - app_count, 0) if system_allowance: half_max = int(system_allowance / 2) # prioritize trimming system frames for frame in system_frames[half_max:-half_max]: frame.pop('vars', None) frame.pop('pre_context', None) frame.pop('post_context', None) remaining -= 1 else: for frame in system_frames: frame.pop('vars', None) frame.pop('pre_context', None) frame.pop('post_context', None) remaining -= 1 if remaining: app_allowance = app_count - remaining half_max = int(app_allowance / 2) for frame in app_frames[half_max:-half_max]: frame.pop('vars', None) frame.pop('pre_context', None) frame.pop('post_context', None) return frames
python
def slim_frame_data(frames, frame_allowance=25): """ Removes various excess metadata from middle frames which go beyond ``frame_allowance``. Returns ``frames``. """ frames_len = 0 app_frames = [] system_frames = [] for frame in frames: frames_len += 1 if frame.get('in_app'): app_frames.append(frame) else: system_frames.append(frame) if frames_len <= frame_allowance: return frames remaining = frames_len - frame_allowance app_count = len(app_frames) system_allowance = max(frame_allowance - app_count, 0) if system_allowance: half_max = int(system_allowance / 2) # prioritize trimming system frames for frame in system_frames[half_max:-half_max]: frame.pop('vars', None) frame.pop('pre_context', None) frame.pop('post_context', None) remaining -= 1 else: for frame in system_frames: frame.pop('vars', None) frame.pop('pre_context', None) frame.pop('post_context', None) remaining -= 1 if remaining: app_allowance = app_count - remaining half_max = int(app_allowance / 2) for frame in app_frames[half_max:-half_max]: frame.pop('vars', None) frame.pop('pre_context', None) frame.pop('post_context', None) return frames
[ "def", "slim_frame_data", "(", "frames", ",", "frame_allowance", "=", "25", ")", ":", "frames_len", "=", "0", "app_frames", "=", "[", "]", "system_frames", "=", "[", "]", "for", "frame", "in", "frames", ":", "frames_len", "+=", "1", "if", "frame", ".", ...
Removes various excess metadata from middle frames which go beyond ``frame_allowance``. Returns ``frames``.
[ "Removes", "various", "excess", "metadata", "from", "middle", "frames", "which", "go", "beyond", "frame_allowance", "." ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/stacks.py#L167-L215
train
227,611
getsentry/raven-python
raven/contrib/webpy/utils.py
get_data_from_request
def get_data_from_request(): """Returns request data extracted from web.ctx.""" return { 'request': { 'url': '%s://%s%s' % (web.ctx['protocol'], web.ctx['host'], web.ctx['path']), 'query_string': web.ctx.query, 'method': web.ctx.method, 'data': web.data(), 'headers': dict(get_headers(web.ctx.environ)), 'env': dict(get_environ(web.ctx.environ)), } }
python
def get_data_from_request(): """Returns request data extracted from web.ctx.""" return { 'request': { 'url': '%s://%s%s' % (web.ctx['protocol'], web.ctx['host'], web.ctx['path']), 'query_string': web.ctx.query, 'method': web.ctx.method, 'data': web.data(), 'headers': dict(get_headers(web.ctx.environ)), 'env': dict(get_environ(web.ctx.environ)), } }
[ "def", "get_data_from_request", "(", ")", ":", "return", "{", "'request'", ":", "{", "'url'", ":", "'%s://%s%s'", "%", "(", "web", ".", "ctx", "[", "'protocol'", "]", ",", "web", ".", "ctx", "[", "'host'", "]", ",", "web", ".", "ctx", "[", "'path'", ...
Returns request data extracted from web.ctx.
[ "Returns", "request", "data", "extracted", "from", "web", ".", "ctx", "." ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/webpy/utils.py#L15-L26
train
227,612
getsentry/raven-python
raven/contrib/django/resolver.py
get_regex
def get_regex(resolver_or_pattern): """Utility method for django's deprecated resolver.regex""" try: regex = resolver_or_pattern.regex except AttributeError: regex = resolver_or_pattern.pattern.regex return regex
python
def get_regex(resolver_or_pattern): """Utility method for django's deprecated resolver.regex""" try: regex = resolver_or_pattern.regex except AttributeError: regex = resolver_or_pattern.pattern.regex return regex
[ "def", "get_regex", "(", "resolver_or_pattern", ")", ":", "try", ":", "regex", "=", "resolver_or_pattern", ".", "regex", "except", "AttributeError", ":", "regex", "=", "resolver_or_pattern", ".", "pattern", ".", "regex", "return", "regex" ]
Utility method for django's deprecated resolver.regex
[ "Utility", "method", "for", "django", "s", "deprecated", "resolver", ".", "regex" ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/resolver.py#L11-L17
train
227,613
getsentry/raven-python
raven/utils/basic.py
once
def once(func): """Runs a thing once and once only.""" lock = threading.Lock() def new_func(*args, **kwargs): if new_func.called: return with lock: if new_func.called: return rv = func(*args, **kwargs) new_func.called = True return rv new_func = update_wrapper(new_func, func) new_func.called = False return new_func
python
def once(func): """Runs a thing once and once only.""" lock = threading.Lock() def new_func(*args, **kwargs): if new_func.called: return with lock: if new_func.called: return rv = func(*args, **kwargs) new_func.called = True return rv new_func = update_wrapper(new_func, func) new_func.called = False return new_func
[ "def", "once", "(", "func", ")", ":", "lock", "=", "threading", ".", "Lock", "(", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "new_func", ".", "called", ":", "return", "with", "lock", ":", "if", "new_func", ...
Runs a thing once and once only.
[ "Runs", "a", "thing", "once", "and", "once", "only", "." ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/utils/basic.py#L75-L91
train
227,614
getsentry/raven-python
raven/contrib/django/utils.py
get_host
def get_host(request): """ A reimplementation of Django's get_host, without the SuspiciousOperation check. """ # We try three options, in order of decreasing preference. if settings.USE_X_FORWARDED_HOST and ( 'HTTP_X_FORWARDED_HOST' in request.META): host = request.META['HTTP_X_FORWARDED_HOST'] elif 'HTTP_HOST' in request.META: host = request.META['HTTP_HOST'] else: # Reconstruct the host using the algorithm from PEP 333. host = request.META['SERVER_NAME'] server_port = str(request.META['SERVER_PORT']) if server_port != (request.is_secure() and '443' or '80'): host = '%s:%s' % (host, server_port) return host
python
def get_host(request): """ A reimplementation of Django's get_host, without the SuspiciousOperation check. """ # We try three options, in order of decreasing preference. if settings.USE_X_FORWARDED_HOST and ( 'HTTP_X_FORWARDED_HOST' in request.META): host = request.META['HTTP_X_FORWARDED_HOST'] elif 'HTTP_HOST' in request.META: host = request.META['HTTP_HOST'] else: # Reconstruct the host using the algorithm from PEP 333. host = request.META['SERVER_NAME'] server_port = str(request.META['SERVER_PORT']) if server_port != (request.is_secure() and '443' or '80'): host = '%s:%s' % (host, server_port) return host
[ "def", "get_host", "(", "request", ")", ":", "# We try three options, in order of decreasing preference.", "if", "settings", ".", "USE_X_FORWARDED_HOST", "and", "(", "'HTTP_X_FORWARDED_HOST'", "in", "request", ".", "META", ")", ":", "host", "=", "request", ".", "META"...
A reimplementation of Django's get_host, without the SuspiciousOperation check.
[ "A", "reimplementation", "of", "Django", "s", "get_host", "without", "the", "SuspiciousOperation", "check", "." ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/utils.py#L84-L101
train
227,615
getsentry/raven-python
raven/contrib/django/models.py
install_middleware
def install_middleware(middleware_name, lookup_names=None): """ Install specified middleware """ if lookup_names is None: lookup_names = (middleware_name,) # default settings.MIDDLEWARE is None middleware_attr = 'MIDDLEWARE' if getattr(settings, 'MIDDLEWARE', None) is not None \ else 'MIDDLEWARE_CLASSES' # make sure to get an empty tuple when attr is None middleware = getattr(settings, middleware_attr, ()) or () if set(lookup_names).isdisjoint(set(middleware)): setattr(settings, middleware_attr, type(middleware)((middleware_name,)) + middleware)
python
def install_middleware(middleware_name, lookup_names=None): """ Install specified middleware """ if lookup_names is None: lookup_names = (middleware_name,) # default settings.MIDDLEWARE is None middleware_attr = 'MIDDLEWARE' if getattr(settings, 'MIDDLEWARE', None) is not None \ else 'MIDDLEWARE_CLASSES' # make sure to get an empty tuple when attr is None middleware = getattr(settings, middleware_attr, ()) or () if set(lookup_names).isdisjoint(set(middleware)): setattr(settings, middleware_attr, type(middleware)((middleware_name,)) + middleware)
[ "def", "install_middleware", "(", "middleware_name", ",", "lookup_names", "=", "None", ")", ":", "if", "lookup_names", "is", "None", ":", "lookup_names", "=", "(", "middleware_name", ",", ")", "# default settings.MIDDLEWARE is None", "middleware_attr", "=", "'MIDDLEWA...
Install specified middleware
[ "Install", "specified", "middleware" ]
d891c20f0f930153f508e9d698d9de42e910face
https://github.com/getsentry/raven-python/blob/d891c20f0f930153f508e9d698d9de42e910face/raven/contrib/django/models.py#L222-L238
train
227,616
sebp/scikit-survival
sksurv/meta/base.py
_fit_and_score
def _fit_and_score(est, x, y, scorer, train_index, test_index, parameters, fit_params, predict_params): """Train survival model on given data and return its score on test data""" X_train, y_train = _safe_split(est, x, y, train_index) train_params = fit_params.copy() # Training est.set_params(**parameters) est.fit(X_train, y_train, **train_params) # Testing test_predict_params = predict_params.copy() X_test, y_test = _safe_split(est, x, y, test_index, train_index) score = scorer(est, X_test, y_test, **test_predict_params) if not isinstance(score, numbers.Number): raise ValueError("scoring must return a number, got %s (%s) instead." % (str(score), type(score))) return score
python
def _fit_and_score(est, x, y, scorer, train_index, test_index, parameters, fit_params, predict_params): """Train survival model on given data and return its score on test data""" X_train, y_train = _safe_split(est, x, y, train_index) train_params = fit_params.copy() # Training est.set_params(**parameters) est.fit(X_train, y_train, **train_params) # Testing test_predict_params = predict_params.copy() X_test, y_test = _safe_split(est, x, y, test_index, train_index) score = scorer(est, X_test, y_test, **test_predict_params) if not isinstance(score, numbers.Number): raise ValueError("scoring must return a number, got %s (%s) instead." % (str(score), type(score))) return score
[ "def", "_fit_and_score", "(", "est", ",", "x", ",", "y", ",", "scorer", ",", "train_index", ",", "test_index", ",", "parameters", ",", "fit_params", ",", "predict_params", ")", ":", "X_train", ",", "y_train", "=", "_safe_split", "(", "est", ",", "x", ","...
Train survival model on given data and return its score on test data
[ "Train", "survival", "model", "on", "given", "data", "and", "return", "its", "score", "on", "test", "data" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/base.py#L17-L35
train
227,617
sebp/scikit-survival
sksurv/linear_model/coxnet.py
CoxnetSurvivalAnalysis._interpolate_coefficients
def _interpolate_coefficients(self, alpha): """Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to neighbors of alpha in the list of alphas constructed during training.""" exact = False coef_idx = None for i, val in enumerate(self.alphas_): if val > alpha: coef_idx = i elif alpha - val < numpy.finfo(numpy.float).eps: coef_idx = i exact = True break if coef_idx is None: coef = self.coef_[:, 0] elif exact or coef_idx == len(self.alphas_) - 1: coef = self.coef_[:, coef_idx] else: # interpolate between coefficients a1 = self.alphas_[coef_idx + 1] a2 = self.alphas_[coef_idx] frac = (alpha - a1) / (a2 - a1) coef = frac * self.coef_[:, coef_idx] + (1.0 - frac) * self.coef_[:, coef_idx + 1] return coef
python
def _interpolate_coefficients(self, alpha): """Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to neighbors of alpha in the list of alphas constructed during training.""" exact = False coef_idx = None for i, val in enumerate(self.alphas_): if val > alpha: coef_idx = i elif alpha - val < numpy.finfo(numpy.float).eps: coef_idx = i exact = True break if coef_idx is None: coef = self.coef_[:, 0] elif exact or coef_idx == len(self.alphas_) - 1: coef = self.coef_[:, coef_idx] else: # interpolate between coefficients a1 = self.alphas_[coef_idx + 1] a2 = self.alphas_[coef_idx] frac = (alpha - a1) / (a2 - a1) coef = frac * self.coef_[:, coef_idx] + (1.0 - frac) * self.coef_[:, coef_idx + 1] return coef
[ "def", "_interpolate_coefficients", "(", "self", ",", "alpha", ")", ":", "exact", "=", "False", "coef_idx", "=", "None", "for", "i", ",", "val", "in", "enumerate", "(", "self", ".", "alphas_", ")", ":", "if", "val", ">", "alpha", ":", "coef_idx", "=", ...
Interpolate coefficients by calculating the weighted average of coefficient vectors corresponding to neighbors of alpha in the list of alphas constructed during training.
[ "Interpolate", "coefficients", "by", "calculating", "the", "weighted", "average", "of", "coefficient", "vectors", "corresponding", "to", "neighbors", "of", "alpha", "in", "the", "list", "of", "alphas", "constructed", "during", "training", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxnet.py#L239-L263
train
227,618
sebp/scikit-survival
sksurv/linear_model/coxnet.py
CoxnetSurvivalAnalysis.predict
def predict(self, X, alpha=None): """The linear predictor of the model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Test data of which to calculate log-likelihood from alpha : float, optional Constant that multiplies the penalty terms. If the same alpha was used during training, exact coefficients are used, otherwise coefficients are interpolated from the closest alpha values that were used during training. If set to ``None``, the last alpha in the solution path is used. Returns ------- T : array, shape = (n_samples,) The predicted decision function """ X = check_array(X) coef = self._get_coef(alpha) return numpy.dot(X, coef)
python
def predict(self, X, alpha=None): """The linear predictor of the model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Test data of which to calculate log-likelihood from alpha : float, optional Constant that multiplies the penalty terms. If the same alpha was used during training, exact coefficients are used, otherwise coefficients are interpolated from the closest alpha values that were used during training. If set to ``None``, the last alpha in the solution path is used. Returns ------- T : array, shape = (n_samples,) The predicted decision function """ X = check_array(X) coef = self._get_coef(alpha) return numpy.dot(X, coef)
[ "def", "predict", "(", "self", ",", "X", ",", "alpha", "=", "None", ")", ":", "X", "=", "check_array", "(", "X", ")", "coef", "=", "self", ".", "_get_coef", "(", "alpha", ")", "return", "numpy", ".", "dot", "(", "X", ",", "coef", ")" ]
The linear predictor of the model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Test data of which to calculate log-likelihood from alpha : float, optional Constant that multiplies the penalty terms. If the same alpha was used during training, exact coefficients are used, otherwise coefficients are interpolated from the closest alpha values that were used during training. If set to ``None``, the last alpha in the solution path is used. Returns ------- T : array, shape = (n_samples,) The predicted decision function
[ "The", "linear", "predictor", "of", "the", "model", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxnet.py#L265-L285
train
227,619
sebp/scikit-survival
sksurv/meta/ensemble_selection.py
BaseEnsembleSelection._create_base_ensemble
def _create_base_ensemble(self, out, n_estimators, n_folds): """For each base estimator collect models trained on each fold""" ensemble_scores = numpy.empty((n_estimators, n_folds)) base_ensemble = numpy.empty_like(ensemble_scores, dtype=numpy.object) for model, fold, score, est in out: ensemble_scores[model, fold] = score base_ensemble[model, fold] = est return ensemble_scores, base_ensemble
python
def _create_base_ensemble(self, out, n_estimators, n_folds): """For each base estimator collect models trained on each fold""" ensemble_scores = numpy.empty((n_estimators, n_folds)) base_ensemble = numpy.empty_like(ensemble_scores, dtype=numpy.object) for model, fold, score, est in out: ensemble_scores[model, fold] = score base_ensemble[model, fold] = est return ensemble_scores, base_ensemble
[ "def", "_create_base_ensemble", "(", "self", ",", "out", ",", "n_estimators", ",", "n_folds", ")", ":", "ensemble_scores", "=", "numpy", ".", "empty", "(", "(", "n_estimators", ",", "n_folds", ")", ")", "base_ensemble", "=", "numpy", ".", "empty_like", "(", ...
For each base estimator collect models trained on each fold
[ "For", "each", "base", "estimator", "collect", "models", "trained", "on", "each", "fold" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L152-L160
train
227,620
sebp/scikit-survival
sksurv/meta/ensemble_selection.py
BaseEnsembleSelection._create_cv_ensemble
def _create_cv_ensemble(self, base_ensemble, idx_models_included, model_names=None): """For each selected base estimator, average models trained on each fold""" fitted_models = numpy.empty(len(idx_models_included), dtype=numpy.object) for i, idx in enumerate(idx_models_included): model_name = self.base_estimators[idx][0] if model_names is None else model_names[idx] avg_model = EnsembleAverage(base_ensemble[idx, :], name=model_name) fitted_models[i] = avg_model return fitted_models
python
def _create_cv_ensemble(self, base_ensemble, idx_models_included, model_names=None): """For each selected base estimator, average models trained on each fold""" fitted_models = numpy.empty(len(idx_models_included), dtype=numpy.object) for i, idx in enumerate(idx_models_included): model_name = self.base_estimators[idx][0] if model_names is None else model_names[idx] avg_model = EnsembleAverage(base_ensemble[idx, :], name=model_name) fitted_models[i] = avg_model return fitted_models
[ "def", "_create_cv_ensemble", "(", "self", ",", "base_ensemble", ",", "idx_models_included", ",", "model_names", "=", "None", ")", ":", "fitted_models", "=", "numpy", ".", "empty", "(", "len", "(", "idx_models_included", ")", ",", "dtype", "=", "numpy", ".", ...
For each selected base estimator, average models trained on each fold
[ "For", "each", "selected", "base", "estimator", "average", "models", "trained", "on", "each", "fold" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L162-L170
train
227,621
sebp/scikit-survival
sksurv/meta/ensemble_selection.py
BaseEnsembleSelection._get_base_estimators
def _get_base_estimators(self, X): """Takes special care of estimators using custom kernel function Parameters ---------- X : array, shape = (n_samples, n_features) Samples to pre-compute kernel matrix from. Returns ------- base_estimators : list Same as `self.base_estimators`, expect that estimators with custom kernel function use ``kernel='precomputed'``. kernel_cache : dict Maps estimator name to kernel matrix. Use this for cross-validation instead of `X`. """ base_estimators = [] kernel_cache = {} kernel_fns = {} for i, (name, estimator) in enumerate(self.base_estimators): if hasattr(estimator, 'kernel') and callable(estimator.kernel): if not hasattr(estimator, '_get_kernel'): raise ValueError( 'estimator %s uses a custom kernel function, but does not have a _get_kernel method' % name) kernel_mat = kernel_fns.get(estimator.kernel, None) if kernel_mat is None: kernel_mat = estimator._get_kernel(X) kernel_cache[i] = kernel_mat kernel_fns[estimator.kernel] = kernel_mat kernel_cache[i] = kernel_mat # We precompute kernel, but only for training, for testing use original custom kernel function kernel_estimator = clone(estimator) kernel_estimator.set_params(kernel='precomputed') base_estimators.append((name, kernel_estimator)) else: base_estimators.append((name, estimator)) return base_estimators, kernel_cache
python
def _get_base_estimators(self, X): """Takes special care of estimators using custom kernel function Parameters ---------- X : array, shape = (n_samples, n_features) Samples to pre-compute kernel matrix from. Returns ------- base_estimators : list Same as `self.base_estimators`, expect that estimators with custom kernel function use ``kernel='precomputed'``. kernel_cache : dict Maps estimator name to kernel matrix. Use this for cross-validation instead of `X`. """ base_estimators = [] kernel_cache = {} kernel_fns = {} for i, (name, estimator) in enumerate(self.base_estimators): if hasattr(estimator, 'kernel') and callable(estimator.kernel): if not hasattr(estimator, '_get_kernel'): raise ValueError( 'estimator %s uses a custom kernel function, but does not have a _get_kernel method' % name) kernel_mat = kernel_fns.get(estimator.kernel, None) if kernel_mat is None: kernel_mat = estimator._get_kernel(X) kernel_cache[i] = kernel_mat kernel_fns[estimator.kernel] = kernel_mat kernel_cache[i] = kernel_mat # We precompute kernel, but only for training, for testing use original custom kernel function kernel_estimator = clone(estimator) kernel_estimator.set_params(kernel='precomputed') base_estimators.append((name, kernel_estimator)) else: base_estimators.append((name, estimator)) return base_estimators, kernel_cache
[ "def", "_get_base_estimators", "(", "self", ",", "X", ")", ":", "base_estimators", "=", "[", "]", "kernel_cache", "=", "{", "}", "kernel_fns", "=", "{", "}", "for", "i", ",", "(", "name", ",", "estimator", ")", "in", "enumerate", "(", "self", ".", "b...
Takes special care of estimators using custom kernel function Parameters ---------- X : array, shape = (n_samples, n_features) Samples to pre-compute kernel matrix from. Returns ------- base_estimators : list Same as `self.base_estimators`, expect that estimators with custom kernel function use ``kernel='precomputed'``. kernel_cache : dict Maps estimator name to kernel matrix. Use this for cross-validation instead of `X`.
[ "Takes", "special", "care", "of", "estimators", "using", "custom", "kernel", "function" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L172-L214
train
227,622
sebp/scikit-survival
sksurv/meta/ensemble_selection.py
BaseEnsembleSelection._restore_base_estimators
def _restore_base_estimators(self, kernel_cache, out, X, cv): """Restore custom kernel functions of estimators for predictions""" train_folds = {fold: train_index for fold, (train_index, _) in enumerate(cv)} for idx, fold, _, est in out: if idx in kernel_cache: if not hasattr(est, 'fit_X_'): raise ValueError( 'estimator %s uses a custom kernel function, ' 'but does not have the attribute `fit_X_` after training' % self.base_estimators[idx][0]) est.set_params(kernel=self.base_estimators[idx][1].kernel) est.fit_X_ = X[train_folds[fold]] return out
python
def _restore_base_estimators(self, kernel_cache, out, X, cv): """Restore custom kernel functions of estimators for predictions""" train_folds = {fold: train_index for fold, (train_index, _) in enumerate(cv)} for idx, fold, _, est in out: if idx in kernel_cache: if not hasattr(est, 'fit_X_'): raise ValueError( 'estimator %s uses a custom kernel function, ' 'but does not have the attribute `fit_X_` after training' % self.base_estimators[idx][0]) est.set_params(kernel=self.base_estimators[idx][1].kernel) est.fit_X_ = X[train_folds[fold]] return out
[ "def", "_restore_base_estimators", "(", "self", ",", "kernel_cache", ",", "out", ",", "X", ",", "cv", ")", ":", "train_folds", "=", "{", "fold", ":", "train_index", "for", "fold", ",", "(", "train_index", ",", "_", ")", "in", "enumerate", "(", "cv", ")...
Restore custom kernel functions of estimators for predictions
[ "Restore", "custom", "kernel", "functions", "of", "estimators", "for", "predictions" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L216-L230
train
227,623
sebp/scikit-survival
sksurv/meta/ensemble_selection.py
BaseEnsembleSelection._fit_and_score_ensemble
def _fit_and_score_ensemble(self, X, y, cv, **fit_params): """Create a cross-validated model by training a model for each fold with the same model parameters""" fit_params_steps = self._split_fit_params(fit_params) folds = list(cv.split(X, y)) # Take care of custom kernel functions base_estimators, kernel_cache = self._get_base_estimators(X) out = Parallel( n_jobs=self.n_jobs, verbose=self.verbose )( delayed(_fit_and_score_fold)(clone(estimator), X if i not in kernel_cache else kernel_cache[i], y, self.scorer, train_index, test_index, fit_params_steps[name], i, fold) for i, (name, estimator) in enumerate(base_estimators) for fold, (train_index, test_index) in enumerate(folds)) if len(kernel_cache) > 0: out = self._restore_base_estimators(kernel_cache, out, X, folds) return self._create_base_ensemble(out, len(base_estimators), len(folds))
python
def _fit_and_score_ensemble(self, X, y, cv, **fit_params): """Create a cross-validated model by training a model for each fold with the same model parameters""" fit_params_steps = self._split_fit_params(fit_params) folds = list(cv.split(X, y)) # Take care of custom kernel functions base_estimators, kernel_cache = self._get_base_estimators(X) out = Parallel( n_jobs=self.n_jobs, verbose=self.verbose )( delayed(_fit_and_score_fold)(clone(estimator), X if i not in kernel_cache else kernel_cache[i], y, self.scorer, train_index, test_index, fit_params_steps[name], i, fold) for i, (name, estimator) in enumerate(base_estimators) for fold, (train_index, test_index) in enumerate(folds)) if len(kernel_cache) > 0: out = self._restore_base_estimators(kernel_cache, out, X, folds) return self._create_base_ensemble(out, len(base_estimators), len(folds))
[ "def", "_fit_and_score_ensemble", "(", "self", ",", "X", ",", "y", ",", "cv", ",", "*", "*", "fit_params", ")", ":", "fit_params_steps", "=", "self", ".", "_split_fit_params", "(", "fit_params", ")", "folds", "=", "list", "(", "cv", ".", "split", "(", ...
Create a cross-validated model by training a model for each fold with the same model parameters
[ "Create", "a", "cross", "-", "validated", "model", "by", "training", "a", "model", "for", "each", "fold", "with", "the", "same", "model", "parameters" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L232-L257
train
227,624
sebp/scikit-survival
sksurv/meta/ensemble_selection.py
BaseEnsembleSelection.fit
def fit(self, X, y=None, **fit_params): """Fit ensemble of models Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data. y : array-like, optional Target data if base estimators are supervised. Returns ------- self """ self._check_params() cv = check_cv(self.cv, X) self._fit(X, y, cv, **fit_params) return self
python
def fit(self, X, y=None, **fit_params): """Fit ensemble of models Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data. y : array-like, optional Target data if base estimators are supervised. Returns ------- self """ self._check_params() cv = check_cv(self.cv, X) self._fit(X, y, cv, **fit_params) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "*", "*", "fit_params", ")", ":", "self", ".", "_check_params", "(", ")", "cv", "=", "check_cv", "(", "self", ".", "cv", ",", "X", ")", "self", ".", "_fit", "(", "X", ",", "y", ...
Fit ensemble of models Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data. y : array-like, optional Target data if base estimators are supervised. Returns ------- self
[ "Fit", "ensemble", "of", "models" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/ensemble_selection.py#L277-L297
train
227,625
sebp/scikit-survival
sksurv/io/arffwrite.py
writearff
def writearff(data, filename, relation_name=None, index=True): """Write ARFF file Parameters ---------- data : :class:`pandas.DataFrame` DataFrame containing data filename : string or file-like object Path to ARFF file or file-like object. In the latter case, the handle is closed by calling this function. relation_name : string, optional, default: "pandas" Name of relation in ARFF file. index : boolean, optional, default: True Write row names (index) """ if isinstance(filename, str): fp = open(filename, 'w') if relation_name is None: relation_name = os.path.basename(filename) else: fp = filename if relation_name is None: relation_name = "pandas" try: data = _write_header(data, fp, relation_name, index) fp.write("\n") _write_data(data, fp) finally: fp.close()
python
def writearff(data, filename, relation_name=None, index=True): """Write ARFF file Parameters ---------- data : :class:`pandas.DataFrame` DataFrame containing data filename : string or file-like object Path to ARFF file or file-like object. In the latter case, the handle is closed by calling this function. relation_name : string, optional, default: "pandas" Name of relation in ARFF file. index : boolean, optional, default: True Write row names (index) """ if isinstance(filename, str): fp = open(filename, 'w') if relation_name is None: relation_name = os.path.basename(filename) else: fp = filename if relation_name is None: relation_name = "pandas" try: data = _write_header(data, fp, relation_name, index) fp.write("\n") _write_data(data, fp) finally: fp.close()
[ "def", "writearff", "(", "data", ",", "filename", ",", "relation_name", "=", "None", ",", "index", "=", "True", ")", ":", "if", "isinstance", "(", "filename", ",", "str", ")", ":", "fp", "=", "open", "(", "filename", ",", "'w'", ")", "if", "relation_...
Write ARFF file Parameters ---------- data : :class:`pandas.DataFrame` DataFrame containing data filename : string or file-like object Path to ARFF file or file-like object. In the latter case, the handle is closed by calling this function. relation_name : string, optional, default: "pandas" Name of relation in ARFF file. index : boolean, optional, default: True Write row names (index)
[ "Write", "ARFF", "file" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L23-L57
train
227,626
sebp/scikit-survival
sksurv/io/arffwrite.py
_write_header
def _write_header(data, fp, relation_name, index): """Write header containing attribute names and types""" fp.write("@relation {0}\n\n".format(relation_name)) if index: data = data.reset_index() attribute_names = _sanitize_column_names(data) for column, series in data.iteritems(): name = attribute_names[column] fp.write("@attribute {0}\t".format(name)) if is_categorical_dtype(series) or is_object_dtype(series): _write_attribute_categorical(series, fp) elif numpy.issubdtype(series.dtype, numpy.floating): fp.write("real") elif numpy.issubdtype(series.dtype, numpy.integer): fp.write("integer") elif numpy.issubdtype(series.dtype, numpy.datetime64): fp.write("date 'yyyy-MM-dd HH:mm:ss'") else: raise TypeError('unsupported type %s' % series.dtype) fp.write("\n") return data
python
def _write_header(data, fp, relation_name, index): """Write header containing attribute names and types""" fp.write("@relation {0}\n\n".format(relation_name)) if index: data = data.reset_index() attribute_names = _sanitize_column_names(data) for column, series in data.iteritems(): name = attribute_names[column] fp.write("@attribute {0}\t".format(name)) if is_categorical_dtype(series) or is_object_dtype(series): _write_attribute_categorical(series, fp) elif numpy.issubdtype(series.dtype, numpy.floating): fp.write("real") elif numpy.issubdtype(series.dtype, numpy.integer): fp.write("integer") elif numpy.issubdtype(series.dtype, numpy.datetime64): fp.write("date 'yyyy-MM-dd HH:mm:ss'") else: raise TypeError('unsupported type %s' % series.dtype) fp.write("\n") return data
[ "def", "_write_header", "(", "data", ",", "fp", ",", "relation_name", ",", "index", ")", ":", "fp", ".", "write", "(", "\"@relation {0}\\n\\n\"", ".", "format", "(", "relation_name", ")", ")", "if", "index", ":", "data", "=", "data", ".", "reset_index", ...
Write header containing attribute names and types
[ "Write", "header", "containing", "attribute", "names", "and", "types" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L60-L85
train
227,627
sebp/scikit-survival
sksurv/io/arffwrite.py
_sanitize_column_names
def _sanitize_column_names(data): """Replace illegal characters with underscore""" new_names = {} for name in data.columns: new_names[name] = _ILLEGAL_CHARACTER_PAT.sub("_", name) return new_names
python
def _sanitize_column_names(data): """Replace illegal characters with underscore""" new_names = {} for name in data.columns: new_names[name] = _ILLEGAL_CHARACTER_PAT.sub("_", name) return new_names
[ "def", "_sanitize_column_names", "(", "data", ")", ":", "new_names", "=", "{", "}", "for", "name", "in", "data", ".", "columns", ":", "new_names", "[", "name", "]", "=", "_ILLEGAL_CHARACTER_PAT", ".", "sub", "(", "\"_\"", ",", "name", ")", "return", "new...
Replace illegal characters with underscore
[ "Replace", "illegal", "characters", "with", "underscore" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L88-L93
train
227,628
sebp/scikit-survival
sksurv/io/arffwrite.py
_write_data
def _write_data(data, fp): """Write the data section""" fp.write("@data\n") def to_str(x): if pandas.isnull(x): return '?' else: return str(x) data = data.applymap(to_str) n_rows = data.shape[0] for i in range(n_rows): str_values = list(data.iloc[i, :].apply(_check_str_array)) line = ",".join(str_values) fp.write(line) fp.write("\n")
python
def _write_data(data, fp): """Write the data section""" fp.write("@data\n") def to_str(x): if pandas.isnull(x): return '?' else: return str(x) data = data.applymap(to_str) n_rows = data.shape[0] for i in range(n_rows): str_values = list(data.iloc[i, :].apply(_check_str_array)) line = ",".join(str_values) fp.write(line) fp.write("\n")
[ "def", "_write_data", "(", "data", ",", "fp", ")", ":", "fp", ".", "write", "(", "\"@data\\n\"", ")", "def", "to_str", "(", "x", ")", ":", "if", "pandas", ".", "isnull", "(", "x", ")", ":", "return", "'?'", "else", ":", "return", "str", "(", "x",...
Write the data section
[ "Write", "the", "data", "section" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/io/arffwrite.py#L130-L146
train
227,629
sebp/scikit-survival
sksurv/meta/stacking.py
Stacking.fit
def fit(self, X, y=None, **fit_params): """Fit base estimators. Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data. y : array-like, optional Target data if base estimators are supervised. Returns ------- self """ X = numpy.asarray(X) self._fit_estimators(X, y, **fit_params) Xt = self._predict_estimators(X) self.meta_estimator.fit(Xt, y) return self
python
def fit(self, X, y=None, **fit_params): """Fit base estimators. Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data. y : array-like, optional Target data if base estimators are supervised. Returns ------- self """ X = numpy.asarray(X) self._fit_estimators(X, y, **fit_params) Xt = self._predict_estimators(X) self.meta_estimator.fit(Xt, y) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "*", "*", "fit_params", ")", ":", "X", "=", "numpy", ".", "asarray", "(", "X", ")", "self", ".", "_fit_estimators", "(", "X", ",", "y", ",", "*", "*", "fit_params", ")", "Xt", "...
Fit base estimators. Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data. y : array-like, optional Target data if base estimators are supervised. Returns ------- self
[ "Fit", "base", "estimators", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/meta/stacking.py#L115-L135
train
227,630
sebp/scikit-survival
sksurv/column.py
standardize
def standardize(table, with_std=True): """ Perform Z-Normalization on each numeric column of the given table. Parameters ---------- table : pandas.DataFrame or numpy.ndarray Data to standardize. with_std : bool, optional, default: True If ``False`` data is only centered and not converted to unit variance. Returns ------- normalized : pandas.DataFrame Table with numeric columns normalized. Categorical columns in the input table remain unchanged. """ if isinstance(table, pandas.DataFrame): cat_columns = table.select_dtypes(include=['category']).columns else: cat_columns = [] new_frame = _apply_along_column(table, standardize_column, with_std=with_std) # work around for apply converting category dtype to object # https://github.com/pydata/pandas/issues/9573 for col in cat_columns: new_frame[col] = table[col].copy() return new_frame
python
def standardize(table, with_std=True): """ Perform Z-Normalization on each numeric column of the given table. Parameters ---------- table : pandas.DataFrame or numpy.ndarray Data to standardize. with_std : bool, optional, default: True If ``False`` data is only centered and not converted to unit variance. Returns ------- normalized : pandas.DataFrame Table with numeric columns normalized. Categorical columns in the input table remain unchanged. """ if isinstance(table, pandas.DataFrame): cat_columns = table.select_dtypes(include=['category']).columns else: cat_columns = [] new_frame = _apply_along_column(table, standardize_column, with_std=with_std) # work around for apply converting category dtype to object # https://github.com/pydata/pandas/issues/9573 for col in cat_columns: new_frame[col] = table[col].copy() return new_frame
[ "def", "standardize", "(", "table", ",", "with_std", "=", "True", ")", ":", "if", "isinstance", "(", "table", ",", "pandas", ".", "DataFrame", ")", ":", "cat_columns", "=", "table", ".", "select_dtypes", "(", "include", "=", "[", "'category'", "]", ")", ...
Perform Z-Normalization on each numeric column of the given table. Parameters ---------- table : pandas.DataFrame or numpy.ndarray Data to standardize. with_std : bool, optional, default: True If ``False`` data is only centered and not converted to unit variance. Returns ------- normalized : pandas.DataFrame Table with numeric columns normalized. Categorical columns in the input table remain unchanged.
[ "Perform", "Z", "-", "Normalization", "on", "each", "numeric", "column", "of", "the", "given", "table", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/column.py#L47-L77
train
227,631
sebp/scikit-survival
sksurv/column.py
encode_categorical
def encode_categorical(table, columns=None, **kwargs): """ Encode categorical columns with `M` categories into `M-1` columns according to the one-hot scheme. Parameters ---------- table : pandas.DataFrame Table with categorical columns to encode. columns : list-like, optional, default: None Column names in the DataFrame to be encoded. If `columns` is None then all the columns with `object` or `category` dtype will be converted. allow_drop : boolean, optional, default: True Whether to allow dropping categorical columns that only consist of a single category. Returns ------- encoded : pandas.DataFrame Table with categorical columns encoded as numeric. Numeric columns in the input table remain unchanged. """ if isinstance(table, pandas.Series): if not is_categorical_dtype(table.dtype) and not table.dtype.char == "O": raise TypeError("series must be of categorical dtype, but was {}".format(table.dtype)) return _encode_categorical_series(table, **kwargs) def _is_categorical_or_object(series): return is_categorical_dtype(series.dtype) or series.dtype.char == "O" if columns is None: # for columns containing categories columns_to_encode = {nam for nam, s in table.iteritems() if _is_categorical_or_object(s)} else: columns_to_encode = set(columns) items = [] for name, series in table.iteritems(): if name in columns_to_encode: series = _encode_categorical_series(series, **kwargs) if series is None: continue items.append(series) # concat columns of tables new_table = pandas.concat(items, axis=1, copy=False) return new_table
python
def encode_categorical(table, columns=None, **kwargs): """ Encode categorical columns with `M` categories into `M-1` columns according to the one-hot scheme. Parameters ---------- table : pandas.DataFrame Table with categorical columns to encode. columns : list-like, optional, default: None Column names in the DataFrame to be encoded. If `columns` is None then all the columns with `object` or `category` dtype will be converted. allow_drop : boolean, optional, default: True Whether to allow dropping categorical columns that only consist of a single category. Returns ------- encoded : pandas.DataFrame Table with categorical columns encoded as numeric. Numeric columns in the input table remain unchanged. """ if isinstance(table, pandas.Series): if not is_categorical_dtype(table.dtype) and not table.dtype.char == "O": raise TypeError("series must be of categorical dtype, but was {}".format(table.dtype)) return _encode_categorical_series(table, **kwargs) def _is_categorical_or_object(series): return is_categorical_dtype(series.dtype) or series.dtype.char == "O" if columns is None: # for columns containing categories columns_to_encode = {nam for nam, s in table.iteritems() if _is_categorical_or_object(s)} else: columns_to_encode = set(columns) items = [] for name, series in table.iteritems(): if name in columns_to_encode: series = _encode_categorical_series(series, **kwargs) if series is None: continue items.append(series) # concat columns of tables new_table = pandas.concat(items, axis=1, copy=False) return new_table
[ "def", "encode_categorical", "(", "table", ",", "columns", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "table", ",", "pandas", ".", "Series", ")", ":", "if", "not", "is_categorical_dtype", "(", "table", ".", "dtype", ")", "...
Encode categorical columns with `M` categories into `M-1` columns according to the one-hot scheme. Parameters ---------- table : pandas.DataFrame Table with categorical columns to encode. columns : list-like, optional, default: None Column names in the DataFrame to be encoded. If `columns` is None then all the columns with `object` or `category` dtype will be converted. allow_drop : boolean, optional, default: True Whether to allow dropping categorical columns that only consist of a single category. Returns ------- encoded : pandas.DataFrame Table with categorical columns encoded as numeric. Numeric columns in the input table remain unchanged.
[ "Encode", "categorical", "columns", "with", "M", "categories", "into", "M", "-", "1", "columns", "according", "to", "the", "one", "-", "hot", "scheme", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/column.py#L97-L146
train
227,632
sebp/scikit-survival
sksurv/column.py
categorical_to_numeric
def categorical_to_numeric(table): """Encode categorical columns to numeric by converting each category to an integer value. Parameters ---------- table : pandas.DataFrame Table with categorical columns to encode. Returns ------- encoded : pandas.DataFrame Table with categorical columns encoded as numeric. Numeric columns in the input table remain unchanged. """ def transform(column): if is_categorical_dtype(column.dtype): return column.cat.codes if column.dtype.char == "O": try: nc = column.astype(numpy.int64) except ValueError: classes = column.dropna().unique() classes.sort(kind="mergesort") nc = column.replace(classes, numpy.arange(classes.shape[0])) return nc elif column.dtype == bool: return column.astype(numpy.int64) return column if isinstance(table, pandas.Series): return pandas.Series(transform(table), name=table.name, index=table.index) else: if _pandas_version_under0p23: return table.apply(transform, axis=0, reduce=False) else: return table.apply(transform, axis=0, result_type='reduce')
python
def categorical_to_numeric(table): """Encode categorical columns to numeric by converting each category to an integer value. Parameters ---------- table : pandas.DataFrame Table with categorical columns to encode. Returns ------- encoded : pandas.DataFrame Table with categorical columns encoded as numeric. Numeric columns in the input table remain unchanged. """ def transform(column): if is_categorical_dtype(column.dtype): return column.cat.codes if column.dtype.char == "O": try: nc = column.astype(numpy.int64) except ValueError: classes = column.dropna().unique() classes.sort(kind="mergesort") nc = column.replace(classes, numpy.arange(classes.shape[0])) return nc elif column.dtype == bool: return column.astype(numpy.int64) return column if isinstance(table, pandas.Series): return pandas.Series(transform(table), name=table.name, index=table.index) else: if _pandas_version_under0p23: return table.apply(transform, axis=0, reduce=False) else: return table.apply(transform, axis=0, result_type='reduce')
[ "def", "categorical_to_numeric", "(", "table", ")", ":", "def", "transform", "(", "column", ")", ":", "if", "is_categorical_dtype", "(", "column", ".", "dtype", ")", ":", "return", "column", ".", "cat", ".", "codes", "if", "column", ".", "dtype", ".", "c...
Encode categorical columns to numeric by converting each category to an integer value. Parameters ---------- table : pandas.DataFrame Table with categorical columns to encode. Returns ------- encoded : pandas.DataFrame Table with categorical columns encoded as numeric. Numeric columns in the input table remain unchanged.
[ "Encode", "categorical", "columns", "to", "numeric", "by", "converting", "each", "category", "to", "an", "integer", "value", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/column.py#L171-L208
train
227,633
sebp/scikit-survival
sksurv/util.py
check_y_survival
def check_y_survival(y_or_event, *args, allow_all_censored=False): """Check that array correctly represents an outcome for survival analysis. Parameters ---------- y_or_event : structured array with two fields, or boolean array If a structured array, it must contain the binary event indicator as first field, and time of event or time of censoring as second field. Otherwise, it is assumed that a boolean array representing the event indicator is passed. *args : list of array-likes Any number of array-like objects representing time information. Elements that are `None` are passed along in the return value. allow_all_censored : bool, optional, default: False Whether to allow all events to be censored. Returns ------- event : array, shape=[n_samples,], dtype=bool Binary event indicator. time : array, shape=[n_samples,], dtype=float Time of event or censoring. """ if len(args) == 0: y = y_or_event if not isinstance(y, numpy.ndarray) or y.dtype.fields is None or len(y.dtype.fields) != 2: raise ValueError('y must be a structured array with the first field' ' being a binary class event indicator and the second field' ' the time of the event/censoring') event_field, time_field = y.dtype.names y_event = y[event_field] time_args = (y[time_field],) else: y_event = numpy.asanyarray(y_or_event) time_args = args event = check_array(y_event, ensure_2d=False) if not numpy.issubdtype(event.dtype, numpy.bool_): raise ValueError('elements of event indicator must be boolean, but found {0}'.format(event.dtype)) if not (allow_all_censored or numpy.any(event)): raise ValueError('all samples are censored') return_val = [event] for i, yt in enumerate(time_args): if yt is None: return_val.append(yt) continue yt = check_array(yt, ensure_2d=False) if not numpy.issubdtype(yt.dtype, numpy.number): raise ValueError('time must be numeric, but found {} for argument {}'.format(yt.dtype, i + 2)) return_val.append(yt) return tuple(return_val)
python
def check_y_survival(y_or_event, *args, allow_all_censored=False): """Check that array correctly represents an outcome for survival analysis. Parameters ---------- y_or_event : structured array with two fields, or boolean array If a structured array, it must contain the binary event indicator as first field, and time of event or time of censoring as second field. Otherwise, it is assumed that a boolean array representing the event indicator is passed. *args : list of array-likes Any number of array-like objects representing time information. Elements that are `None` are passed along in the return value. allow_all_censored : bool, optional, default: False Whether to allow all events to be censored. Returns ------- event : array, shape=[n_samples,], dtype=bool Binary event indicator. time : array, shape=[n_samples,], dtype=float Time of event or censoring. """ if len(args) == 0: y = y_or_event if not isinstance(y, numpy.ndarray) or y.dtype.fields is None or len(y.dtype.fields) != 2: raise ValueError('y must be a structured array with the first field' ' being a binary class event indicator and the second field' ' the time of the event/censoring') event_field, time_field = y.dtype.names y_event = y[event_field] time_args = (y[time_field],) else: y_event = numpy.asanyarray(y_or_event) time_args = args event = check_array(y_event, ensure_2d=False) if not numpy.issubdtype(event.dtype, numpy.bool_): raise ValueError('elements of event indicator must be boolean, but found {0}'.format(event.dtype)) if not (allow_all_censored or numpy.any(event)): raise ValueError('all samples are censored') return_val = [event] for i, yt in enumerate(time_args): if yt is None: return_val.append(yt) continue yt = check_array(yt, ensure_2d=False) if not numpy.issubdtype(yt.dtype, numpy.number): raise ValueError('time must be numeric, but found {} for argument {}'.format(yt.dtype, i + 2)) return_val.append(yt) return tuple(return_val)
[ "def", "check_y_survival", "(", "y_or_event", ",", "*", "args", ",", "allow_all_censored", "=", "False", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "y", "=", "y_or_event", "if", "not", "isinstance", "(", "y", ",", "numpy", ".", "ndarray",...
Check that array correctly represents an outcome for survival analysis. Parameters ---------- y_or_event : structured array with two fields, or boolean array If a structured array, it must contain the binary event indicator as first field, and time of event or time of censoring as second field. Otherwise, it is assumed that a boolean array representing the event indicator is passed. *args : list of array-likes Any number of array-like objects representing time information. Elements that are `None` are passed along in the return value. allow_all_censored : bool, optional, default: False Whether to allow all events to be censored. Returns ------- event : array, shape=[n_samples,], dtype=bool Binary event indicator. time : array, shape=[n_samples,], dtype=float Time of event or censoring.
[ "Check", "that", "array", "correctly", "represents", "an", "outcome", "for", "survival", "analysis", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L104-L164
train
227,634
sebp/scikit-survival
sksurv/util.py
check_arrays_survival
def check_arrays_survival(X, y, **kwargs): """Check that all arrays have consistent first dimensions. Parameters ---------- X : array-like Data matrix containing feature vectors. y : structured array with two fields A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. kwargs : dict Additional arguments passed to :func:`sklearn.utils.check_array`. Returns ------- X : array, shape=[n_samples, n_features] Feature vectors. event : array, shape=[n_samples,], dtype=bool Binary event indicator. time : array, shape=[n_samples,], dtype=float Time of event or censoring. """ event, time = check_y_survival(y) kwargs.setdefault("dtype", numpy.float64) X = check_array(X, ensure_min_samples=2, **kwargs) check_consistent_length(X, event, time) return X, event, time
python
def check_arrays_survival(X, y, **kwargs): """Check that all arrays have consistent first dimensions. Parameters ---------- X : array-like Data matrix containing feature vectors. y : structured array with two fields A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. kwargs : dict Additional arguments passed to :func:`sklearn.utils.check_array`. Returns ------- X : array, shape=[n_samples, n_features] Feature vectors. event : array, shape=[n_samples,], dtype=bool Binary event indicator. time : array, shape=[n_samples,], dtype=float Time of event or censoring. """ event, time = check_y_survival(y) kwargs.setdefault("dtype", numpy.float64) X = check_array(X, ensure_min_samples=2, **kwargs) check_consistent_length(X, event, time) return X, event, time
[ "def", "check_arrays_survival", "(", "X", ",", "y", ",", "*", "*", "kwargs", ")", ":", "event", ",", "time", "=", "check_y_survival", "(", "y", ")", "kwargs", ".", "setdefault", "(", "\"dtype\"", ",", "numpy", ".", "float64", ")", "X", "=", "check_arra...
Check that all arrays have consistent first dimensions. Parameters ---------- X : array-like Data matrix containing feature vectors. y : structured array with two fields A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. kwargs : dict Additional arguments passed to :func:`sklearn.utils.check_array`. Returns ------- X : array, shape=[n_samples, n_features] Feature vectors. event : array, shape=[n_samples,], dtype=bool Binary event indicator. time : array, shape=[n_samples,], dtype=float Time of event or censoring.
[ "Check", "that", "all", "arrays", "have", "consistent", "first", "dimensions", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L167-L198
train
227,635
sebp/scikit-survival
sksurv/util.py
Surv.from_arrays
def from_arrays(event, time, name_event=None, name_time=None): """Create structured array. Parameters ---------- event : array-like Event indicator. A boolean array or array with values 0/1. time : array-like Observed time. name_event : str|None Name of event, optional, default: 'event' name_time : str|None Name of observed time, optional, default: 'time' Returns ------- y : np.array Structured array with two fields. """ name_event = name_event or 'event' name_time = name_time or 'time' if name_time == name_event: raise ValueError('name_time must be different from name_event') time = numpy.asanyarray(time, dtype=numpy.float_) y = numpy.empty(time.shape[0], dtype=[(name_event, numpy.bool_), (name_time, numpy.float_)]) y[name_time] = time event = numpy.asanyarray(event) check_consistent_length(time, event) if numpy.issubdtype(event.dtype, numpy.bool_): y[name_event] = event else: events = numpy.unique(event) events.sort() if len(events) != 2: raise ValueError('event indicator must be binary') if numpy.all(events == numpy.array([0, 1], dtype=events.dtype)): y[name_event] = event.astype(numpy.bool_) else: raise ValueError('non-boolean event indicator must contain 0 and 1 only') return y
python
def from_arrays(event, time, name_event=None, name_time=None): """Create structured array. Parameters ---------- event : array-like Event indicator. A boolean array or array with values 0/1. time : array-like Observed time. name_event : str|None Name of event, optional, default: 'event' name_time : str|None Name of observed time, optional, default: 'time' Returns ------- y : np.array Structured array with two fields. """ name_event = name_event or 'event' name_time = name_time or 'time' if name_time == name_event: raise ValueError('name_time must be different from name_event') time = numpy.asanyarray(time, dtype=numpy.float_) y = numpy.empty(time.shape[0], dtype=[(name_event, numpy.bool_), (name_time, numpy.float_)]) y[name_time] = time event = numpy.asanyarray(event) check_consistent_length(time, event) if numpy.issubdtype(event.dtype, numpy.bool_): y[name_event] = event else: events = numpy.unique(event) events.sort() if len(events) != 2: raise ValueError('event indicator must be binary') if numpy.all(events == numpy.array([0, 1], dtype=events.dtype)): y[name_event] = event.astype(numpy.bool_) else: raise ValueError('non-boolean event indicator must contain 0 and 1 only') return y
[ "def", "from_arrays", "(", "event", ",", "time", ",", "name_event", "=", "None", ",", "name_time", "=", "None", ")", ":", "name_event", "=", "name_event", "or", "'event'", "name_time", "=", "name_time", "or", "'time'", "if", "name_time", "==", "name_event", ...
Create structured array. Parameters ---------- event : array-like Event indicator. A boolean array or array with values 0/1. time : array-like Observed time. name_event : str|None Name of event, optional, default: 'event' name_time : str|None Name of observed time, optional, default: 'time' Returns ------- y : np.array Structured array with two fields.
[ "Create", "structured", "array", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L28-L73
train
227,636
sebp/scikit-survival
sksurv/util.py
Surv.from_dataframe
def from_dataframe(event, time, data): """Create structured array from data frame. Parameters ---------- event : object Identifier of column containing event indicator. time : object Identifier of column containing time. data : pandas.DataFrame Dataset. Returns ------- y : np.array Structured array with two fields. """ if not isinstance(data, pandas.DataFrame): raise TypeError( "exepected pandas.DataFrame, but got {!r}".format(type(data))) return Surv.from_arrays( data.loc[:, event].values, data.loc[:, time].values, name_event=str(event), name_time=str(time))
python
def from_dataframe(event, time, data): """Create structured array from data frame. Parameters ---------- event : object Identifier of column containing event indicator. time : object Identifier of column containing time. data : pandas.DataFrame Dataset. Returns ------- y : np.array Structured array with two fields. """ if not isinstance(data, pandas.DataFrame): raise TypeError( "exepected pandas.DataFrame, but got {!r}".format(type(data))) return Surv.from_arrays( data.loc[:, event].values, data.loc[:, time].values, name_event=str(event), name_time=str(time))
[ "def", "from_dataframe", "(", "event", ",", "time", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "pandas", ".", "DataFrame", ")", ":", "raise", "TypeError", "(", "\"exepected pandas.DataFrame, but got {!r}\"", ".", "format", "(", "type",...
Create structured array from data frame. Parameters ---------- event : object Identifier of column containing event indicator. time : object Identifier of column containing time. data : pandas.DataFrame Dataset. Returns ------- y : np.array Structured array with two fields.
[ "Create", "structured", "array", "from", "data", "frame", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/util.py#L76-L101
train
227,637
sebp/scikit-survival
sksurv/ensemble/survival_loss.py
CoxPH.update_terminal_regions
def update_terminal_regions(self, tree, X, y, residual, y_pred, sample_weight, sample_mask, learning_rate=1.0, k=0): """Least squares does not need to update terminal regions. But it has to update the predictions. """ # update predictions y_pred[:, k] += learning_rate * tree.predict(X).ravel()
python
def update_terminal_regions(self, tree, X, y, residual, y_pred, sample_weight, sample_mask, learning_rate=1.0, k=0): """Least squares does not need to update terminal regions. But it has to update the predictions. """ # update predictions y_pred[:, k] += learning_rate * tree.predict(X).ravel()
[ "def", "update_terminal_regions", "(", "self", ",", "tree", ",", "X", ",", "y", ",", "residual", ",", "y_pred", ",", "sample_weight", ",", "sample_mask", ",", "learning_rate", "=", "1.0", ",", "k", "=", "0", ")", ":", "# update predictions", "y_pred", "[",...
Least squares does not need to update terminal regions. But it has to update the predictions.
[ "Least", "squares", "does", "not", "need", "to", "update", "terminal", "regions", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/survival_loss.py#L55-L63
train
227,638
sebp/scikit-survival
sksurv/setup.py
build_from_c_and_cpp_files
def build_from_c_and_cpp_files(extensions): """Modify the extensions to build from the .c and .cpp files. This is useful for releases, this way cython is not required to run python setup.py install. """ for extension in extensions: sources = [] for sfile in extension.sources: path, ext = os.path.splitext(sfile) if ext in ('.pyx', '.py'): if extension.language == 'c++': ext = '.cpp' else: ext = '.c' sfile = path + ext sources.append(sfile) extension.sources = sources
python
def build_from_c_and_cpp_files(extensions): """Modify the extensions to build from the .c and .cpp files. This is useful for releases, this way cython is not required to run python setup.py install. """ for extension in extensions: sources = [] for sfile in extension.sources: path, ext = os.path.splitext(sfile) if ext in ('.pyx', '.py'): if extension.language == 'c++': ext = '.cpp' else: ext = '.c' sfile = path + ext sources.append(sfile) extension.sources = sources
[ "def", "build_from_c_and_cpp_files", "(", "extensions", ")", ":", "for", "extension", "in", "extensions", ":", "sources", "=", "[", "]", "for", "sfile", "in", "extension", ".", "sources", ":", "path", ",", "ext", "=", "os", ".", "path", ".", "splitext", ...
Modify the extensions to build from the .c and .cpp files. This is useful for releases, this way cython is not required to run python setup.py install.
[ "Modify", "the", "extensions", "to", "build", "from", "the", ".", "c", "and", ".", "cpp", "files", ".", "This", "is", "useful", "for", "releases", "this", "way", "cython", "is", "not", "required", "to", "run", "python", "setup", ".", "py", "install", "...
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/setup.py#L20-L36
train
227,639
sebp/scikit-survival
sksurv/svm/survival_svm.py
SurvivalCounter._count_values
def _count_values(self): """Return dict mapping relevance level to sample index""" indices = {yi: [i] for i, yi in enumerate(self.y) if self.status[i]} return indices
python
def _count_values(self): """Return dict mapping relevance level to sample index""" indices = {yi: [i] for i, yi in enumerate(self.y) if self.status[i]} return indices
[ "def", "_count_values", "(", "self", ")", ":", "indices", "=", "{", "yi", ":", "[", "i", "]", "for", "i", ",", "yi", "in", "enumerate", "(", "self", ".", "y", ")", "if", "self", ".", "status", "[", "i", "]", "}", "return", "indices" ]
Return dict mapping relevance level to sample index
[ "Return", "dict", "mapping", "relevance", "level", "to", "sample", "index" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/survival_svm.py#L134-L138
train
227,640
sebp/scikit-survival
sksurv/svm/survival_svm.py
BaseSurvivalSVM._create_optimizer
def _create_optimizer(self, X, y, status): """Samples are ordered by relevance""" if self.optimizer is None: self.optimizer = 'avltree' times, ranks = y if self.optimizer == 'simple': optimizer = SimpleOptimizer(X, status, self.alpha, self.rank_ratio, timeit=self.timeit) elif self.optimizer == 'PRSVM': optimizer = PRSVMOptimizer(X, status, self.alpha, self.rank_ratio, timeit=self.timeit) elif self.optimizer == 'direct-count': optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept, SurvivalCounter(X, ranks, status, len(ranks), times), timeit=self.timeit) elif self.optimizer == 'rbtree': optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept, OrderStatisticTreeSurvivalCounter(X, ranks, status, RBTree, times), timeit=self.timeit) elif self.optimizer == 'avltree': optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept, OrderStatisticTreeSurvivalCounter(X, ranks, status, AVLTree, times), timeit=self.timeit) else: raise ValueError('unknown optimizer: {0}'.format(self.optimizer)) return optimizer
python
def _create_optimizer(self, X, y, status): """Samples are ordered by relevance""" if self.optimizer is None: self.optimizer = 'avltree' times, ranks = y if self.optimizer == 'simple': optimizer = SimpleOptimizer(X, status, self.alpha, self.rank_ratio, timeit=self.timeit) elif self.optimizer == 'PRSVM': optimizer = PRSVMOptimizer(X, status, self.alpha, self.rank_ratio, timeit=self.timeit) elif self.optimizer == 'direct-count': optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept, SurvivalCounter(X, ranks, status, len(ranks), times), timeit=self.timeit) elif self.optimizer == 'rbtree': optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept, OrderStatisticTreeSurvivalCounter(X, ranks, status, RBTree, times), timeit=self.timeit) elif self.optimizer == 'avltree': optimizer = LargeScaleOptimizer(self.alpha, self.rank_ratio, self.fit_intercept, OrderStatisticTreeSurvivalCounter(X, ranks, status, AVLTree, times), timeit=self.timeit) else: raise ValueError('unknown optimizer: {0}'.format(self.optimizer)) return optimizer
[ "def", "_create_optimizer", "(", "self", ",", "X", ",", "y", ",", "status", ")", ":", "if", "self", ".", "optimizer", "is", "None", ":", "self", ".", "optimizer", "=", "'avltree'", "times", ",", "ranks", "=", "y", "if", "self", ".", "optimizer", "=="...
Samples are ordered by relevance
[ "Samples", "are", "ordered", "by", "relevance" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/survival_svm.py#L608-L633
train
227,641
sebp/scikit-survival
sksurv/svm/survival_svm.py
BaseSurvivalSVM._argsort_and_resolve_ties
def _argsort_and_resolve_ties(time, random_state): """Like numpy.argsort, but resolves ties uniformly at random""" n_samples = len(time) order = numpy.argsort(time, kind="mergesort") i = 0 while i < n_samples - 1: inext = i + 1 while inext < n_samples and time[order[i]] == time[order[inext]]: inext += 1 if i + 1 != inext: # resolve ties randomly random_state.shuffle(order[i:inext]) i = inext return order
python
def _argsort_and_resolve_ties(time, random_state): """Like numpy.argsort, but resolves ties uniformly at random""" n_samples = len(time) order = numpy.argsort(time, kind="mergesort") i = 0 while i < n_samples - 1: inext = i + 1 while inext < n_samples and time[order[i]] == time[order[inext]]: inext += 1 if i + 1 != inext: # resolve ties randomly random_state.shuffle(order[i:inext]) i = inext return order
[ "def", "_argsort_and_resolve_ties", "(", "time", ",", "random_state", ")", ":", "n_samples", "=", "len", "(", "time", ")", "order", "=", "numpy", ".", "argsort", "(", "time", ",", "kind", "=", "\"mergesort\"", ")", "i", "=", "0", "while", "i", "<", "n_...
Like numpy.argsort, but resolves ties uniformly at random
[ "Like", "numpy", ".", "argsort", "but", "resolves", "ties", "uniformly", "at", "random" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/survival_svm.py#L702-L717
train
227,642
sebp/scikit-survival
sksurv/linear_model/aft.py
IPCRidge.fit
def fit(self, X, y): """Build an accelerated failure time model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self """ X, event, time = check_arrays_survival(X, y) weights = ipc_weights(event, time) super().fit(X, numpy.log(time), sample_weight=weights) return self
python
def fit(self, X, y): """Build an accelerated failure time model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self """ X, event, time = check_arrays_survival(X, y) weights = ipc_weights(event, time) super().fit(X, numpy.log(time), sample_weight=weights) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "X", ",", "event", ",", "time", "=", "check_arrays_survival", "(", "X", ",", "y", ")", "weights", "=", "ipc_weights", "(", "event", ",", "time", ")", "super", "(", ")", ".", "fit", "(", "...
Build an accelerated failure time model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self
[ "Build", "an", "accelerated", "failure", "time", "model", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/aft.py#L52-L74
train
227,643
sebp/scikit-survival
sksurv/linear_model/coxph.py
BreslowEstimator.fit
def fit(self, linear_predictor, event, time): """Compute baseline cumulative hazard function. Parameters ---------- linear_predictor : array-like, shape = (n_samples,) Linear predictor of risk: `X @ coef`. event : array-like, shape = (n_samples,) Contains binary event indicators. time : array-like, shape = (n_samples,) Contains event/censoring times. Returns ------- self """ risk_score = numpy.exp(linear_predictor) order = numpy.argsort(time, kind="mergesort") risk_score = risk_score[order] uniq_times, n_events, n_at_risk = _compute_counts(event, time, order) divisor = numpy.empty(n_at_risk.shape, dtype=numpy.float_) value = numpy.sum(risk_score) divisor[0] = value k = 0 for i in range(1, len(n_at_risk)): d = n_at_risk[i - 1] - n_at_risk[i] value -= risk_score[k:(k + d)].sum() k += d divisor[i] = value assert k == n_at_risk[0] - n_at_risk[-1] y = numpy.cumsum(n_events / divisor) self.cum_baseline_hazard_ = StepFunction(uniq_times, y) self.baseline_survival_ = StepFunction(self.cum_baseline_hazard_.x, numpy.exp(- self.cum_baseline_hazard_.y)) return self
python
def fit(self, linear_predictor, event, time): """Compute baseline cumulative hazard function. Parameters ---------- linear_predictor : array-like, shape = (n_samples,) Linear predictor of risk: `X @ coef`. event : array-like, shape = (n_samples,) Contains binary event indicators. time : array-like, shape = (n_samples,) Contains event/censoring times. Returns ------- self """ risk_score = numpy.exp(linear_predictor) order = numpy.argsort(time, kind="mergesort") risk_score = risk_score[order] uniq_times, n_events, n_at_risk = _compute_counts(event, time, order) divisor = numpy.empty(n_at_risk.shape, dtype=numpy.float_) value = numpy.sum(risk_score) divisor[0] = value k = 0 for i in range(1, len(n_at_risk)): d = n_at_risk[i - 1] - n_at_risk[i] value -= risk_score[k:(k + d)].sum() k += d divisor[i] = value assert k == n_at_risk[0] - n_at_risk[-1] y = numpy.cumsum(n_events / divisor) self.cum_baseline_hazard_ = StepFunction(uniq_times, y) self.baseline_survival_ = StepFunction(self.cum_baseline_hazard_.x, numpy.exp(- self.cum_baseline_hazard_.y)) return self
[ "def", "fit", "(", "self", ",", "linear_predictor", ",", "event", ",", "time", ")", ":", "risk_score", "=", "numpy", ".", "exp", "(", "linear_predictor", ")", "order", "=", "numpy", ".", "argsort", "(", "time", ",", "kind", "=", "\"mergesort\"", ")", "...
Compute baseline cumulative hazard function. Parameters ---------- linear_predictor : array-like, shape = (n_samples,) Linear predictor of risk: `X @ coef`. event : array-like, shape = (n_samples,) Contains binary event indicators. time : array-like, shape = (n_samples,) Contains event/censoring times. Returns ------- self
[ "Compute", "baseline", "cumulative", "hazard", "function", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxph.py#L42-L81
train
227,644
sebp/scikit-survival
sksurv/linear_model/coxph.py
CoxPHOptimizer.nlog_likelihood
def nlog_likelihood(self, w): """Compute negative partial log-likelihood Parameters ---------- w : array, shape = (n_features,) Estimate of coefficients Returns ------- loss : float Average negative partial log-likelihood """ time = self.time n_samples = self.x.shape[0] xw = numpy.dot(self.x, w) loss = 0 risk_set = 0 k = 0 for i in range(n_samples): ti = time[i] while k < n_samples and ti == time[k]: risk_set += numpy.exp(xw[k]) k += 1 if self.event[i]: loss -= (xw[i] - numpy.log(risk_set)) / n_samples # add regularization term to log-likelihood return loss + self.alpha * squared_norm(w) / (2. * n_samples)
python
def nlog_likelihood(self, w): """Compute negative partial log-likelihood Parameters ---------- w : array, shape = (n_features,) Estimate of coefficients Returns ------- loss : float Average negative partial log-likelihood """ time = self.time n_samples = self.x.shape[0] xw = numpy.dot(self.x, w) loss = 0 risk_set = 0 k = 0 for i in range(n_samples): ti = time[i] while k < n_samples and ti == time[k]: risk_set += numpy.exp(xw[k]) k += 1 if self.event[i]: loss -= (xw[i] - numpy.log(risk_set)) / n_samples # add regularization term to log-likelihood return loss + self.alpha * squared_norm(w) / (2. * n_samples)
[ "def", "nlog_likelihood", "(", "self", ",", "w", ")", ":", "time", "=", "self", ".", "time", "n_samples", "=", "self", ".", "x", ".", "shape", "[", "0", "]", "xw", "=", "numpy", ".", "dot", "(", "self", ".", "x", ",", "w", ")", "loss", "=", "...
Compute negative partial log-likelihood Parameters ---------- w : array, shape = (n_features,) Estimate of coefficients Returns ------- loss : float Average negative partial log-likelihood
[ "Compute", "negative", "partial", "log", "-", "likelihood" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxph.py#L138-L168
train
227,645
sebp/scikit-survival
sksurv/linear_model/coxph.py
CoxPHOptimizer.update
def update(self, w, offset=0): """Compute gradient and Hessian matrix with respect to `w`.""" time = self.time x = self.x exp_xw = numpy.exp(offset + numpy.dot(x, w)) n_samples, n_features = x.shape gradient = numpy.zeros((1, n_features), dtype=float) hessian = numpy.zeros((n_features, n_features), dtype=float) inv_n_samples = 1. / n_samples risk_set = 0 risk_set_x = 0 risk_set_xx = 0 k = 0 # iterate time in descending order for i in range(n_samples): ti = time[i] while k < n_samples and ti == time[k]: risk_set += exp_xw[k] # preserve 2D shape of row vector xk = x[k:k + 1] risk_set_x += exp_xw[k] * xk # outer product xx = numpy.dot(xk.T, xk) risk_set_xx += exp_xw[k] * xx k += 1 if self.event[i]: gradient -= (x[i:i + 1] - risk_set_x / risk_set) * inv_n_samples a = risk_set_xx / risk_set z = risk_set_x / risk_set # outer product b = numpy.dot(z.T, z) hessian += (a - b) * inv_n_samples if self.alpha > 0: gradient += self.alpha * inv_n_samples * w diag_idx = numpy.diag_indices(n_features) hessian[diag_idx] += self.alpha * inv_n_samples self.gradient = gradient.ravel() self.hessian = hessian
python
def update(self, w, offset=0): """Compute gradient and Hessian matrix with respect to `w`.""" time = self.time x = self.x exp_xw = numpy.exp(offset + numpy.dot(x, w)) n_samples, n_features = x.shape gradient = numpy.zeros((1, n_features), dtype=float) hessian = numpy.zeros((n_features, n_features), dtype=float) inv_n_samples = 1. / n_samples risk_set = 0 risk_set_x = 0 risk_set_xx = 0 k = 0 # iterate time in descending order for i in range(n_samples): ti = time[i] while k < n_samples and ti == time[k]: risk_set += exp_xw[k] # preserve 2D shape of row vector xk = x[k:k + 1] risk_set_x += exp_xw[k] * xk # outer product xx = numpy.dot(xk.T, xk) risk_set_xx += exp_xw[k] * xx k += 1 if self.event[i]: gradient -= (x[i:i + 1] - risk_set_x / risk_set) * inv_n_samples a = risk_set_xx / risk_set z = risk_set_x / risk_set # outer product b = numpy.dot(z.T, z) hessian += (a - b) * inv_n_samples if self.alpha > 0: gradient += self.alpha * inv_n_samples * w diag_idx = numpy.diag_indices(n_features) hessian[diag_idx] += self.alpha * inv_n_samples self.gradient = gradient.ravel() self.hessian = hessian
[ "def", "update", "(", "self", ",", "w", ",", "offset", "=", "0", ")", ":", "time", "=", "self", ".", "time", "x", "=", "self", ".", "x", "exp_xw", "=", "numpy", ".", "exp", "(", "offset", "+", "numpy", ".", "dot", "(", "x", ",", "w", ")", "...
Compute gradient and Hessian matrix with respect to `w`.
[ "Compute", "gradient", "and", "Hessian", "matrix", "with", "respect", "to", "w", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxph.py#L170-L218
train
227,646
sebp/scikit-survival
sksurv/linear_model/coxph.py
CoxPHSurvivalAnalysis.fit
def fit(self, X, y): """Minimize negative partial log-likelihood for provided data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self """ X, event, time = check_arrays_survival(X, y) if self.alpha < 0: raise ValueError("alpha must be positive, but was %r" % self.alpha) optimizer = CoxPHOptimizer(X, event, time, self.alpha) verbose_reporter = VerboseReporter(self.verbose) w = numpy.zeros(X.shape[1]) w_prev = w i = 0 loss = float('inf') while True: if i >= self.n_iter: verbose_reporter.end_max_iter(i) warnings.warn(('Optimization did not converge: Maximum number of iterations has been exceeded.'), stacklevel=2, category=ConvergenceWarning) break optimizer.update(w) delta = solve(optimizer.hessian, optimizer.gradient, overwrite_a=False, overwrite_b=False, check_finite=False) if not numpy.all(numpy.isfinite(delta)): raise ValueError("search direction contains NaN or infinite values") w_new = w - delta loss_new = optimizer.nlog_likelihood(w_new) verbose_reporter.update(i, delta, loss_new) if loss_new > loss: # perform step-halving if negative log-likelihood does not decrease w = (w_prev + w) / 2 loss = optimizer.nlog_likelihood(w) verbose_reporter.step_halving(i, loss) i += 1 continue w_prev = w w = w_new res = numpy.abs(1 - (loss_new / loss)) if res < self.tol: verbose_reporter.end_converged(i) break loss = loss_new i += 1 self.coef_ = w self._baseline_model.fit(numpy.dot(X, self.coef_), event, time) return self
python
def fit(self, X, y): """Minimize negative partial log-likelihood for provided data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self """ X, event, time = check_arrays_survival(X, y) if self.alpha < 0: raise ValueError("alpha must be positive, but was %r" % self.alpha) optimizer = CoxPHOptimizer(X, event, time, self.alpha) verbose_reporter = VerboseReporter(self.verbose) w = numpy.zeros(X.shape[1]) w_prev = w i = 0 loss = float('inf') while True: if i >= self.n_iter: verbose_reporter.end_max_iter(i) warnings.warn(('Optimization did not converge: Maximum number of iterations has been exceeded.'), stacklevel=2, category=ConvergenceWarning) break optimizer.update(w) delta = solve(optimizer.hessian, optimizer.gradient, overwrite_a=False, overwrite_b=False, check_finite=False) if not numpy.all(numpy.isfinite(delta)): raise ValueError("search direction contains NaN or infinite values") w_new = w - delta loss_new = optimizer.nlog_likelihood(w_new) verbose_reporter.update(i, delta, loss_new) if loss_new > loss: # perform step-halving if negative log-likelihood does not decrease w = (w_prev + w) / 2 loss = optimizer.nlog_likelihood(w) verbose_reporter.step_halving(i, loss) i += 1 continue w_prev = w w = w_new res = numpy.abs(1 - (loss_new / loss)) if res < self.tol: verbose_reporter.end_converged(i) break loss = loss_new i += 1 self.coef_ = w self._baseline_model.fit(numpy.dot(X, self.coef_), event, time) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "X", ",", "event", ",", "time", "=", "check_arrays_survival", "(", "X", ",", "y", ")", "if", "self", ".", "alpha", "<", "0", ":", "raise", "ValueError", "(", "\"alpha must be positive, but was %r...
Minimize negative partial log-likelihood for provided data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self
[ "Minimize", "negative", "partial", "log", "-", "likelihood", "for", "provided", "data", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/linear_model/coxph.py#L292-L359
train
227,647
sebp/scikit-survival
sksurv/nonparametric.py
_compute_counts
def _compute_counts(event, time, order=None): """Count right censored and uncensored samples at each unique time point. Parameters ---------- event : array Boolean event indicator. time : array Survival time or time of censoring. order : array or None Indices to order time in ascending order. If None, order will be computed. Returns ------- times : array Unique time points. n_events : array Number of events at each time point. n_at_risk : array Number of samples that are censored or have an event at each time point. """ n_samples = event.shape[0] if order is None: order = numpy.argsort(time, kind="mergesort") uniq_times = numpy.empty(n_samples, dtype=time.dtype) uniq_events = numpy.empty(n_samples, dtype=numpy.int_) uniq_counts = numpy.empty(n_samples, dtype=numpy.int_) i = 0 prev_val = time[order[0]] j = 0 while True: count_event = 0 count = 0 while i < n_samples and prev_val == time[order[i]]: if event[order[i]]: count_event += 1 count += 1 i += 1 uniq_times[j] = prev_val uniq_events[j] = count_event uniq_counts[j] = count j += 1 if i == n_samples: break prev_val = time[order[i]] times = numpy.resize(uniq_times, j) n_events = numpy.resize(uniq_events, j) total_count = numpy.resize(uniq_counts, j) # offset cumulative sum by one total_count = numpy.concatenate(([0], total_count)) n_at_risk = n_samples - numpy.cumsum(total_count) return times, n_events, n_at_risk[:-1]
python
def _compute_counts(event, time, order=None): """Count right censored and uncensored samples at each unique time point. Parameters ---------- event : array Boolean event indicator. time : array Survival time or time of censoring. order : array or None Indices to order time in ascending order. If None, order will be computed. Returns ------- times : array Unique time points. n_events : array Number of events at each time point. n_at_risk : array Number of samples that are censored or have an event at each time point. """ n_samples = event.shape[0] if order is None: order = numpy.argsort(time, kind="mergesort") uniq_times = numpy.empty(n_samples, dtype=time.dtype) uniq_events = numpy.empty(n_samples, dtype=numpy.int_) uniq_counts = numpy.empty(n_samples, dtype=numpy.int_) i = 0 prev_val = time[order[0]] j = 0 while True: count_event = 0 count = 0 while i < n_samples and prev_val == time[order[i]]: if event[order[i]]: count_event += 1 count += 1 i += 1 uniq_times[j] = prev_val uniq_events[j] = count_event uniq_counts[j] = count j += 1 if i == n_samples: break prev_val = time[order[i]] times = numpy.resize(uniq_times, j) n_events = numpy.resize(uniq_events, j) total_count = numpy.resize(uniq_counts, j) # offset cumulative sum by one total_count = numpy.concatenate(([0], total_count)) n_at_risk = n_samples - numpy.cumsum(total_count) return times, n_events, n_at_risk[:-1]
[ "def", "_compute_counts", "(", "event", ",", "time", ",", "order", "=", "None", ")", ":", "n_samples", "=", "event", ".", "shape", "[", "0", "]", "if", "order", "is", "None", ":", "order", "=", "numpy", ".", "argsort", "(", "time", ",", "kind", "="...
Count right censored and uncensored samples at each unique time point. Parameters ---------- event : array Boolean event indicator. time : array Survival time or time of censoring. order : array or None Indices to order time in ascending order. If None, order will be computed. Returns ------- times : array Unique time points. n_events : array Number of events at each time point. n_at_risk : array Number of samples that are censored or have an event at each time point.
[ "Count", "right", "censored", "and", "uncensored", "samples", "at", "each", "unique", "time", "point", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L28-L94
train
227,648
sebp/scikit-survival
sksurv/nonparametric.py
_compute_counts_truncated
def _compute_counts_truncated(event, time_enter, time_exit): """Compute counts for left truncated and right censored survival data. Parameters ---------- event : array Boolean event indicator. time_start : array Time when a subject entered the study. time_exit : array Time when a subject left the study due to an event or censoring. Returns ------- times : array Unique time points. n_events : array Number of events at each time point. n_at_risk : array Number of samples that are censored or have an event at each time point. """ if (time_enter > time_exit).any(): raise ValueError("exit time must be larger start time for all samples") n_samples = event.shape[0] uniq_times = numpy.sort(numpy.unique(numpy.concatenate((time_enter, time_exit))), kind="mergesort") total_counts = numpy.empty(len(uniq_times), dtype=numpy.int_) event_counts = numpy.empty(len(uniq_times), dtype=numpy.int_) order_enter = numpy.argsort(time_enter, kind="mergesort") order_exit = numpy.argsort(time_exit, kind="mergesort") s_time_enter = time_enter[order_enter] s_time_exit = time_exit[order_exit] t0 = uniq_times[0] # everything larger is included idx_enter = numpy.searchsorted(s_time_enter, t0, side="right") # everything smaller is excluded idx_exit = numpy.searchsorted(s_time_exit, t0, side="left") total_counts[0] = idx_enter # except people die on the day they enter event_counts[0] = 0 for i in range(1, len(uniq_times)): ti = uniq_times[i] while idx_enter < n_samples and s_time_enter[idx_enter] <= ti: idx_enter += 1 while idx_exit < n_samples and s_time_exit[idx_exit] < ti: idx_exit += 1 risk_set = numpy.setdiff1d(order_enter[:idx_enter], order_exit[:idx_exit], assume_unique=True) total_counts[i] = len(risk_set) count_event = 0 k = idx_exit while k < n_samples and s_time_exit[k] == ti: if event[order_exit[k]]: count_event += 1 k += 1 event_counts[i] = count_event return uniq_times, event_counts, total_counts
python
def _compute_counts_truncated(event, time_enter, time_exit): """Compute counts for left truncated and right censored survival data. Parameters ---------- event : array Boolean event indicator. time_start : array Time when a subject entered the study. time_exit : array Time when a subject left the study due to an event or censoring. Returns ------- times : array Unique time points. n_events : array Number of events at each time point. n_at_risk : array Number of samples that are censored or have an event at each time point. """ if (time_enter > time_exit).any(): raise ValueError("exit time must be larger start time for all samples") n_samples = event.shape[0] uniq_times = numpy.sort(numpy.unique(numpy.concatenate((time_enter, time_exit))), kind="mergesort") total_counts = numpy.empty(len(uniq_times), dtype=numpy.int_) event_counts = numpy.empty(len(uniq_times), dtype=numpy.int_) order_enter = numpy.argsort(time_enter, kind="mergesort") order_exit = numpy.argsort(time_exit, kind="mergesort") s_time_enter = time_enter[order_enter] s_time_exit = time_exit[order_exit] t0 = uniq_times[0] # everything larger is included idx_enter = numpy.searchsorted(s_time_enter, t0, side="right") # everything smaller is excluded idx_exit = numpy.searchsorted(s_time_exit, t0, side="left") total_counts[0] = idx_enter # except people die on the day they enter event_counts[0] = 0 for i in range(1, len(uniq_times)): ti = uniq_times[i] while idx_enter < n_samples and s_time_enter[idx_enter] <= ti: idx_enter += 1 while idx_exit < n_samples and s_time_exit[idx_exit] < ti: idx_exit += 1 risk_set = numpy.setdiff1d(order_enter[:idx_enter], order_exit[:idx_exit], assume_unique=True) total_counts[i] = len(risk_set) count_event = 0 k = idx_exit while k < n_samples and s_time_exit[k] == ti: if event[order_exit[k]]: count_event += 1 k += 1 event_counts[i] = count_event return uniq_times, event_counts, total_counts
[ "def", "_compute_counts_truncated", "(", "event", ",", "time_enter", ",", "time_exit", ")", ":", "if", "(", "time_enter", ">", "time_exit", ")", ".", "any", "(", ")", ":", "raise", "ValueError", "(", "\"exit time must be larger start time for all samples\"", ")", ...
Compute counts for left truncated and right censored survival data. Parameters ---------- event : array Boolean event indicator. time_start : array Time when a subject entered the study. time_exit : array Time when a subject left the study due to an event or censoring. Returns ------- times : array Unique time points. n_events : array Number of events at each time point. n_at_risk : array Number of samples that are censored or have an event at each time point.
[ "Compute", "counts", "for", "left", "truncated", "and", "right", "censored", "survival", "data", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L97-L167
train
227,649
sebp/scikit-survival
sksurv/nonparametric.py
kaplan_meier_estimator
def kaplan_meier_estimator(event, time_exit, time_enter=None, time_min=None): """Kaplan-Meier estimator of survival function. Parameters ---------- event : array-like, shape = (n_samples,) Contains binary event indicators. time_exit : array-like, shape = (n_samples,) Contains event/censoring times. time_enter : array-like, shape = (n_samples,), optional Contains time when each individual entered the study for left truncated survival data. time_min : float, optional Compute estimator conditional on survival at least up to the specified time. Returns ------- time : array, shape = (n_times,) Unique times. prob_survival : array, shape = (n_times,) Survival probability at each unique time point. If `time_enter` is provided, estimates are conditional probabilities. Examples -------- Creating a Kaplan-Meier curve: >>> x, y = kaplan_meier_estimator(event, time) >>> plt.step(x, y, where="post") >>> plt.ylim(0, 1) >>> plt.show() References ---------- .. [1] Kaplan, E. L. and Meier, P., "Nonparametric estimation from incomplete observations", Journal of The American Statistical Association, vol. 53, pp. 457-481, 1958. """ event, time_enter, time_exit = check_y_survival(event, time_enter, time_exit, allow_all_censored=True) check_consistent_length(event, time_enter, time_exit) if time_enter is None: uniq_times, n_events, n_at_risk = _compute_counts(event, time_exit) else: uniq_times, n_events, n_at_risk = _compute_counts_truncated(event, time_enter, time_exit) values = 1 - n_events / n_at_risk if time_min is not None: mask = uniq_times >= time_min uniq_times = numpy.compress(mask, uniq_times) values = numpy.compress(mask, values) y = numpy.cumprod(values) return uniq_times, y
python
def kaplan_meier_estimator(event, time_exit, time_enter=None, time_min=None): """Kaplan-Meier estimator of survival function. Parameters ---------- event : array-like, shape = (n_samples,) Contains binary event indicators. time_exit : array-like, shape = (n_samples,) Contains event/censoring times. time_enter : array-like, shape = (n_samples,), optional Contains time when each individual entered the study for left truncated survival data. time_min : float, optional Compute estimator conditional on survival at least up to the specified time. Returns ------- time : array, shape = (n_times,) Unique times. prob_survival : array, shape = (n_times,) Survival probability at each unique time point. If `time_enter` is provided, estimates are conditional probabilities. Examples -------- Creating a Kaplan-Meier curve: >>> x, y = kaplan_meier_estimator(event, time) >>> plt.step(x, y, where="post") >>> plt.ylim(0, 1) >>> plt.show() References ---------- .. [1] Kaplan, E. L. and Meier, P., "Nonparametric estimation from incomplete observations", Journal of The American Statistical Association, vol. 53, pp. 457-481, 1958. """ event, time_enter, time_exit = check_y_survival(event, time_enter, time_exit, allow_all_censored=True) check_consistent_length(event, time_enter, time_exit) if time_enter is None: uniq_times, n_events, n_at_risk = _compute_counts(event, time_exit) else: uniq_times, n_events, n_at_risk = _compute_counts_truncated(event, time_enter, time_exit) values = 1 - n_events / n_at_risk if time_min is not None: mask = uniq_times >= time_min uniq_times = numpy.compress(mask, uniq_times) values = numpy.compress(mask, values) y = numpy.cumprod(values) return uniq_times, y
[ "def", "kaplan_meier_estimator", "(", "event", ",", "time_exit", ",", "time_enter", "=", "None", ",", "time_min", "=", "None", ")", ":", "event", ",", "time_enter", ",", "time_exit", "=", "check_y_survival", "(", "event", ",", "time_enter", ",", "time_exit", ...
Kaplan-Meier estimator of survival function. Parameters ---------- event : array-like, shape = (n_samples,) Contains binary event indicators. time_exit : array-like, shape = (n_samples,) Contains event/censoring times. time_enter : array-like, shape = (n_samples,), optional Contains time when each individual entered the study for left truncated survival data. time_min : float, optional Compute estimator conditional on survival at least up to the specified time. Returns ------- time : array, shape = (n_times,) Unique times. prob_survival : array, shape = (n_times,) Survival probability at each unique time point. If `time_enter` is provided, estimates are conditional probabilities. Examples -------- Creating a Kaplan-Meier curve: >>> x, y = kaplan_meier_estimator(event, time) >>> plt.step(x, y, where="post") >>> plt.ylim(0, 1) >>> plt.show() References ---------- .. [1] Kaplan, E. L. and Meier, P., "Nonparametric estimation from incomplete observations", Journal of The American Statistical Association, vol. 53, pp. 457-481, 1958.
[ "Kaplan", "-", "Meier", "estimator", "of", "survival", "function", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L170-L228
train
227,650
sebp/scikit-survival
sksurv/nonparametric.py
nelson_aalen_estimator
def nelson_aalen_estimator(event, time): """Nelson-Aalen estimator of cumulative hazard function. Parameters ---------- event : array-like, shape = (n_samples,) Contains binary event indicators. time : array-like, shape = (n_samples,) Contains event/censoring times. Returns ------- time : array, shape = (n_times,) Unique times. cum_hazard : array, shape = (n_times,) Cumulative hazard at each unique time point. References ---------- .. [1] Nelson, W., "Theory and applications of hazard plotting for censored failure data", Technometrics, vol. 14, pp. 945-965, 1972. .. [2] Aalen, O. O., "Nonparametric inference for a family of counting processes", Annals of Statistics, vol. 6, pp. 701–726, 1978. """ event, time = check_y_survival(event, time) check_consistent_length(event, time) uniq_times, n_events, n_at_risk = _compute_counts(event, time) y = numpy.cumsum(n_events / n_at_risk) return uniq_times, y
python
def nelson_aalen_estimator(event, time): """Nelson-Aalen estimator of cumulative hazard function. Parameters ---------- event : array-like, shape = (n_samples,) Contains binary event indicators. time : array-like, shape = (n_samples,) Contains event/censoring times. Returns ------- time : array, shape = (n_times,) Unique times. cum_hazard : array, shape = (n_times,) Cumulative hazard at each unique time point. References ---------- .. [1] Nelson, W., "Theory and applications of hazard plotting for censored failure data", Technometrics, vol. 14, pp. 945-965, 1972. .. [2] Aalen, O. O., "Nonparametric inference for a family of counting processes", Annals of Statistics, vol. 6, pp. 701–726, 1978. """ event, time = check_y_survival(event, time) check_consistent_length(event, time) uniq_times, n_events, n_at_risk = _compute_counts(event, time) y = numpy.cumsum(n_events / n_at_risk) return uniq_times, y
[ "def", "nelson_aalen_estimator", "(", "event", ",", "time", ")", ":", "event", ",", "time", "=", "check_y_survival", "(", "event", ",", "time", ")", "check_consistent_length", "(", "event", ",", "time", ")", "uniq_times", ",", "n_events", ",", "n_at_risk", "...
Nelson-Aalen estimator of cumulative hazard function. Parameters ---------- event : array-like, shape = (n_samples,) Contains binary event indicators. time : array-like, shape = (n_samples,) Contains event/censoring times. Returns ------- time : array, shape = (n_times,) Unique times. cum_hazard : array, shape = (n_times,) Cumulative hazard at each unique time point. References ---------- .. [1] Nelson, W., "Theory and applications of hazard plotting for censored failure data", Technometrics, vol. 14, pp. 945-965, 1972. .. [2] Aalen, O. O., "Nonparametric inference for a family of counting processes", Annals of Statistics, vol. 6, pp. 701–726, 1978.
[ "Nelson", "-", "Aalen", "estimator", "of", "cumulative", "hazard", "function", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L231-L264
train
227,651
sebp/scikit-survival
sksurv/nonparametric.py
ipc_weights
def ipc_weights(event, time): """Compute inverse probability of censoring weights Parameters ---------- event : array, shape = (n_samples,) Boolean event indicator. time : array, shape = (n_samples,) Time when a subject experienced an event or was censored. Returns ------- weights : array, shape = (n_samples,) inverse probability of censoring weights """ if event.all(): return numpy.ones(time.shape[0]) unique_time, p = kaplan_meier_estimator(~event, time) idx = numpy.searchsorted(unique_time, time[event]) Ghat = p[idx] assert (Ghat > 0).all() weights = numpy.zeros(time.shape[0]) weights[event] = 1.0 / Ghat return weights
python
def ipc_weights(event, time): """Compute inverse probability of censoring weights Parameters ---------- event : array, shape = (n_samples,) Boolean event indicator. time : array, shape = (n_samples,) Time when a subject experienced an event or was censored. Returns ------- weights : array, shape = (n_samples,) inverse probability of censoring weights """ if event.all(): return numpy.ones(time.shape[0]) unique_time, p = kaplan_meier_estimator(~event, time) idx = numpy.searchsorted(unique_time, time[event]) Ghat = p[idx] assert (Ghat > 0).all() weights = numpy.zeros(time.shape[0]) weights[event] = 1.0 / Ghat return weights
[ "def", "ipc_weights", "(", "event", ",", "time", ")", ":", "if", "event", ".", "all", "(", ")", ":", "return", "numpy", ".", "ones", "(", "time", ".", "shape", "[", "0", "]", ")", "unique_time", ",", "p", "=", "kaplan_meier_estimator", "(", "~", "e...
Compute inverse probability of censoring weights Parameters ---------- event : array, shape = (n_samples,) Boolean event indicator. time : array, shape = (n_samples,) Time when a subject experienced an event or was censored. Returns ------- weights : array, shape = (n_samples,) inverse probability of censoring weights
[ "Compute", "inverse", "probability", "of", "censoring", "weights" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L267-L296
train
227,652
sebp/scikit-survival
sksurv/nonparametric.py
SurvivalFunctionEstimator.fit
def fit(self, y): """Estimate survival distribution from training data. Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self """ event, time = check_y_survival(y, allow_all_censored=True) unique_time, prob = kaplan_meier_estimator(event, time) self.unique_time_ = numpy.concatenate(([-numpy.infty], unique_time)) self.prob_ = numpy.concatenate(([1.], prob)) return self
python
def fit(self, y): """Estimate survival distribution from training data. Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self """ event, time = check_y_survival(y, allow_all_censored=True) unique_time, prob = kaplan_meier_estimator(event, time) self.unique_time_ = numpy.concatenate(([-numpy.infty], unique_time)) self.prob_ = numpy.concatenate(([1.], prob)) return self
[ "def", "fit", "(", "self", ",", "y", ")", ":", "event", ",", "time", "=", "check_y_survival", "(", "y", ",", "allow_all_censored", "=", "True", ")", "unique_time", ",", "prob", "=", "kaplan_meier_estimator", "(", "event", ",", "time", ")", "self", ".", ...
Estimate survival distribution from training data. Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self
[ "Estimate", "survival", "distribution", "from", "training", "data", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L305-L325
train
227,653
sebp/scikit-survival
sksurv/nonparametric.py
SurvivalFunctionEstimator.predict_proba
def predict_proba(self, time): """Return probability of an event after given time point. :math:`\\hat{S}(t) = P(T > t)` Parameters ---------- time : array, shape = (n_samples,) Time to estimate probability at. Returns ------- prob : array, shape = (n_samples,) Probability of an event. """ check_is_fitted(self, "unique_time_") time = check_array(time, ensure_2d=False) # K-M is undefined if estimate at last time point is non-zero extends = time > self.unique_time_[-1] if self.prob_[-1] > 0 and extends.any(): raise ValueError("time must be smaller than largest " "observed time point: {}".format(self.unique_time_[-1])) # beyond last time point is zero probability Shat = numpy.empty(time.shape, dtype=float) Shat[extends] = 0.0 valid = ~extends time = time[valid] idx = numpy.searchsorted(self.unique_time_, time) # for non-exact matches, we need to shift the index to left eps = numpy.finfo(self.unique_time_.dtype).eps exact = numpy.absolute(self.unique_time_[idx] - time) < eps idx[~exact] -= 1 Shat[valid] = self.prob_[idx] return Shat
python
def predict_proba(self, time): """Return probability of an event after given time point. :math:`\\hat{S}(t) = P(T > t)` Parameters ---------- time : array, shape = (n_samples,) Time to estimate probability at. Returns ------- prob : array, shape = (n_samples,) Probability of an event. """ check_is_fitted(self, "unique_time_") time = check_array(time, ensure_2d=False) # K-M is undefined if estimate at last time point is non-zero extends = time > self.unique_time_[-1] if self.prob_[-1] > 0 and extends.any(): raise ValueError("time must be smaller than largest " "observed time point: {}".format(self.unique_time_[-1])) # beyond last time point is zero probability Shat = numpy.empty(time.shape, dtype=float) Shat[extends] = 0.0 valid = ~extends time = time[valid] idx = numpy.searchsorted(self.unique_time_, time) # for non-exact matches, we need to shift the index to left eps = numpy.finfo(self.unique_time_.dtype).eps exact = numpy.absolute(self.unique_time_[idx] - time) < eps idx[~exact] -= 1 Shat[valid] = self.prob_[idx] return Shat
[ "def", "predict_proba", "(", "self", ",", "time", ")", ":", "check_is_fitted", "(", "self", ",", "\"unique_time_\"", ")", "time", "=", "check_array", "(", "time", ",", "ensure_2d", "=", "False", ")", "# K-M is undefined if estimate at last time point is non-zero", "...
Return probability of an event after given time point. :math:`\\hat{S}(t) = P(T > t)` Parameters ---------- time : array, shape = (n_samples,) Time to estimate probability at. Returns ------- prob : array, shape = (n_samples,) Probability of an event.
[ "Return", "probability", "of", "an", "event", "after", "given", "time", "point", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L327-L364
train
227,654
sebp/scikit-survival
sksurv/nonparametric.py
CensoringDistributionEstimator.fit
def fit(self, y): """Estimate censoring distribution from training data. Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self """ event, time = check_y_survival(y) if event.all(): self.unique_time_ = numpy.unique(time) self.prob_ = numpy.ones(self.unique_time_.shape[0]) else: unique_time, prob = kaplan_meier_estimator(~event, time) self.unique_time_ = numpy.concatenate(([-numpy.infty], unique_time)) self.prob_ = numpy.concatenate(([1.], prob)) return self
python
def fit(self, y): """Estimate censoring distribution from training data. Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self """ event, time = check_y_survival(y) if event.all(): self.unique_time_ = numpy.unique(time) self.prob_ = numpy.ones(self.unique_time_.shape[0]) else: unique_time, prob = kaplan_meier_estimator(~event, time) self.unique_time_ = numpy.concatenate(([-numpy.infty], unique_time)) self.prob_ = numpy.concatenate(([1.], prob)) return self
[ "def", "fit", "(", "self", ",", "y", ")", ":", "event", ",", "time", "=", "check_y_survival", "(", "y", ")", "if", "event", ".", "all", "(", ")", ":", "self", ".", "unique_time_", "=", "numpy", ".", "unique", "(", "time", ")", "self", ".", "prob_...
Estimate censoring distribution from training data. Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self
[ "Estimate", "censoring", "distribution", "from", "training", "data", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L370-L393
train
227,655
sebp/scikit-survival
sksurv/nonparametric.py
CensoringDistributionEstimator.predict_ipcw
def predict_ipcw(self, y): """Return inverse probability of censoring weights at given time points. :math:`\\omega_i = \\delta_i / \\hat{G}(y_i)` Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- ipcw : array, shape = (n_samples,) Inverse probability of censoring weights. """ event, time = check_y_survival(y) Ghat = self.predict_proba(time[event]) if (Ghat == 0.0).any(): raise ValueError("censoring survival function is zero at one or more time points") weights = numpy.zeros(time.shape[0]) weights[event] = 1.0 / Ghat return weights
python
def predict_ipcw(self, y): """Return inverse probability of censoring weights at given time points. :math:`\\omega_i = \\delta_i / \\hat{G}(y_i)` Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- ipcw : array, shape = (n_samples,) Inverse probability of censoring weights. """ event, time = check_y_survival(y) Ghat = self.predict_proba(time[event]) if (Ghat == 0.0).any(): raise ValueError("censoring survival function is zero at one or more time points") weights = numpy.zeros(time.shape[0]) weights[event] = 1.0 / Ghat return weights
[ "def", "predict_ipcw", "(", "self", ",", "y", ")", ":", "event", ",", "time", "=", "check_y_survival", "(", "y", ")", "Ghat", "=", "self", ".", "predict_proba", "(", "time", "[", "event", "]", ")", "if", "(", "Ghat", "==", "0.0", ")", ".", "any", ...
Return inverse probability of censoring weights at given time points. :math:`\\omega_i = \\delta_i / \\hat{G}(y_i)` Parameters ---------- y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- ipcw : array, shape = (n_samples,) Inverse probability of censoring weights.
[ "Return", "inverse", "probability", "of", "censoring", "weights", "at", "given", "time", "points", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/nonparametric.py#L395-L421
train
227,656
sebp/scikit-survival
sksurv/metrics.py
concordance_index_censored
def concordance_index_censored(event_indicator, event_time, estimate, tied_tol=1e-8): """Concordance index for right-censored data The concordance index is defined as the proportion of all comparable pairs in which the predictions and outcomes are concordant. Samples are comparable if for at least one of them an event occurred. If the estimated risk is larger for the sample with a higher time of event/censoring, the predictions of that pair are said to be concordant. If an event occurred for one sample and the other is known to be event-free at least until the time of event of the first, the second sample is assumed to *outlive* the first. When predicted risks are identical for a pair, 0.5 rather than 1 is added to the count of concordant pairs. A pair is not comparable if an event occurred for both of them at the same time or an event occurred for one of them but the time of censoring is smaller than the time of event of the first one. Parameters ---------- event_indicator : array-like, shape = (n_samples,) Boolean array denotes whether an event occurred event_time : array-like, shape = (n_samples,) Array containing the time of an event or time of censoring estimate : array-like, shape = (n_samples,) Estimated risk of experiencing an event tied_tol : float, optional, default: 1e-8 The tolerance value for considering ties. If the absolute difference between risk scores is smaller or equal than `tied_tol`, risk scores are considered tied. Returns ------- cindex : float Concordance index concordant : int Number of concordant pairs discordant : int Number of discordant pairs tied_risk : int Number of pairs having tied estimated risks tied_time : int Number of comparable pairs sharing the same time References ---------- .. [1] Harrell, F.E., Califf, R.M., Pryor, D.B., Lee, K.L., Rosati, R.A, "Multivariable prognostic models: issues in developing models, evaluating assumptions and adequacy, and measuring and reducing errors", Statistics in Medicine, 15(4), 361-87, 1996. """ event_indicator, event_time, estimate = _check_inputs( event_indicator, event_time, estimate) w = numpy.ones_like(estimate) return _estimate_concordance_index(event_indicator, event_time, estimate, w, tied_tol)
python
def concordance_index_censored(event_indicator, event_time, estimate, tied_tol=1e-8): """Concordance index for right-censored data The concordance index is defined as the proportion of all comparable pairs in which the predictions and outcomes are concordant. Samples are comparable if for at least one of them an event occurred. If the estimated risk is larger for the sample with a higher time of event/censoring, the predictions of that pair are said to be concordant. If an event occurred for one sample and the other is known to be event-free at least until the time of event of the first, the second sample is assumed to *outlive* the first. When predicted risks are identical for a pair, 0.5 rather than 1 is added to the count of concordant pairs. A pair is not comparable if an event occurred for both of them at the same time or an event occurred for one of them but the time of censoring is smaller than the time of event of the first one. Parameters ---------- event_indicator : array-like, shape = (n_samples,) Boolean array denotes whether an event occurred event_time : array-like, shape = (n_samples,) Array containing the time of an event or time of censoring estimate : array-like, shape = (n_samples,) Estimated risk of experiencing an event tied_tol : float, optional, default: 1e-8 The tolerance value for considering ties. If the absolute difference between risk scores is smaller or equal than `tied_tol`, risk scores are considered tied. Returns ------- cindex : float Concordance index concordant : int Number of concordant pairs discordant : int Number of discordant pairs tied_risk : int Number of pairs having tied estimated risks tied_time : int Number of comparable pairs sharing the same time References ---------- .. [1] Harrell, F.E., Califf, R.M., Pryor, D.B., Lee, K.L., Rosati, R.A, "Multivariable prognostic models: issues in developing models, evaluating assumptions and adequacy, and measuring and reducing errors", Statistics in Medicine, 15(4), 361-87, 1996. """ event_indicator, event_time, estimate = _check_inputs( event_indicator, event_time, estimate) w = numpy.ones_like(estimate) return _estimate_concordance_index(event_indicator, event_time, estimate, w, tied_tol)
[ "def", "concordance_index_censored", "(", "event_indicator", ",", "event_time", ",", "estimate", ",", "tied_tol", "=", "1e-8", ")", ":", "event_indicator", ",", "event_time", ",", "estimate", "=", "_check_inputs", "(", "event_indicator", ",", "event_time", ",", "e...
Concordance index for right-censored data The concordance index is defined as the proportion of all comparable pairs in which the predictions and outcomes are concordant. Samples are comparable if for at least one of them an event occurred. If the estimated risk is larger for the sample with a higher time of event/censoring, the predictions of that pair are said to be concordant. If an event occurred for one sample and the other is known to be event-free at least until the time of event of the first, the second sample is assumed to *outlive* the first. When predicted risks are identical for a pair, 0.5 rather than 1 is added to the count of concordant pairs. A pair is not comparable if an event occurred for both of them at the same time or an event occurred for one of them but the time of censoring is smaller than the time of event of the first one. Parameters ---------- event_indicator : array-like, shape = (n_samples,) Boolean array denotes whether an event occurred event_time : array-like, shape = (n_samples,) Array containing the time of an event or time of censoring estimate : array-like, shape = (n_samples,) Estimated risk of experiencing an event tied_tol : float, optional, default: 1e-8 The tolerance value for considering ties. If the absolute difference between risk scores is smaller or equal than `tied_tol`, risk scores are considered tied. Returns ------- cindex : float Concordance index concordant : int Number of concordant pairs discordant : int Number of discordant pairs tied_risk : int Number of pairs having tied estimated risks tied_time : int Number of comparable pairs sharing the same time References ---------- .. [1] Harrell, F.E., Califf, R.M., Pryor, D.B., Lee, K.L., Rosati, R.A, "Multivariable prognostic models: issues in developing models, evaluating assumptions and adequacy, and measuring and reducing errors", Statistics in Medicine, 15(4), 361-87, 1996.
[ "Concordance", "index", "for", "right", "-", "censored", "data" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/metrics.py#L111-L174
train
227,657
sebp/scikit-survival
sksurv/metrics.py
concordance_index_ipcw
def concordance_index_ipcw(survival_train, survival_test, estimate, tau=None, tied_tol=1e-8): """Concordance index for right-censored data based on inverse probability of censoring weights. This is an alternative to the estimator in :func:`concordance_index_censored` that does not depend on the distribution of censoring times in the test data. Therefore, the estimate is unbiased and consistent for a population concordance measure that is free of censoring. It is based on inverse probability of censoring weights, thus requires access to survival times from the training data to estimate the censoring distribution. Note that this requires that survival times `survival_test` lie within the range of survival times `survival_train`. This can be achieved by specifying the truncation time `tau`. The resulting `cindex` tells how well the given prediction model works in predicting events that occur in the time range from 0 to `tau`. The estimator uses the Kaplan-Meier estimator to estimate the censoring survivor function. Therefore, it is restricted to situations where the random censoring assumption holds and censoring is independent of the features. Parameters ---------- survival_train : structured array, shape = (n_train_samples,) Survival times for training data to estimate the censoring distribution from. A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. survival_test : structured array, shape = (n_samples,) Survival times of test data. A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. estimate : array-like, shape = (n_samples,) Estimated risk of experiencing an event of test data. tau : float, optional Truncation time. The survival function for the underlying censoring time distribution :math:`D` needs to be positive at `tau`, i.e., `tau` should be chosen such that the probability of being censored after time `tau` is non-zero: :math:`P(D > \\tau) > 0`. If `None`, no truncation is performed. tied_tol : float, optional, default: 1e-8 The tolerance value for considering ties. If the absolute difference between risk scores is smaller or equal than `tied_tol`, risk scores are considered tied. Returns ------- cindex : float Concordance index concordant : int Number of concordant pairs discordant : int Number of discordant pairs tied_risk : int Number of pairs having tied estimated risks tied_time : int Number of comparable pairs sharing the same time References ---------- .. [1] Uno, H., Cai, T., Pencina, M. J., D’Agostino, R. B., & Wei, L. J. (2011). "On the C-statistics for evaluating overall adequacy of risk prediction procedures with censored survival data". Statistics in Medicine, 30(10), 1105–1117. """ test_event, test_time = check_y_survival(survival_test) if tau is not None: survival_test = survival_test[test_time < tau] estimate = check_array(estimate, ensure_2d=False) check_consistent_length(test_event, test_time, estimate) cens = CensoringDistributionEstimator() cens.fit(survival_train) ipcw = cens.predict_ipcw(survival_test) w = numpy.square(ipcw) return _estimate_concordance_index(test_event, test_time, estimate, w, tied_tol)
python
def concordance_index_ipcw(survival_train, survival_test, estimate, tau=None, tied_tol=1e-8): """Concordance index for right-censored data based on inverse probability of censoring weights. This is an alternative to the estimator in :func:`concordance_index_censored` that does not depend on the distribution of censoring times in the test data. Therefore, the estimate is unbiased and consistent for a population concordance measure that is free of censoring. It is based on inverse probability of censoring weights, thus requires access to survival times from the training data to estimate the censoring distribution. Note that this requires that survival times `survival_test` lie within the range of survival times `survival_train`. This can be achieved by specifying the truncation time `tau`. The resulting `cindex` tells how well the given prediction model works in predicting events that occur in the time range from 0 to `tau`. The estimator uses the Kaplan-Meier estimator to estimate the censoring survivor function. Therefore, it is restricted to situations where the random censoring assumption holds and censoring is independent of the features. Parameters ---------- survival_train : structured array, shape = (n_train_samples,) Survival times for training data to estimate the censoring distribution from. A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. survival_test : structured array, shape = (n_samples,) Survival times of test data. A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. estimate : array-like, shape = (n_samples,) Estimated risk of experiencing an event of test data. tau : float, optional Truncation time. The survival function for the underlying censoring time distribution :math:`D` needs to be positive at `tau`, i.e., `tau` should be chosen such that the probability of being censored after time `tau` is non-zero: :math:`P(D > \\tau) > 0`. If `None`, no truncation is performed. tied_tol : float, optional, default: 1e-8 The tolerance value for considering ties. If the absolute difference between risk scores is smaller or equal than `tied_tol`, risk scores are considered tied. Returns ------- cindex : float Concordance index concordant : int Number of concordant pairs discordant : int Number of discordant pairs tied_risk : int Number of pairs having tied estimated risks tied_time : int Number of comparable pairs sharing the same time References ---------- .. [1] Uno, H., Cai, T., Pencina, M. J., D’Agostino, R. B., & Wei, L. J. (2011). "On the C-statistics for evaluating overall adequacy of risk prediction procedures with censored survival data". Statistics in Medicine, 30(10), 1105–1117. """ test_event, test_time = check_y_survival(survival_test) if tau is not None: survival_test = survival_test[test_time < tau] estimate = check_array(estimate, ensure_2d=False) check_consistent_length(test_event, test_time, estimate) cens = CensoringDistributionEstimator() cens.fit(survival_train) ipcw = cens.predict_ipcw(survival_test) w = numpy.square(ipcw) return _estimate_concordance_index(test_event, test_time, estimate, w, tied_tol)
[ "def", "concordance_index_ipcw", "(", "survival_train", ",", "survival_test", ",", "estimate", ",", "tau", "=", "None", ",", "tied_tol", "=", "1e-8", ")", ":", "test_event", ",", "test_time", "=", "check_y_survival", "(", "survival_test", ")", "if", "tau", "is...
Concordance index for right-censored data based on inverse probability of censoring weights. This is an alternative to the estimator in :func:`concordance_index_censored` that does not depend on the distribution of censoring times in the test data. Therefore, the estimate is unbiased and consistent for a population concordance measure that is free of censoring. It is based on inverse probability of censoring weights, thus requires access to survival times from the training data to estimate the censoring distribution. Note that this requires that survival times `survival_test` lie within the range of survival times `survival_train`. This can be achieved by specifying the truncation time `tau`. The resulting `cindex` tells how well the given prediction model works in predicting events that occur in the time range from 0 to `tau`. The estimator uses the Kaplan-Meier estimator to estimate the censoring survivor function. Therefore, it is restricted to situations where the random censoring assumption holds and censoring is independent of the features. Parameters ---------- survival_train : structured array, shape = (n_train_samples,) Survival times for training data to estimate the censoring distribution from. A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. survival_test : structured array, shape = (n_samples,) Survival times of test data. A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. estimate : array-like, shape = (n_samples,) Estimated risk of experiencing an event of test data. tau : float, optional Truncation time. The survival function for the underlying censoring time distribution :math:`D` needs to be positive at `tau`, i.e., `tau` should be chosen such that the probability of being censored after time `tau` is non-zero: :math:`P(D > \\tau) > 0`. If `None`, no truncation is performed. tied_tol : float, optional, default: 1e-8 The tolerance value for considering ties. If the absolute difference between risk scores is smaller or equal than `tied_tol`, risk scores are considered tied. Returns ------- cindex : float Concordance index concordant : int Number of concordant pairs discordant : int Number of discordant pairs tied_risk : int Number of pairs having tied estimated risks tied_time : int Number of comparable pairs sharing the same time References ---------- .. [1] Uno, H., Cai, T., Pencina, M. J., D’Agostino, R. B., & Wei, L. J. (2011). "On the C-statistics for evaluating overall adequacy of risk prediction procedures with censored survival data". Statistics in Medicine, 30(10), 1105–1117.
[ "Concordance", "index", "for", "right", "-", "censored", "data", "based", "on", "inverse", "probability", "of", "censoring", "weights", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/metrics.py#L177-L266
train
227,658
sebp/scikit-survival
sksurv/kernels/clinical.py
_nominal_kernel
def _nominal_kernel(x, y, out): """Number of features that match exactly""" for i in range(x.shape[0]): for j in range(y.shape[0]): out[i, j] += (x[i, :] == y[j, :]).sum() return out
python
def _nominal_kernel(x, y, out): """Number of features that match exactly""" for i in range(x.shape[0]): for j in range(y.shape[0]): out[i, j] += (x[i, :] == y[j, :]).sum() return out
[ "def", "_nominal_kernel", "(", "x", ",", "y", ",", "out", ")", ":", "for", "i", "in", "range", "(", "x", ".", "shape", "[", "0", "]", ")", ":", "for", "j", "in", "range", "(", "y", ".", "shape", "[", "0", "]", ")", ":", "out", "[", "i", "...
Number of features that match exactly
[ "Number", "of", "features", "that", "match", "exactly" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/kernels/clinical.py#L26-L32
train
227,659
sebp/scikit-survival
sksurv/kernels/clinical.py
_get_continuous_and_ordinal_array
def _get_continuous_and_ordinal_array(x): """Convert array from continuous and ordered categorical columns""" nominal_columns = x.select_dtypes(include=['object', 'category']).columns ordinal_columns = pandas.Index([v for v in nominal_columns if x[v].cat.ordered]) continuous_columns = x.select_dtypes(include=[numpy.number]).columns x_num = x.loc[:, continuous_columns].astype(numpy.float64).values if len(ordinal_columns) > 0: x = _ordinal_as_numeric(x, ordinal_columns) nominal_columns = nominal_columns.difference(ordinal_columns) x_out = numpy.column_stack((x_num, x)) else: x_out = x_num return x_out, nominal_columns
python
def _get_continuous_and_ordinal_array(x): """Convert array from continuous and ordered categorical columns""" nominal_columns = x.select_dtypes(include=['object', 'category']).columns ordinal_columns = pandas.Index([v for v in nominal_columns if x[v].cat.ordered]) continuous_columns = x.select_dtypes(include=[numpy.number]).columns x_num = x.loc[:, continuous_columns].astype(numpy.float64).values if len(ordinal_columns) > 0: x = _ordinal_as_numeric(x, ordinal_columns) nominal_columns = nominal_columns.difference(ordinal_columns) x_out = numpy.column_stack((x_num, x)) else: x_out = x_num return x_out, nominal_columns
[ "def", "_get_continuous_and_ordinal_array", "(", "x", ")", ":", "nominal_columns", "=", "x", ".", "select_dtypes", "(", "include", "=", "[", "'object'", ",", "'category'", "]", ")", ".", "columns", "ordinal_columns", "=", "pandas", ".", "Index", "(", "[", "v...
Convert array from continuous and ordered categorical columns
[ "Convert", "array", "from", "continuous", "and", "ordered", "categorical", "columns" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/kernels/clinical.py#L35-L50
train
227,660
sebp/scikit-survival
sksurv/kernels/clinical.py
clinical_kernel
def clinical_kernel(x, y=None): """Computes clinical kernel The clinical kernel distinguishes between continuous ordinal,and nominal variables. Parameters ---------- x : pandas.DataFrame, shape = (n_samples_x, n_features) Training data y : pandas.DataFrame, shape = (n_samples_y, n_features) Testing data Returns ------- kernel : array, shape = (n_samples_x, n_samples_y) Kernel matrix. Values are normalized to lie within [0, 1]. References ---------- .. [1] Daemen, A., De Moor, B., "Development of a kernel function for clinical data". Annual International Conference of the IEEE Engineering in Medicine and Biology Society, 5913-7, 2009 """ if y is not None: if x.shape[1] != y.shape[1]: raise ValueError('x and y have different number of features') if not x.columns.equals(y.columns): raise ValueError('columns do not match') else: y = x mat = numpy.zeros((x.shape[0], y.shape[0]), dtype=float) x_numeric, nominal_columns = _get_continuous_and_ordinal_array(x) if id(x) != id(y): y_numeric, _ = _get_continuous_and_ordinal_array(y) else: y_numeric = x_numeric continuous_ordinal_kernel(x_numeric, y_numeric, mat) _nominal_kernel(x.loc[:, nominal_columns].values, y.loc[:, nominal_columns].values, mat) mat /= x.shape[1] return mat
python
def clinical_kernel(x, y=None): """Computes clinical kernel The clinical kernel distinguishes between continuous ordinal,and nominal variables. Parameters ---------- x : pandas.DataFrame, shape = (n_samples_x, n_features) Training data y : pandas.DataFrame, shape = (n_samples_y, n_features) Testing data Returns ------- kernel : array, shape = (n_samples_x, n_samples_y) Kernel matrix. Values are normalized to lie within [0, 1]. References ---------- .. [1] Daemen, A., De Moor, B., "Development of a kernel function for clinical data". Annual International Conference of the IEEE Engineering in Medicine and Biology Society, 5913-7, 2009 """ if y is not None: if x.shape[1] != y.shape[1]: raise ValueError('x and y have different number of features') if not x.columns.equals(y.columns): raise ValueError('columns do not match') else: y = x mat = numpy.zeros((x.shape[0], y.shape[0]), dtype=float) x_numeric, nominal_columns = _get_continuous_and_ordinal_array(x) if id(x) != id(y): y_numeric, _ = _get_continuous_and_ordinal_array(y) else: y_numeric = x_numeric continuous_ordinal_kernel(x_numeric, y_numeric, mat) _nominal_kernel(x.loc[:, nominal_columns].values, y.loc[:, nominal_columns].values, mat) mat /= x.shape[1] return mat
[ "def", "clinical_kernel", "(", "x", ",", "y", "=", "None", ")", ":", "if", "y", "is", "not", "None", ":", "if", "x", ".", "shape", "[", "1", "]", "!=", "y", ".", "shape", "[", "1", "]", ":", "raise", "ValueError", "(", "'x and y have different numb...
Computes clinical kernel The clinical kernel distinguishes between continuous ordinal,and nominal variables. Parameters ---------- x : pandas.DataFrame, shape = (n_samples_x, n_features) Training data y : pandas.DataFrame, shape = (n_samples_y, n_features) Testing data Returns ------- kernel : array, shape = (n_samples_x, n_samples_y) Kernel matrix. Values are normalized to lie within [0, 1]. References ---------- .. [1] Daemen, A., De Moor, B., "Development of a kernel function for clinical data". Annual International Conference of the IEEE Engineering in Medicine and Biology Society, 5913-7, 2009
[ "Computes", "clinical", "kernel" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/kernels/clinical.py#L61-L107
train
227,661
sebp/scikit-survival
sksurv/kernels/clinical.py
ClinicalKernelTransform._prepare_by_column_dtype
def _prepare_by_column_dtype(self, X): """Get distance functions for each column's dtype""" if not isinstance(X, pandas.DataFrame): raise TypeError('X must be a pandas DataFrame') numeric_columns = [] nominal_columns = [] numeric_ranges = [] fit_data = numpy.empty_like(X) for i, dt in enumerate(X.dtypes): col = X.iloc[:, i] if is_categorical_dtype(dt): if col.cat.ordered: numeric_ranges.append(col.cat.codes.max() - col.cat.codes.min()) numeric_columns.append(i) else: nominal_columns.append(i) col = col.cat.codes elif is_numeric_dtype(dt): numeric_ranges.append(col.max() - col.min()) numeric_columns.append(i) else: raise TypeError('unsupported dtype: %r' % dt) fit_data[:, i] = col.values self._numeric_columns = numpy.asarray(numeric_columns) self._nominal_columns = numpy.asarray(nominal_columns) self._numeric_ranges = numpy.asarray(numeric_ranges, dtype=float) self.X_fit_ = fit_data
python
def _prepare_by_column_dtype(self, X): """Get distance functions for each column's dtype""" if not isinstance(X, pandas.DataFrame): raise TypeError('X must be a pandas DataFrame') numeric_columns = [] nominal_columns = [] numeric_ranges = [] fit_data = numpy.empty_like(X) for i, dt in enumerate(X.dtypes): col = X.iloc[:, i] if is_categorical_dtype(dt): if col.cat.ordered: numeric_ranges.append(col.cat.codes.max() - col.cat.codes.min()) numeric_columns.append(i) else: nominal_columns.append(i) col = col.cat.codes elif is_numeric_dtype(dt): numeric_ranges.append(col.max() - col.min()) numeric_columns.append(i) else: raise TypeError('unsupported dtype: %r' % dt) fit_data[:, i] = col.values self._numeric_columns = numpy.asarray(numeric_columns) self._nominal_columns = numpy.asarray(nominal_columns) self._numeric_ranges = numpy.asarray(numeric_ranges, dtype=float) self.X_fit_ = fit_data
[ "def", "_prepare_by_column_dtype", "(", "self", ",", "X", ")", ":", "if", "not", "isinstance", "(", "X", ",", "pandas", ".", "DataFrame", ")", ":", "raise", "TypeError", "(", "'X must be a pandas DataFrame'", ")", "numeric_columns", "=", "[", "]", "nominal_col...
Get distance functions for each column's dtype
[ "Get", "distance", "functions", "for", "each", "column", "s", "dtype" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/kernels/clinical.py#L153-L185
train
227,662
sebp/scikit-survival
sksurv/kernels/clinical.py
ClinicalKernelTransform.fit
def fit(self, X, y=None, **kwargs): """Determine transformation parameters from data in X. Subsequent calls to `transform(Y)` compute the pairwise distance to `X`. Parameters of the clinical kernel are only updated if `fit_once` is `False`, otherwise you have to explicitly call `prepare()` once. Parameters ---------- X: pandas.DataFrame, shape = (n_samples, n_features) Data to estimate parameters from. y : None Argument is ignored (included for compatibility reasons). kwargs : dict Argument is ignored (included for compatibility reasons). Returns ------- self : object Returns the instance itself. """ if X.ndim != 2: raise ValueError("expected 2d array, but got %d" % X.ndim) if self.fit_once: self.X_fit_ = X else: self._prepare_by_column_dtype(X) return self
python
def fit(self, X, y=None, **kwargs): """Determine transformation parameters from data in X. Subsequent calls to `transform(Y)` compute the pairwise distance to `X`. Parameters of the clinical kernel are only updated if `fit_once` is `False`, otherwise you have to explicitly call `prepare()` once. Parameters ---------- X: pandas.DataFrame, shape = (n_samples, n_features) Data to estimate parameters from. y : None Argument is ignored (included for compatibility reasons). kwargs : dict Argument is ignored (included for compatibility reasons). Returns ------- self : object Returns the instance itself. """ if X.ndim != 2: raise ValueError("expected 2d array, but got %d" % X.ndim) if self.fit_once: self.X_fit_ = X else: self._prepare_by_column_dtype(X) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "X", ".", "ndim", "!=", "2", ":", "raise", "ValueError", "(", "\"expected 2d array, but got %d\"", "%", "X", ".", "ndim", ")", "if", "self", ".", ...
Determine transformation parameters from data in X. Subsequent calls to `transform(Y)` compute the pairwise distance to `X`. Parameters of the clinical kernel are only updated if `fit_once` is `False`, otherwise you have to explicitly call `prepare()` once. Parameters ---------- X: pandas.DataFrame, shape = (n_samples, n_features) Data to estimate parameters from. y : None Argument is ignored (included for compatibility reasons). kwargs : dict Argument is ignored (included for compatibility reasons). Returns ------- self : object Returns the instance itself.
[ "Determine", "transformation", "parameters", "from", "data", "in", "X", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/kernels/clinical.py#L187-L220
train
227,663
sebp/scikit-survival
sksurv/kernels/clinical.py
ClinicalKernelTransform.transform
def transform(self, Y): r"""Compute all pairwise distances between `self.X_fit_` and `Y`. Parameters ---------- y : array-like, shape = (n_samples_y, n_features) Returns ------- kernel : ndarray, shape = (n_samples_y, n_samples_X_fit\_) Kernel matrix. Values are normalized to lie within [0, 1]. """ check_is_fitted(self, 'X_fit_') n_samples_x, n_features = self.X_fit_.shape Y = numpy.asarray(Y) if Y.shape[1] != n_features: raise ValueError('expected array with %d features, but got %d' % (n_features, Y.shape[1])) n_samples_y = Y.shape[0] mat = numpy.zeros((n_samples_y, n_samples_x), dtype=float) continuous_ordinal_kernel_with_ranges(Y[:, self._numeric_columns].astype(numpy.float64), self.X_fit_[:, self._numeric_columns].astype(numpy.float64), self._numeric_ranges, mat) if len(self._nominal_columns) > 0: _nominal_kernel(Y[:, self._nominal_columns], self.X_fit_[:, self._nominal_columns], mat) mat /= n_features return mat
python
def transform(self, Y): r"""Compute all pairwise distances between `self.X_fit_` and `Y`. Parameters ---------- y : array-like, shape = (n_samples_y, n_features) Returns ------- kernel : ndarray, shape = (n_samples_y, n_samples_X_fit\_) Kernel matrix. Values are normalized to lie within [0, 1]. """ check_is_fitted(self, 'X_fit_') n_samples_x, n_features = self.X_fit_.shape Y = numpy.asarray(Y) if Y.shape[1] != n_features: raise ValueError('expected array with %d features, but got %d' % (n_features, Y.shape[1])) n_samples_y = Y.shape[0] mat = numpy.zeros((n_samples_y, n_samples_x), dtype=float) continuous_ordinal_kernel_with_ranges(Y[:, self._numeric_columns].astype(numpy.float64), self.X_fit_[:, self._numeric_columns].astype(numpy.float64), self._numeric_ranges, mat) if len(self._nominal_columns) > 0: _nominal_kernel(Y[:, self._nominal_columns], self.X_fit_[:, self._nominal_columns], mat) mat /= n_features return mat
[ "def", "transform", "(", "self", ",", "Y", ")", ":", "check_is_fitted", "(", "self", ",", "'X_fit_'", ")", "n_samples_x", ",", "n_features", "=", "self", ".", "X_fit_", ".", "shape", "Y", "=", "numpy", ".", "asarray", "(", "Y", ")", "if", "Y", ".", ...
r"""Compute all pairwise distances between `self.X_fit_` and `Y`. Parameters ---------- y : array-like, shape = (n_samples_y, n_features) Returns ------- kernel : ndarray, shape = (n_samples_y, n_samples_X_fit\_) Kernel matrix. Values are normalized to lie within [0, 1].
[ "r", "Compute", "all", "pairwise", "distances", "between", "self", ".", "X_fit_", "and", "Y", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/kernels/clinical.py#L222-L257
train
227,664
sebp/scikit-survival
sksurv/ensemble/boosting.py
_fit_stage_componentwise
def _fit_stage_componentwise(X, residuals, sample_weight, **fit_params): """Fit component-wise weighted least squares model""" n_features = X.shape[1] base_learners = [] error = numpy.empty(n_features) for component in range(n_features): learner = ComponentwiseLeastSquares(component).fit(X, residuals, sample_weight) l_pred = learner.predict(X) error[component] = squared_norm(residuals - l_pred) base_learners.append(learner) # TODO: could use bottleneck.nanargmin for speed best_component = numpy.nanargmin(error) best_learner = base_learners[best_component] return best_learner
python
def _fit_stage_componentwise(X, residuals, sample_weight, **fit_params): """Fit component-wise weighted least squares model""" n_features = X.shape[1] base_learners = [] error = numpy.empty(n_features) for component in range(n_features): learner = ComponentwiseLeastSquares(component).fit(X, residuals, sample_weight) l_pred = learner.predict(X) error[component] = squared_norm(residuals - l_pred) base_learners.append(learner) # TODO: could use bottleneck.nanargmin for speed best_component = numpy.nanargmin(error) best_learner = base_learners[best_component] return best_learner
[ "def", "_fit_stage_componentwise", "(", "X", ",", "residuals", ",", "sample_weight", ",", "*", "*", "fit_params", ")", ":", "n_features", "=", "X", ".", "shape", "[", "1", "]", "base_learners", "=", "[", "]", "error", "=", "numpy", ".", "empty", "(", "...
Fit component-wise weighted least squares model
[ "Fit", "component", "-", "wise", "weighted", "least", "squares", "model" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/boosting.py#L72-L87
train
227,665
sebp/scikit-survival
sksurv/ensemble/boosting.py
ComponentwiseGradientBoostingSurvivalAnalysis.coef_
def coef_(self): """Return the aggregated coefficients. Returns ------- coef_ : ndarray, shape = (n_features + 1,) Coefficients of features. The first element denotes the intercept. """ coef = numpy.zeros(self.n_features_ + 1, dtype=float) for estimator in self.estimators_: coef[estimator.component] += self.learning_rate * estimator.coef_ return coef
python
def coef_(self): """Return the aggregated coefficients. Returns ------- coef_ : ndarray, shape = (n_features + 1,) Coefficients of features. The first element denotes the intercept. """ coef = numpy.zeros(self.n_features_ + 1, dtype=float) for estimator in self.estimators_: coef[estimator.component] += self.learning_rate * estimator.coef_ return coef
[ "def", "coef_", "(", "self", ")", ":", "coef", "=", "numpy", ".", "zeros", "(", "self", ".", "n_features_", "+", "1", ",", "dtype", "=", "float", ")", "for", "estimator", "in", "self", ".", "estimators_", ":", "coef", "[", "estimator", ".", "componen...
Return the aggregated coefficients. Returns ------- coef_ : ndarray, shape = (n_features + 1,) Coefficients of features. The first element denotes the intercept.
[ "Return", "the", "aggregated", "coefficients", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/boosting.py#L338-L351
train
227,666
sebp/scikit-survival
sksurv/ensemble/boosting.py
GradientBoostingSurvivalAnalysis._fit_stage
def _fit_stage(self, i, X, y, y_pred, sample_weight, sample_mask, random_state, scale, X_idx_sorted, X_csc=None, X_csr=None): """Fit another stage of ``n_classes_`` trees to the boosting model. """ assert sample_mask.dtype == numpy.bool loss = self.loss_ # whether to use dropout in next iteration do_dropout = self.dropout_rate > 0. and 0 < i < len(scale) - 1 for k in range(loss.K): residual = loss.negative_gradient(y, y_pred, k=k, sample_weight=sample_weight) # induce regression tree on residuals tree = DecisionTreeRegressor( criterion=self.criterion, splitter='best', max_depth=self.max_depth, min_samples_split=self.min_samples_split, min_samples_leaf=self.min_samples_leaf, min_weight_fraction_leaf=self.min_weight_fraction_leaf, min_impurity_split=self.min_impurity_split, min_impurity_decrease=self.min_impurity_decrease, max_features=self.max_features, max_leaf_nodes=self.max_leaf_nodes, random_state=random_state, presort=self.presort) if self.subsample < 1.0: # no inplace multiplication! sample_weight = sample_weight * sample_mask.astype(numpy.float64) X = X_csr if X_csr is not None else X tree.fit(X, residual, sample_weight=sample_weight, check_input=False, X_idx_sorted=X_idx_sorted) # add tree to ensemble self.estimators_[i, k] = tree # update tree leaves if do_dropout: # select base learners to be dropped for next iteration drop_model, n_dropped = _sample_binomial_plus_one(self.dropout_rate, i + 1, random_state) # adjust scaling factor of tree that is going to be trained in next iteration scale[i + 1] = 1. / (n_dropped + 1.) y_pred[:, k] = 0 for m in range(i + 1): if drop_model[m] == 1: # adjust scaling factor of dropped trees scale[m] *= n_dropped / (n_dropped + 1.) else: # pseudoresponse of next iteration (without contribution of dropped trees) y_pred[:, k] += self.learning_rate * scale[m] * self.estimators_[m, k].predict(X).ravel() else: # update tree leaves loss.update_terminal_regions(tree.tree_, X, y, residual, y_pred, sample_weight, sample_mask, self.learning_rate, k=k) return y_pred
python
def _fit_stage(self, i, X, y, y_pred, sample_weight, sample_mask, random_state, scale, X_idx_sorted, X_csc=None, X_csr=None): """Fit another stage of ``n_classes_`` trees to the boosting model. """ assert sample_mask.dtype == numpy.bool loss = self.loss_ # whether to use dropout in next iteration do_dropout = self.dropout_rate > 0. and 0 < i < len(scale) - 1 for k in range(loss.K): residual = loss.negative_gradient(y, y_pred, k=k, sample_weight=sample_weight) # induce regression tree on residuals tree = DecisionTreeRegressor( criterion=self.criterion, splitter='best', max_depth=self.max_depth, min_samples_split=self.min_samples_split, min_samples_leaf=self.min_samples_leaf, min_weight_fraction_leaf=self.min_weight_fraction_leaf, min_impurity_split=self.min_impurity_split, min_impurity_decrease=self.min_impurity_decrease, max_features=self.max_features, max_leaf_nodes=self.max_leaf_nodes, random_state=random_state, presort=self.presort) if self.subsample < 1.0: # no inplace multiplication! sample_weight = sample_weight * sample_mask.astype(numpy.float64) X = X_csr if X_csr is not None else X tree.fit(X, residual, sample_weight=sample_weight, check_input=False, X_idx_sorted=X_idx_sorted) # add tree to ensemble self.estimators_[i, k] = tree # update tree leaves if do_dropout: # select base learners to be dropped for next iteration drop_model, n_dropped = _sample_binomial_plus_one(self.dropout_rate, i + 1, random_state) # adjust scaling factor of tree that is going to be trained in next iteration scale[i + 1] = 1. / (n_dropped + 1.) y_pred[:, k] = 0 for m in range(i + 1): if drop_model[m] == 1: # adjust scaling factor of dropped trees scale[m] *= n_dropped / (n_dropped + 1.) else: # pseudoresponse of next iteration (without contribution of dropped trees) y_pred[:, k] += self.learning_rate * scale[m] * self.estimators_[m, k].predict(X).ravel() else: # update tree leaves loss.update_terminal_regions(tree.tree_, X, y, residual, y_pred, sample_weight, sample_mask, self.learning_rate, k=k) return y_pred
[ "def", "_fit_stage", "(", "self", ",", "i", ",", "X", ",", "y", ",", "y_pred", ",", "sample_weight", ",", "sample_mask", ",", "random_state", ",", "scale", ",", "X_idx_sorted", ",", "X_csc", "=", "None", ",", "X_csr", "=", "None", ")", ":", "assert", ...
Fit another stage of ``n_classes_`` trees to the boosting model.
[ "Fit", "another", "stage", "of", "n_classes_", "trees", "to", "the", "boosting", "model", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/boosting.py#L609-L671
train
227,667
sebp/scikit-survival
sksurv/ensemble/boosting.py
GradientBoostingSurvivalAnalysis._fit_stages
def _fit_stages(self, X, y, y_pred, sample_weight, random_state, begin_at_stage=0, monitor=None, X_idx_sorted=None): """Iteratively fits the stages. For each stage it computes the progress (OOB, train score) and delegates to ``_fit_stage``. Returns the number of stages fit; might differ from ``n_estimators`` due to early stopping. """ n_samples = X.shape[0] do_oob = self.subsample < 1.0 sample_mask = numpy.ones((n_samples, ), dtype=numpy.bool) n_inbag = max(1, int(self.subsample * n_samples)) loss_ = self.loss_ if self.verbose: verbose_reporter = VerboseReporter(self.verbose) verbose_reporter.init(self, begin_at_stage) X_csc = csc_matrix(X) if issparse(X) else None X_csr = csr_matrix(X) if issparse(X) else None if self.dropout_rate > 0.: scale = numpy.ones(self.n_estimators, dtype=float) else: scale = None # perform boosting iterations i = begin_at_stage for i in range(begin_at_stage, self.n_estimators): # subsampling if do_oob: sample_mask = _random_sample_mask(n_samples, n_inbag, random_state) # OOB score before adding this stage y_oob_sample = y[~sample_mask] old_oob_score = loss_(y_oob_sample, y_pred[~sample_mask], sample_weight[~sample_mask]) # fit next stage of trees y_pred = self._fit_stage(i, X, y, y_pred, sample_weight, sample_mask, random_state, scale, X_idx_sorted, X_csc, X_csr) # track deviance (= loss) if do_oob: self.train_score_[i] = loss_(y[sample_mask], y_pred[sample_mask], sample_weight[sample_mask]) self.oob_improvement_[i] = (old_oob_score - loss_(y_oob_sample, y_pred[~sample_mask], sample_weight[~sample_mask])) else: # no need to fancy index w/ no subsampling self.train_score_[i] = loss_(y, y_pred, sample_weight) if self.verbose > 0: verbose_reporter.update(i, self) if monitor is not None: early_stopping = monitor(i, self, locals()) if early_stopping: break if self.dropout_rate > 0.: self.scale_ = scale return i + 1
python
def _fit_stages(self, X, y, y_pred, sample_weight, random_state, begin_at_stage=0, monitor=None, X_idx_sorted=None): """Iteratively fits the stages. For each stage it computes the progress (OOB, train score) and delegates to ``_fit_stage``. Returns the number of stages fit; might differ from ``n_estimators`` due to early stopping. """ n_samples = X.shape[0] do_oob = self.subsample < 1.0 sample_mask = numpy.ones((n_samples, ), dtype=numpy.bool) n_inbag = max(1, int(self.subsample * n_samples)) loss_ = self.loss_ if self.verbose: verbose_reporter = VerboseReporter(self.verbose) verbose_reporter.init(self, begin_at_stage) X_csc = csc_matrix(X) if issparse(X) else None X_csr = csr_matrix(X) if issparse(X) else None if self.dropout_rate > 0.: scale = numpy.ones(self.n_estimators, dtype=float) else: scale = None # perform boosting iterations i = begin_at_stage for i in range(begin_at_stage, self.n_estimators): # subsampling if do_oob: sample_mask = _random_sample_mask(n_samples, n_inbag, random_state) # OOB score before adding this stage y_oob_sample = y[~sample_mask] old_oob_score = loss_(y_oob_sample, y_pred[~sample_mask], sample_weight[~sample_mask]) # fit next stage of trees y_pred = self._fit_stage(i, X, y, y_pred, sample_weight, sample_mask, random_state, scale, X_idx_sorted, X_csc, X_csr) # track deviance (= loss) if do_oob: self.train_score_[i] = loss_(y[sample_mask], y_pred[sample_mask], sample_weight[sample_mask]) self.oob_improvement_[i] = (old_oob_score - loss_(y_oob_sample, y_pred[~sample_mask], sample_weight[~sample_mask])) else: # no need to fancy index w/ no subsampling self.train_score_[i] = loss_(y, y_pred, sample_weight) if self.verbose > 0: verbose_reporter.update(i, self) if monitor is not None: early_stopping = monitor(i, self, locals()) if early_stopping: break if self.dropout_rate > 0.: self.scale_ = scale return i + 1
[ "def", "_fit_stages", "(", "self", ",", "X", ",", "y", ",", "y_pred", ",", "sample_weight", ",", "random_state", ",", "begin_at_stage", "=", "0", ",", "monitor", "=", "None", ",", "X_idx_sorted", "=", "None", ")", ":", "n_samples", "=", "X", ".", "shap...
Iteratively fits the stages. For each stage it computes the progress (OOB, train score) and delegates to ``_fit_stage``. Returns the number of stages fit; might differ from ``n_estimators`` due to early stopping.
[ "Iteratively", "fits", "the", "stages", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/boosting.py#L673-L741
train
227,668
sebp/scikit-survival
sksurv/ensemble/boosting.py
GradientBoostingSurvivalAnalysis.fit
def fit(self, X, y, sample_weight=None, monitor=None): """Fit the gradient boosting model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. sample_weight : array-like, shape = (n_samples,), optional Weights given to each sample. If omitted, all samples have weight 1. monitor : callable, optional The monitor is called after each iteration with the current iteration, a reference to the estimator and the local variables of ``_fit_stages`` as keyword arguments ``callable(i, self, locals())``. If the callable returns ``True`` the fitting procedure is stopped. The monitor can be used for various things such as computing held-out estimates, early stopping, model introspect, and snapshoting. Returns ------- self : object Returns self. """ random_state = check_random_state(self.random_state) X, event, time = check_arrays_survival(X, y, accept_sparse=['csr', 'csc', 'coo'], dtype=DTYPE) n_samples, self.n_features_ = X.shape X = X.astype(DTYPE) if sample_weight is None: sample_weight = numpy.ones(n_samples, dtype=numpy.float32) else: sample_weight = column_or_1d(sample_weight, warn=True) check_consistent_length(X, sample_weight) self._check_params() self.loss_ = LOSS_FUNCTIONS[self.loss](1) if isinstance(self.loss_, (CensoredSquaredLoss, IPCWLeastSquaresError)): time = numpy.log(time) self._init_state() self.init_.fit(X, (event, time), sample_weight) y_pred = self.init_.predict(X) begin_at_stage = 0 if self.presort is True and issparse(X): raise ValueError( "Presorting is not supported for sparse matrices.") presort = self.presort # Allow presort to be 'auto', which means True if the dataset is dense, # otherwise it will be False. if presort == 'auto': presort = not issparse(X) X_idx_sorted = None if presort: X_idx_sorted = numpy.asfortranarray(numpy.argsort(X, axis=0), dtype=numpy.int32) # fit the boosting stages y = numpy.fromiter(zip(event, time), dtype=[('event', numpy.bool), ('time', numpy.float64)]) n_stages = self._fit_stages(X, y, y_pred, sample_weight, random_state, begin_at_stage, monitor, X_idx_sorted) # change shape of arrays after fit (early-stopping or additional tests) if n_stages != self.estimators_.shape[0]: self.estimators_ = self.estimators_[:n_stages] self.train_score_ = self.train_score_[:n_stages] if hasattr(self, 'oob_improvement_'): self.oob_improvement_ = self.oob_improvement_[:n_stages] self.n_estimators_ = n_stages return self
python
def fit(self, X, y, sample_weight=None, monitor=None): """Fit the gradient boosting model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. sample_weight : array-like, shape = (n_samples,), optional Weights given to each sample. If omitted, all samples have weight 1. monitor : callable, optional The monitor is called after each iteration with the current iteration, a reference to the estimator and the local variables of ``_fit_stages`` as keyword arguments ``callable(i, self, locals())``. If the callable returns ``True`` the fitting procedure is stopped. The monitor can be used for various things such as computing held-out estimates, early stopping, model introspect, and snapshoting. Returns ------- self : object Returns self. """ random_state = check_random_state(self.random_state) X, event, time = check_arrays_survival(X, y, accept_sparse=['csr', 'csc', 'coo'], dtype=DTYPE) n_samples, self.n_features_ = X.shape X = X.astype(DTYPE) if sample_weight is None: sample_weight = numpy.ones(n_samples, dtype=numpy.float32) else: sample_weight = column_or_1d(sample_weight, warn=True) check_consistent_length(X, sample_weight) self._check_params() self.loss_ = LOSS_FUNCTIONS[self.loss](1) if isinstance(self.loss_, (CensoredSquaredLoss, IPCWLeastSquaresError)): time = numpy.log(time) self._init_state() self.init_.fit(X, (event, time), sample_weight) y_pred = self.init_.predict(X) begin_at_stage = 0 if self.presort is True and issparse(X): raise ValueError( "Presorting is not supported for sparse matrices.") presort = self.presort # Allow presort to be 'auto', which means True if the dataset is dense, # otherwise it will be False. if presort == 'auto': presort = not issparse(X) X_idx_sorted = None if presort: X_idx_sorted = numpy.asfortranarray(numpy.argsort(X, axis=0), dtype=numpy.int32) # fit the boosting stages y = numpy.fromiter(zip(event, time), dtype=[('event', numpy.bool), ('time', numpy.float64)]) n_stages = self._fit_stages(X, y, y_pred, sample_weight, random_state, begin_at_stage, monitor, X_idx_sorted) # change shape of arrays after fit (early-stopping or additional tests) if n_stages != self.estimators_.shape[0]: self.estimators_ = self.estimators_[:n_stages] self.train_score_ = self.train_score_[:n_stages] if hasattr(self, 'oob_improvement_'): self.oob_improvement_ = self.oob_improvement_[:n_stages] self.n_estimators_ = n_stages return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "sample_weight", "=", "None", ",", "monitor", "=", "None", ")", ":", "random_state", "=", "check_random_state", "(", "self", ".", "random_state", ")", "X", ",", "event", ",", "time", "=", "check_array...
Fit the gradient boosting model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. sample_weight : array-like, shape = (n_samples,), optional Weights given to each sample. If omitted, all samples have weight 1. monitor : callable, optional The monitor is called after each iteration with the current iteration, a reference to the estimator and the local variables of ``_fit_stages`` as keyword arguments ``callable(i, self, locals())``. If the callable returns ``True`` the fitting procedure is stopped. The monitor can be used for various things such as computing held-out estimates, early stopping, model introspect, and snapshoting. Returns ------- self : object Returns self.
[ "Fit", "the", "gradient", "boosting", "model", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/boosting.py#L743-L823
train
227,669
sebp/scikit-survival
sksurv/ensemble/boosting.py
GradientBoostingSurvivalAnalysis.staged_predict
def staged_predict(self, X): """Predict hazard at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y : generator of array of shape = (n_samples,) The predicted value of the input samples. """ check_is_fitted(self, 'estimators_') # if dropout wasn't used during training, proceed as usual, # otherwise consider scaling factor of individual trees if not hasattr(self, "scale_"): for y in self._staged_decision_function(X): yield self._scale_prediction(y.ravel()) else: for y in self._dropout_staged_decision_function(X): yield self._scale_prediction(y.ravel())
python
def staged_predict(self, X): """Predict hazard at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y : generator of array of shape = (n_samples,) The predicted value of the input samples. """ check_is_fitted(self, 'estimators_') # if dropout wasn't used during training, proceed as usual, # otherwise consider scaling factor of individual trees if not hasattr(self, "scale_"): for y in self._staged_decision_function(X): yield self._scale_prediction(y.ravel()) else: for y in self._dropout_staged_decision_function(X): yield self._scale_prediction(y.ravel())
[ "def", "staged_predict", "(", "self", ",", "X", ")", ":", "check_is_fitted", "(", "self", ",", "'estimators_'", ")", "# if dropout wasn't used during training, proceed as usual,", "# otherwise consider scaling factor of individual trees", "if", "not", "hasattr", "(", "self", ...
Predict hazard at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y : generator of array of shape = (n_samples,) The predicted value of the input samples.
[ "Predict", "hazard", "at", "each", "stage", "for", "X", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/ensemble/boosting.py#L886-L911
train
227,670
sebp/scikit-survival
sksurv/svm/minlip.py
MinlipSurvivalAnalysis.fit
def fit(self, X, y): """Build a MINLIP survival model from training data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self """ X, event, time = check_arrays_survival(X, y) self._fit(X, event, time) return self
python
def fit(self, X, y): """Build a MINLIP survival model from training data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self """ X, event, time = check_arrays_survival(X, y) self._fit(X, event, time) return self
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "X", ",", "event", ",", "time", "=", "check_arrays_survival", "(", "X", ",", "y", ")", "self", ".", "_fit", "(", "X", ",", "event", ",", "time", ")", "return", "self" ]
Build a MINLIP survival model from training data. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the binary event indicator as first field, and time of event or time of censoring as second field. Returns ------- self
[ "Build", "a", "MINLIP", "survival", "model", "from", "training", "data", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/minlip.py#L227-L247
train
227,671
sebp/scikit-survival
sksurv/svm/minlip.py
MinlipSurvivalAnalysis.predict
def predict(self, X): """Predict risk score of experiencing an event. Higher scores indicate shorter survival (high risk), lower scores longer survival (low risk). Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y : ndarray, shape = (n_samples,) Predicted risk. """ K = self._get_kernel(X, self.X_fit_) pred = -numpy.dot(self.coef_, K.T) return pred.ravel()
python
def predict(self, X): """Predict risk score of experiencing an event. Higher scores indicate shorter survival (high risk), lower scores longer survival (low risk). Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y : ndarray, shape = (n_samples,) Predicted risk. """ K = self._get_kernel(X, self.X_fit_) pred = -numpy.dot(self.coef_, K.T) return pred.ravel()
[ "def", "predict", "(", "self", ",", "X", ")", ":", "K", "=", "self", ".", "_get_kernel", "(", "X", ",", "self", ".", "X_fit_", ")", "pred", "=", "-", "numpy", ".", "dot", "(", "self", ".", "coef_", ",", "K", ".", "T", ")", "return", "pred", "...
Predict risk score of experiencing an event. Higher scores indicate shorter survival (high risk), lower scores longer survival (low risk). Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y : ndarray, shape = (n_samples,) Predicted risk.
[ "Predict", "risk", "score", "of", "experiencing", "an", "event", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/svm/minlip.py#L249-L267
train
227,672
sebp/scikit-survival
sksurv/datasets/base.py
get_x_y
def get_x_y(data_frame, attr_labels, pos_label=None, survival=True): """Split data frame into features and labels. Parameters ---------- data_frame : pandas.DataFrame, shape = (n_samples, n_columns) A data frame. attr_labels : sequence of str or None A list of one or more columns that are considered the label. If `survival` is `True`, then attr_labels has two elements: 1) the name of the column denoting the event indicator, and 2) the name of the column denoting the survival time. If the sequence contains `None`, then labels are not retrieved and only a data frame with features is returned. pos_label : any, optional Which value of the event indicator column denotes that a patient experienced an event. This value is ignored if `survival` is `False`. survival : bool, optional, default: True Whether to return `y` that can be used for survival analysis. Returns ------- X : pandas.DataFrame, shape = (n_samples, n_columns - len(attr_labels)) Data frame containing features. y : None or pandas.DataFrame, shape = (n_samples, len(attr_labels)) Data frame containing columns with supervised information. If `survival` was `True`, then the column denoting the event indicator will be boolean and survival times will be float. If `attr_labels` contains `None`, y is set to `None`. """ if survival: if len(attr_labels) != 2: raise ValueError("expected sequence of length two for attr_labels, but got %d" % len(attr_labels)) if pos_label is None: raise ValueError("pos_label needs to be specified if survival=True") return _get_x_y_survival(data_frame, attr_labels[0], attr_labels[1], pos_label) return _get_x_y_other(data_frame, attr_labels)
python
def get_x_y(data_frame, attr_labels, pos_label=None, survival=True): """Split data frame into features and labels. Parameters ---------- data_frame : pandas.DataFrame, shape = (n_samples, n_columns) A data frame. attr_labels : sequence of str or None A list of one or more columns that are considered the label. If `survival` is `True`, then attr_labels has two elements: 1) the name of the column denoting the event indicator, and 2) the name of the column denoting the survival time. If the sequence contains `None`, then labels are not retrieved and only a data frame with features is returned. pos_label : any, optional Which value of the event indicator column denotes that a patient experienced an event. This value is ignored if `survival` is `False`. survival : bool, optional, default: True Whether to return `y` that can be used for survival analysis. Returns ------- X : pandas.DataFrame, shape = (n_samples, n_columns - len(attr_labels)) Data frame containing features. y : None or pandas.DataFrame, shape = (n_samples, len(attr_labels)) Data frame containing columns with supervised information. If `survival` was `True`, then the column denoting the event indicator will be boolean and survival times will be float. If `attr_labels` contains `None`, y is set to `None`. """ if survival: if len(attr_labels) != 2: raise ValueError("expected sequence of length two for attr_labels, but got %d" % len(attr_labels)) if pos_label is None: raise ValueError("pos_label needs to be specified if survival=True") return _get_x_y_survival(data_frame, attr_labels[0], attr_labels[1], pos_label) return _get_x_y_other(data_frame, attr_labels)
[ "def", "get_x_y", "(", "data_frame", ",", "attr_labels", ",", "pos_label", "=", "None", ",", "survival", "=", "True", ")", ":", "if", "survival", ":", "if", "len", "(", "attr_labels", ")", "!=", "2", ":", "raise", "ValueError", "(", "\"expected sequence of...
Split data frame into features and labels. Parameters ---------- data_frame : pandas.DataFrame, shape = (n_samples, n_columns) A data frame. attr_labels : sequence of str or None A list of one or more columns that are considered the label. If `survival` is `True`, then attr_labels has two elements: 1) the name of the column denoting the event indicator, and 2) the name of the column denoting the survival time. If the sequence contains `None`, then labels are not retrieved and only a data frame with features is returned. pos_label : any, optional Which value of the event indicator column denotes that a patient experienced an event. This value is ignored if `survival` is `False`. survival : bool, optional, default: True Whether to return `y` that can be used for survival analysis. Returns ------- X : pandas.DataFrame, shape = (n_samples, n_columns - len(attr_labels)) Data frame containing features. y : None or pandas.DataFrame, shape = (n_samples, len(attr_labels)) Data frame containing columns with supervised information. If `survival` was `True`, then the column denoting the event indicator will be boolean and survival times will be float. If `attr_labels` contains `None`, y is set to `None`.
[ "Split", "data", "frame", "into", "features", "and", "labels", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/datasets/base.py#L46-L88
train
227,673
sebp/scikit-survival
sksurv/datasets/base.py
load_arff_files_standardized
def load_arff_files_standardized(path_training, attr_labels, pos_label=None, path_testing=None, survival=True, standardize_numeric=True, to_numeric=True): """Load dataset in ARFF format. Parameters ---------- path_training : str Path to ARFF file containing data. attr_labels : sequence of str Names of attributes denoting dependent variables. If ``survival`` is set, it must be a sequence with two items: the name of the event indicator and the name of the survival/censoring time. pos_label : any type, optional Value corresponding to an event in survival analysis. Only considered if ``survival`` is ``True``. path_testing : str, optional Path to ARFF file containing hold-out data. Only columns that are available in both training and testing are considered (excluding dependent variables). If ``standardize_numeric`` is set, data is normalized by considering both training and testing data. survival : bool, optional, default: True Whether the dependent variables denote event indicator and survival/censoring time. standardize_numeric : bool, optional, default: True Whether to standardize data to zero mean and unit variance. See :func:`sksurv.column.standardize`. to_numeric : boo, optional, default: True Whether to convert categorical variables to numeric values. See :func:`sksurv.column.categorical_to_numeric`. Returns ------- x_train : pandas.DataFrame, shape = (n_train, n_features) Training data. y_train : pandas.DataFrame, shape = (n_train, n_labels) Dependent variables of training data. x_test : None or pandas.DataFrame, shape = (n_train, n_features) Testing data if `path_testing` was provided. y_test : None or pandas.DataFrame, shape = (n_train, n_labels) Dependent variables of testing data if `path_testing` was provided. """ dataset = loadarff(path_training) if "index" in dataset.columns: dataset.index = dataset["index"].astype(object) dataset.drop("index", axis=1, inplace=True) x_train, y_train = get_x_y(dataset, attr_labels, pos_label, survival) if path_testing is not None: x_test, y_test = _load_arff_testing(path_testing, attr_labels, pos_label, survival) if len(x_train.columns.symmetric_difference(x_test.columns)) > 0: warnings.warn("Restricting columns to intersection between training and testing data", stacklevel=2) cols = x_train.columns.intersection(x_test.columns) if len(cols) == 0: raise ValueError("columns of training and test data do not intersect") x_train = x_train.loc[:, cols] x_test = x_test.loc[:, cols] x = safe_concat((x_train, x_test), axis=0) if standardize_numeric: x = standardize(x) if to_numeric: x = categorical_to_numeric(x) n_train = x_train.shape[0] x_train = x.iloc[:n_train, :] x_test = x.iloc[n_train:, :] else: if standardize_numeric: x_train = standardize(x_train) if to_numeric: x_train = categorical_to_numeric(x_train) x_test = None y_test = None return x_train, y_train, x_test, y_test
python
def load_arff_files_standardized(path_training, attr_labels, pos_label=None, path_testing=None, survival=True, standardize_numeric=True, to_numeric=True): """Load dataset in ARFF format. Parameters ---------- path_training : str Path to ARFF file containing data. attr_labels : sequence of str Names of attributes denoting dependent variables. If ``survival`` is set, it must be a sequence with two items: the name of the event indicator and the name of the survival/censoring time. pos_label : any type, optional Value corresponding to an event in survival analysis. Only considered if ``survival`` is ``True``. path_testing : str, optional Path to ARFF file containing hold-out data. Only columns that are available in both training and testing are considered (excluding dependent variables). If ``standardize_numeric`` is set, data is normalized by considering both training and testing data. survival : bool, optional, default: True Whether the dependent variables denote event indicator and survival/censoring time. standardize_numeric : bool, optional, default: True Whether to standardize data to zero mean and unit variance. See :func:`sksurv.column.standardize`. to_numeric : boo, optional, default: True Whether to convert categorical variables to numeric values. See :func:`sksurv.column.categorical_to_numeric`. Returns ------- x_train : pandas.DataFrame, shape = (n_train, n_features) Training data. y_train : pandas.DataFrame, shape = (n_train, n_labels) Dependent variables of training data. x_test : None or pandas.DataFrame, shape = (n_train, n_features) Testing data if `path_testing` was provided. y_test : None or pandas.DataFrame, shape = (n_train, n_labels) Dependent variables of testing data if `path_testing` was provided. """ dataset = loadarff(path_training) if "index" in dataset.columns: dataset.index = dataset["index"].astype(object) dataset.drop("index", axis=1, inplace=True) x_train, y_train = get_x_y(dataset, attr_labels, pos_label, survival) if path_testing is not None: x_test, y_test = _load_arff_testing(path_testing, attr_labels, pos_label, survival) if len(x_train.columns.symmetric_difference(x_test.columns)) > 0: warnings.warn("Restricting columns to intersection between training and testing data", stacklevel=2) cols = x_train.columns.intersection(x_test.columns) if len(cols) == 0: raise ValueError("columns of training and test data do not intersect") x_train = x_train.loc[:, cols] x_test = x_test.loc[:, cols] x = safe_concat((x_train, x_test), axis=0) if standardize_numeric: x = standardize(x) if to_numeric: x = categorical_to_numeric(x) n_train = x_train.shape[0] x_train = x.iloc[:n_train, :] x_test = x.iloc[n_train:, :] else: if standardize_numeric: x_train = standardize(x_train) if to_numeric: x_train = categorical_to_numeric(x_train) x_test = None y_test = None return x_train, y_train, x_test, y_test
[ "def", "load_arff_files_standardized", "(", "path_training", ",", "attr_labels", ",", "pos_label", "=", "None", ",", "path_testing", "=", "None", ",", "survival", "=", "True", ",", "standardize_numeric", "=", "True", ",", "to_numeric", "=", "True", ")", ":", "...
Load dataset in ARFF format. Parameters ---------- path_training : str Path to ARFF file containing data. attr_labels : sequence of str Names of attributes denoting dependent variables. If ``survival`` is set, it must be a sequence with two items: the name of the event indicator and the name of the survival/censoring time. pos_label : any type, optional Value corresponding to an event in survival analysis. Only considered if ``survival`` is ``True``. path_testing : str, optional Path to ARFF file containing hold-out data. Only columns that are available in both training and testing are considered (excluding dependent variables). If ``standardize_numeric`` is set, data is normalized by considering both training and testing data. survival : bool, optional, default: True Whether the dependent variables denote event indicator and survival/censoring time. standardize_numeric : bool, optional, default: True Whether to standardize data to zero mean and unit variance. See :func:`sksurv.column.standardize`. to_numeric : boo, optional, default: True Whether to convert categorical variables to numeric values. See :func:`sksurv.column.categorical_to_numeric`. Returns ------- x_train : pandas.DataFrame, shape = (n_train, n_features) Training data. y_train : pandas.DataFrame, shape = (n_train, n_labels) Dependent variables of training data. x_test : None or pandas.DataFrame, shape = (n_train, n_features) Testing data if `path_testing` was provided. y_test : None or pandas.DataFrame, shape = (n_train, n_labels) Dependent variables of testing data if `path_testing` was provided.
[ "Load", "dataset", "in", "ARFF", "format", "." ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/datasets/base.py#L91-L179
train
227,674
sebp/scikit-survival
sksurv/datasets/base.py
load_aids
def load_aids(endpoint="aids"): """Load and return the AIDS Clinical Trial dataset The dataset has 1,151 samples and 11 features. The dataset has 2 endpoints: 1. AIDS defining event, which occurred for 96 patients (8.3%) 2. Death, which occurred for 26 patients (2.3%) Parameters ---------- endpoint : aids|death The endpoint Returns ------- x : pandas.DataFrame The measurements for each patient. y : structured array with 2 fields *censor*: boolean indicating whether the endpoint has been reached or the event time is right censored. *time*: total length of follow-up If ``endpoint`` is death, the fields are named *censor_d* and *time_d*. References ---------- .. [1] http://www.umass.edu/statdata/statdata/data/ .. [2] Hosmer, D., Lemeshow, S., May, S.: "Applied Survival Analysis: Regression Modeling of Time to Event Data." John Wiley & Sons, Inc. (2008) """ labels_aids = ['censor', 'time'] labels_death = ['censor_d', 'time_d'] if endpoint == "aids": attr_labels = labels_aids drop_columns = labels_death elif endpoint == "death": attr_labels = labels_death drop_columns = labels_aids else: raise ValueError("endpoint must be 'aids' or 'death'") fn = resource_filename(__name__, 'data/actg320.arff') x, y = get_x_y(loadarff(fn), attr_labels=attr_labels, pos_label='1') x.drop(drop_columns, axis=1, inplace=True) return x, y
python
def load_aids(endpoint="aids"): """Load and return the AIDS Clinical Trial dataset The dataset has 1,151 samples and 11 features. The dataset has 2 endpoints: 1. AIDS defining event, which occurred for 96 patients (8.3%) 2. Death, which occurred for 26 patients (2.3%) Parameters ---------- endpoint : aids|death The endpoint Returns ------- x : pandas.DataFrame The measurements for each patient. y : structured array with 2 fields *censor*: boolean indicating whether the endpoint has been reached or the event time is right censored. *time*: total length of follow-up If ``endpoint`` is death, the fields are named *censor_d* and *time_d*. References ---------- .. [1] http://www.umass.edu/statdata/statdata/data/ .. [2] Hosmer, D., Lemeshow, S., May, S.: "Applied Survival Analysis: Regression Modeling of Time to Event Data." John Wiley & Sons, Inc. (2008) """ labels_aids = ['censor', 'time'] labels_death = ['censor_d', 'time_d'] if endpoint == "aids": attr_labels = labels_aids drop_columns = labels_death elif endpoint == "death": attr_labels = labels_death drop_columns = labels_aids else: raise ValueError("endpoint must be 'aids' or 'death'") fn = resource_filename(__name__, 'data/actg320.arff') x, y = get_x_y(loadarff(fn), attr_labels=attr_labels, pos_label='1') x.drop(drop_columns, axis=1, inplace=True) return x, y
[ "def", "load_aids", "(", "endpoint", "=", "\"aids\"", ")", ":", "labels_aids", "=", "[", "'censor'", ",", "'time'", "]", "labels_death", "=", "[", "'censor_d'", ",", "'time_d'", "]", "if", "endpoint", "==", "\"aids\"", ":", "attr_labels", "=", "labels_aids",...
Load and return the AIDS Clinical Trial dataset The dataset has 1,151 samples and 11 features. The dataset has 2 endpoints: 1. AIDS defining event, which occurred for 96 patients (8.3%) 2. Death, which occurred for 26 patients (2.3%) Parameters ---------- endpoint : aids|death The endpoint Returns ------- x : pandas.DataFrame The measurements for each patient. y : structured array with 2 fields *censor*: boolean indicating whether the endpoint has been reached or the event time is right censored. *time*: total length of follow-up If ``endpoint`` is death, the fields are named *censor_d* and *time_d*. References ---------- .. [1] http://www.umass.edu/statdata/statdata/data/ .. [2] Hosmer, D., Lemeshow, S., May, S.: "Applied Survival Analysis: Regression Modeling of Time to Event Data." John Wiley & Sons, Inc. (2008)
[ "Load", "and", "return", "the", "AIDS", "Clinical", "Trial", "dataset" ]
cfc99fd20454cdd6f4f20fe331b39f2191ccaabc
https://github.com/sebp/scikit-survival/blob/cfc99fd20454cdd6f4f20fe331b39f2191ccaabc/sksurv/datasets/base.py#L284-L333
train
227,675
seemethere/nba_py
nba_py/__init__.py
_api_scrape
def _api_scrape(json_inp, ndx): """ Internal method to streamline the getting of data from the json Args: json_inp (json): json input from our caller ndx (int): index where the data is located in the api Returns: If pandas is present: DataFrame (pandas.DataFrame): data set from ndx within the API's json else: A dictionary of both headers and values from the page """ try: headers = json_inp['resultSets'][ndx]['headers'] values = json_inp['resultSets'][ndx]['rowSet'] except KeyError: # This is so ugly but this is what you get when your data comes out # in not a standard format try: headers = json_inp['resultSet'][ndx]['headers'] values = json_inp['resultSet'][ndx]['rowSet'] except KeyError: # Added for results that only include one set (ex. LeagueLeaders) headers = json_inp['resultSet']['headers'] values = json_inp['resultSet']['rowSet'] if HAS_PANDAS: return DataFrame(values, columns=headers) else: # Taken from www.github.com/bradleyfay/py-goldsberry return [dict(zip(headers, value)) for value in values]
python
def _api_scrape(json_inp, ndx): """ Internal method to streamline the getting of data from the json Args: json_inp (json): json input from our caller ndx (int): index where the data is located in the api Returns: If pandas is present: DataFrame (pandas.DataFrame): data set from ndx within the API's json else: A dictionary of both headers and values from the page """ try: headers = json_inp['resultSets'][ndx]['headers'] values = json_inp['resultSets'][ndx]['rowSet'] except KeyError: # This is so ugly but this is what you get when your data comes out # in not a standard format try: headers = json_inp['resultSet'][ndx]['headers'] values = json_inp['resultSet'][ndx]['rowSet'] except KeyError: # Added for results that only include one set (ex. LeagueLeaders) headers = json_inp['resultSet']['headers'] values = json_inp['resultSet']['rowSet'] if HAS_PANDAS: return DataFrame(values, columns=headers) else: # Taken from www.github.com/bradleyfay/py-goldsberry return [dict(zip(headers, value)) for value in values]
[ "def", "_api_scrape", "(", "json_inp", ",", "ndx", ")", ":", "try", ":", "headers", "=", "json_inp", "[", "'resultSets'", "]", "[", "ndx", "]", "[", "'headers'", "]", "values", "=", "json_inp", "[", "'resultSets'", "]", "[", "ndx", "]", "[", "'rowSet'"...
Internal method to streamline the getting of data from the json Args: json_inp (json): json input from our caller ndx (int): index where the data is located in the api Returns: If pandas is present: DataFrame (pandas.DataFrame): data set from ndx within the API's json else: A dictionary of both headers and values from the page
[ "Internal", "method", "to", "streamline", "the", "getting", "of", "data", "from", "the", "json" ]
ffeaf4251d796ff9313367a752a45a0d7b16489e
https://github.com/seemethere/nba_py/blob/ffeaf4251d796ff9313367a752a45a0d7b16489e/nba_py/__init__.py#L34-L67
train
227,676
seemethere/nba_py
nba_py/player.py
get_player
def get_player(first_name, last_name=None, season=constants.CURRENT_SEASON, only_current=0, just_id=True): """ Calls our PlayerList class to get a full list of players and then returns just an id if specified or the full row of player information Args: :first_name: First name of the player :last_name: Last name of the player (this is None if the player only has first name [Nene]) :only_current: Only wants the current list of players :just_id: Only wants the id of the player Returns: Either the ID or full row of information of the player inputted Raises: :PlayerNotFoundException:: """ if last_name is None: name = first_name.lower() else: name = '{}, {}'.format(last_name, first_name).lower() pl = PlayerList(season=season, only_current=only_current).info() hdr = 'DISPLAY_LAST_COMMA_FIRST' if HAS_PANDAS: item = pl[pl.DISPLAY_LAST_COMMA_FIRST.str.lower() == name] else: item = next(plyr for plyr in pl if str(plyr[hdr]).lower() == name) if len(item) == 0: raise PlayerNotFoundException elif just_id: return item['PERSON_ID'] else: return item
python
def get_player(first_name, last_name=None, season=constants.CURRENT_SEASON, only_current=0, just_id=True): """ Calls our PlayerList class to get a full list of players and then returns just an id if specified or the full row of player information Args: :first_name: First name of the player :last_name: Last name of the player (this is None if the player only has first name [Nene]) :only_current: Only wants the current list of players :just_id: Only wants the id of the player Returns: Either the ID or full row of information of the player inputted Raises: :PlayerNotFoundException:: """ if last_name is None: name = first_name.lower() else: name = '{}, {}'.format(last_name, first_name).lower() pl = PlayerList(season=season, only_current=only_current).info() hdr = 'DISPLAY_LAST_COMMA_FIRST' if HAS_PANDAS: item = pl[pl.DISPLAY_LAST_COMMA_FIRST.str.lower() == name] else: item = next(plyr for plyr in pl if str(plyr[hdr]).lower() == name) if len(item) == 0: raise PlayerNotFoundException elif just_id: return item['PERSON_ID'] else: return item
[ "def", "get_player", "(", "first_name", ",", "last_name", "=", "None", ",", "season", "=", "constants", ".", "CURRENT_SEASON", ",", "only_current", "=", "0", ",", "just_id", "=", "True", ")", ":", "if", "last_name", "is", "None", ":", "name", "=", "first...
Calls our PlayerList class to get a full list of players and then returns just an id if specified or the full row of player information Args: :first_name: First name of the player :last_name: Last name of the player (this is None if the player only has first name [Nene]) :only_current: Only wants the current list of players :just_id: Only wants the id of the player Returns: Either the ID or full row of information of the player inputted Raises: :PlayerNotFoundException::
[ "Calls", "our", "PlayerList", "class", "to", "get", "a", "full", "list", "of", "players", "and", "then", "returns", "just", "an", "id", "if", "specified", "or", "the", "full", "row", "of", "player", "information" ]
ffeaf4251d796ff9313367a752a45a0d7b16489e
https://github.com/seemethere/nba_py/blob/ffeaf4251d796ff9313367a752a45a0d7b16489e/nba_py/player.py#L9-L46
train
227,677
ishikota/PyPokerEngine
pypokerengine/players.py
BasePokerPlayer.respond_to_ask
def respond_to_ask(self, message): """Called from Dealer when ask message received from RoundManager""" valid_actions, hole_card, round_state = self.__parse_ask_message(message) return self.declare_action(valid_actions, hole_card, round_state)
python
def respond_to_ask(self, message): """Called from Dealer when ask message received from RoundManager""" valid_actions, hole_card, round_state = self.__parse_ask_message(message) return self.declare_action(valid_actions, hole_card, round_state)
[ "def", "respond_to_ask", "(", "self", ",", "message", ")", ":", "valid_actions", ",", "hole_card", ",", "round_state", "=", "self", ".", "__parse_ask_message", "(", "message", ")", "return", "self", ".", "declare_action", "(", "valid_actions", ",", "hole_card", ...
Called from Dealer when ask message received from RoundManager
[ "Called", "from", "Dealer", "when", "ask", "message", "received", "from", "RoundManager" ]
a52a048a15da276005eca4acae96fb6eeb4dc034
https://github.com/ishikota/PyPokerEngine/blob/a52a048a15da276005eca4acae96fb6eeb4dc034/pypokerengine/players.py#L45-L48
train
227,678
ishikota/PyPokerEngine
pypokerengine/players.py
BasePokerPlayer.receive_notification
def receive_notification(self, message): """Called from Dealer when notification received from RoundManager""" msg_type = message["message_type"] if msg_type == "game_start_message": info = self.__parse_game_start_message(message) self.receive_game_start_message(info) elif msg_type == "round_start_message": round_count, hole, seats = self.__parse_round_start_message(message) self.receive_round_start_message(round_count, hole, seats) elif msg_type == "street_start_message": street, state = self.__parse_street_start_message(message) self.receive_street_start_message(street, state) elif msg_type == "game_update_message": new_action, round_state = self.__parse_game_update_message(message) self.receive_game_update_message(new_action, round_state) elif msg_type == "round_result_message": winners, hand_info, state = self.__parse_round_result_message(message) self.receive_round_result_message(winners, hand_info, state)
python
def receive_notification(self, message): """Called from Dealer when notification received from RoundManager""" msg_type = message["message_type"] if msg_type == "game_start_message": info = self.__parse_game_start_message(message) self.receive_game_start_message(info) elif msg_type == "round_start_message": round_count, hole, seats = self.__parse_round_start_message(message) self.receive_round_start_message(round_count, hole, seats) elif msg_type == "street_start_message": street, state = self.__parse_street_start_message(message) self.receive_street_start_message(street, state) elif msg_type == "game_update_message": new_action, round_state = self.__parse_game_update_message(message) self.receive_game_update_message(new_action, round_state) elif msg_type == "round_result_message": winners, hand_info, state = self.__parse_round_result_message(message) self.receive_round_result_message(winners, hand_info, state)
[ "def", "receive_notification", "(", "self", ",", "message", ")", ":", "msg_type", "=", "message", "[", "\"message_type\"", "]", "if", "msg_type", "==", "\"game_start_message\"", ":", "info", "=", "self", ".", "__parse_game_start_message", "(", "message", ")", "s...
Called from Dealer when notification received from RoundManager
[ "Called", "from", "Dealer", "when", "notification", "received", "from", "RoundManager" ]
a52a048a15da276005eca4acae96fb6eeb4dc034
https://github.com/ishikota/PyPokerEngine/blob/a52a048a15da276005eca4acae96fb6eeb4dc034/pypokerengine/players.py#L50-L72
train
227,679
alex-sherman/unsync
examples/mixing_methods.py
result_continuation
async def result_continuation(task): """A preliminary result processor we'll chain on to the original task This will get executed wherever the source task was executed, in this case one of the threads in the ThreadPoolExecutor""" await asyncio.sleep(0.1) num, res = task.result() return num, res * 2
python
async def result_continuation(task): """A preliminary result processor we'll chain on to the original task This will get executed wherever the source task was executed, in this case one of the threads in the ThreadPoolExecutor""" await asyncio.sleep(0.1) num, res = task.result() return num, res * 2
[ "async", "def", "result_continuation", "(", "task", ")", ":", "await", "asyncio", ".", "sleep", "(", "0.1", ")", "num", ",", "res", "=", "task", ".", "result", "(", ")", "return", "num", ",", "res", "*", "2" ]
A preliminary result processor we'll chain on to the original task This will get executed wherever the source task was executed, in this case one of the threads in the ThreadPoolExecutor
[ "A", "preliminary", "result", "processor", "we", "ll", "chain", "on", "to", "the", "original", "task", "This", "will", "get", "executed", "wherever", "the", "source", "task", "was", "executed", "in", "this", "case", "one", "of", "the", "threads", "in", "th...
a52a0b04980dcaf6dc2fd734aa9d7be9d8960bbe
https://github.com/alex-sherman/unsync/blob/a52a0b04980dcaf6dc2fd734aa9d7be9d8960bbe/examples/mixing_methods.py#L16-L22
train
227,680
alex-sherman/unsync
examples/mixing_methods.py
result_processor
async def result_processor(tasks): """An async result aggregator that combines all the results This gets executed in unsync.loop and unsync.thread""" output = {} for task in tasks: num, res = await task output[num] = res return output
python
async def result_processor(tasks): """An async result aggregator that combines all the results This gets executed in unsync.loop and unsync.thread""" output = {} for task in tasks: num, res = await task output[num] = res return output
[ "async", "def", "result_processor", "(", "tasks", ")", ":", "output", "=", "{", "}", "for", "task", "in", "tasks", ":", "num", ",", "res", "=", "await", "task", "output", "[", "num", "]", "=", "res", "return", "output" ]
An async result aggregator that combines all the results This gets executed in unsync.loop and unsync.thread
[ "An", "async", "result", "aggregator", "that", "combines", "all", "the", "results", "This", "gets", "executed", "in", "unsync", ".", "loop", "and", "unsync", ".", "thread" ]
a52a0b04980dcaf6dc2fd734aa9d7be9d8960bbe
https://github.com/alex-sherman/unsync/blob/a52a0b04980dcaf6dc2fd734aa9d7be9d8960bbe/examples/mixing_methods.py#L25-L32
train
227,681
fastavro/fastavro
fastavro/_read_py.py
read_union
def read_union(fo, writer_schema, reader_schema=None): """A union is encoded by first writing a long value indicating the zero-based position within the union of the schema of its value. The value is then encoded per the indicated schema within the union. """ # schema resolution index = read_long(fo) if reader_schema: # Handle case where the reader schema is just a single type (not union) if not isinstance(reader_schema, list): if match_types(writer_schema[index], reader_schema): return read_data(fo, writer_schema[index], reader_schema) else: for schema in reader_schema: if match_types(writer_schema[index], schema): return read_data(fo, writer_schema[index], schema) msg = 'schema mismatch: %s not found in %s' % \ (writer_schema, reader_schema) raise SchemaResolutionError(msg) else: return read_data(fo, writer_schema[index])
python
def read_union(fo, writer_schema, reader_schema=None): """A union is encoded by first writing a long value indicating the zero-based position within the union of the schema of its value. The value is then encoded per the indicated schema within the union. """ # schema resolution index = read_long(fo) if reader_schema: # Handle case where the reader schema is just a single type (not union) if not isinstance(reader_schema, list): if match_types(writer_schema[index], reader_schema): return read_data(fo, writer_schema[index], reader_schema) else: for schema in reader_schema: if match_types(writer_schema[index], schema): return read_data(fo, writer_schema[index], schema) msg = 'schema mismatch: %s not found in %s' % \ (writer_schema, reader_schema) raise SchemaResolutionError(msg) else: return read_data(fo, writer_schema[index])
[ "def", "read_union", "(", "fo", ",", "writer_schema", ",", "reader_schema", "=", "None", ")", ":", "# schema resolution", "index", "=", "read_long", "(", "fo", ")", "if", "reader_schema", ":", "# Handle case where the reader schema is just a single type (not union)", "i...
A union is encoded by first writing a long value indicating the zero-based position within the union of the schema of its value. The value is then encoded per the indicated schema within the union.
[ "A", "union", "is", "encoded", "by", "first", "writing", "a", "long", "value", "indicating", "the", "zero", "-", "based", "position", "within", "the", "union", "of", "the", "schema", "of", "its", "value", "." ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_read_py.py#L345-L366
train
227,682
fastavro/fastavro
fastavro/_read_py.py
read_data
def read_data(fo, writer_schema, reader_schema=None): """Read data from file object according to schema.""" record_type = extract_record_type(writer_schema) logical_type = extract_logical_type(writer_schema) if reader_schema and record_type in AVRO_TYPES: # If the schemas are the same, set the reader schema to None so that no # schema resolution is done for this call or future recursive calls if writer_schema == reader_schema: reader_schema = None else: match_schemas(writer_schema, reader_schema) reader_fn = READERS.get(record_type) if reader_fn: try: data = reader_fn(fo, writer_schema, reader_schema) except StructError: raise EOFError('cannot read %s from %s' % (record_type, fo)) if 'logicalType' in writer_schema: fn = LOGICAL_READERS.get(logical_type) if fn: return fn(data, writer_schema, reader_schema) if reader_schema is not None: return maybe_promote( data, record_type, extract_record_type(reader_schema) ) else: return data else: return read_data( fo, SCHEMA_DEFS[record_type], SCHEMA_DEFS.get(reader_schema) )
python
def read_data(fo, writer_schema, reader_schema=None): """Read data from file object according to schema.""" record_type = extract_record_type(writer_schema) logical_type = extract_logical_type(writer_schema) if reader_schema and record_type in AVRO_TYPES: # If the schemas are the same, set the reader schema to None so that no # schema resolution is done for this call or future recursive calls if writer_schema == reader_schema: reader_schema = None else: match_schemas(writer_schema, reader_schema) reader_fn = READERS.get(record_type) if reader_fn: try: data = reader_fn(fo, writer_schema, reader_schema) except StructError: raise EOFError('cannot read %s from %s' % (record_type, fo)) if 'logicalType' in writer_schema: fn = LOGICAL_READERS.get(logical_type) if fn: return fn(data, writer_schema, reader_schema) if reader_schema is not None: return maybe_promote( data, record_type, extract_record_type(reader_schema) ) else: return data else: return read_data( fo, SCHEMA_DEFS[record_type], SCHEMA_DEFS.get(reader_schema) )
[ "def", "read_data", "(", "fo", ",", "writer_schema", ",", "reader_schema", "=", "None", ")", ":", "record_type", "=", "extract_record_type", "(", "writer_schema", ")", "logical_type", "=", "extract_logical_type", "(", "writer_schema", ")", "if", "reader_schema", "...
Read data from file object according to schema.
[ "Read", "data", "from", "file", "object", "according", "to", "schema", "." ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_read_py.py#L477-L516
train
227,683
fastavro/fastavro
fastavro/_read_py.py
_iter_avro_records
def _iter_avro_records(fo, header, codec, writer_schema, reader_schema): """Return iterator over avro records.""" sync_marker = header['sync'] read_block = BLOCK_READERS.get(codec) if not read_block: raise ValueError('Unrecognized codec: %r' % codec) block_count = 0 while True: try: block_count = read_long(fo) except StopIteration: return block_fo = read_block(fo) for i in xrange(block_count): yield read_data(block_fo, writer_schema, reader_schema) skip_sync(fo, sync_marker)
python
def _iter_avro_records(fo, header, codec, writer_schema, reader_schema): """Return iterator over avro records.""" sync_marker = header['sync'] read_block = BLOCK_READERS.get(codec) if not read_block: raise ValueError('Unrecognized codec: %r' % codec) block_count = 0 while True: try: block_count = read_long(fo) except StopIteration: return block_fo = read_block(fo) for i in xrange(block_count): yield read_data(block_fo, writer_schema, reader_schema) skip_sync(fo, sync_marker)
[ "def", "_iter_avro_records", "(", "fo", ",", "header", ",", "codec", ",", "writer_schema", ",", "reader_schema", ")", ":", "sync_marker", "=", "header", "[", "'sync'", "]", "read_block", "=", "BLOCK_READERS", ".", "get", "(", "codec", ")", "if", "not", "re...
Return iterator over avro records.
[ "Return", "iterator", "over", "avro", "records", "." ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_read_py.py#L559-L579
train
227,684
fastavro/fastavro
fastavro/_read_py.py
_iter_avro_blocks
def _iter_avro_blocks(fo, header, codec, writer_schema, reader_schema): """Return iterator over avro blocks.""" sync_marker = header['sync'] read_block = BLOCK_READERS.get(codec) if not read_block: raise ValueError('Unrecognized codec: %r' % codec) while True: offset = fo.tell() try: num_block_records = read_long(fo) except StopIteration: return block_bytes = read_block(fo) skip_sync(fo, sync_marker) size = fo.tell() - offset yield Block( block_bytes, num_block_records, codec, reader_schema, writer_schema, offset, size )
python
def _iter_avro_blocks(fo, header, codec, writer_schema, reader_schema): """Return iterator over avro blocks.""" sync_marker = header['sync'] read_block = BLOCK_READERS.get(codec) if not read_block: raise ValueError('Unrecognized codec: %r' % codec) while True: offset = fo.tell() try: num_block_records = read_long(fo) except StopIteration: return block_bytes = read_block(fo) skip_sync(fo, sync_marker) size = fo.tell() - offset yield Block( block_bytes, num_block_records, codec, reader_schema, writer_schema, offset, size )
[ "def", "_iter_avro_blocks", "(", "fo", ",", "header", ",", "codec", ",", "writer_schema", ",", "reader_schema", ")", ":", "sync_marker", "=", "header", "[", "'sync'", "]", "read_block", "=", "BLOCK_READERS", ".", "get", "(", "codec", ")", "if", "not", "rea...
Return iterator over avro blocks.
[ "Return", "iterator", "over", "avro", "blocks", "." ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_read_py.py#L582-L606
train
227,685
fastavro/fastavro
fastavro/_write_py.py
prepare_timestamp_millis
def prepare_timestamp_millis(data, schema): """Converts datetime.datetime object to int timestamp with milliseconds """ if isinstance(data, datetime.datetime): if data.tzinfo is not None: delta = (data - epoch) return int(delta.total_seconds() * MLS_PER_SECOND) t = int(time.mktime(data.timetuple())) * MLS_PER_SECOND + int( data.microsecond / 1000) return t else: return data
python
def prepare_timestamp_millis(data, schema): """Converts datetime.datetime object to int timestamp with milliseconds """ if isinstance(data, datetime.datetime): if data.tzinfo is not None: delta = (data - epoch) return int(delta.total_seconds() * MLS_PER_SECOND) t = int(time.mktime(data.timetuple())) * MLS_PER_SECOND + int( data.microsecond / 1000) return t else: return data
[ "def", "prepare_timestamp_millis", "(", "data", ",", "schema", ")", ":", "if", "isinstance", "(", "data", ",", "datetime", ".", "datetime", ")", ":", "if", "data", ".", "tzinfo", "is", "not", "None", ":", "delta", "=", "(", "data", "-", "epoch", ")", ...
Converts datetime.datetime object to int timestamp with milliseconds
[ "Converts", "datetime", ".", "datetime", "object", "to", "int", "timestamp", "with", "milliseconds" ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L43-L54
train
227,686
fastavro/fastavro
fastavro/_write_py.py
prepare_timestamp_micros
def prepare_timestamp_micros(data, schema): """Converts datetime.datetime to int timestamp with microseconds""" if isinstance(data, datetime.datetime): if data.tzinfo is not None: delta = (data - epoch) return int(delta.total_seconds() * MCS_PER_SECOND) t = int(time.mktime(data.timetuple())) * MCS_PER_SECOND + \ data.microsecond return t else: return data
python
def prepare_timestamp_micros(data, schema): """Converts datetime.datetime to int timestamp with microseconds""" if isinstance(data, datetime.datetime): if data.tzinfo is not None: delta = (data - epoch) return int(delta.total_seconds() * MCS_PER_SECOND) t = int(time.mktime(data.timetuple())) * MCS_PER_SECOND + \ data.microsecond return t else: return data
[ "def", "prepare_timestamp_micros", "(", "data", ",", "schema", ")", ":", "if", "isinstance", "(", "data", ",", "datetime", ".", "datetime", ")", ":", "if", "data", ".", "tzinfo", "is", "not", "None", ":", "delta", "=", "(", "data", "-", "epoch", ")", ...
Converts datetime.datetime to int timestamp with microseconds
[ "Converts", "datetime", ".", "datetime", "to", "int", "timestamp", "with", "microseconds" ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L57-L67
train
227,687
fastavro/fastavro
fastavro/_write_py.py
prepare_date
def prepare_date(data, schema): """Converts datetime.date to int timestamp""" if isinstance(data, datetime.date): return data.toordinal() - DAYS_SHIFT else: return data
python
def prepare_date(data, schema): """Converts datetime.date to int timestamp""" if isinstance(data, datetime.date): return data.toordinal() - DAYS_SHIFT else: return data
[ "def", "prepare_date", "(", "data", ",", "schema", ")", ":", "if", "isinstance", "(", "data", ",", "datetime", ".", "date", ")", ":", "return", "data", ".", "toordinal", "(", ")", "-", "DAYS_SHIFT", "else", ":", "return", "data" ]
Converts datetime.date to int timestamp
[ "Converts", "datetime", ".", "date", "to", "int", "timestamp" ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L70-L75
train
227,688
fastavro/fastavro
fastavro/_write_py.py
prepare_uuid
def prepare_uuid(data, schema): """Converts uuid.UUID to string formatted UUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx """ if isinstance(data, uuid.UUID): return str(data) else: return data
python
def prepare_uuid(data, schema): """Converts uuid.UUID to string formatted UUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx """ if isinstance(data, uuid.UUID): return str(data) else: return data
[ "def", "prepare_uuid", "(", "data", ",", "schema", ")", ":", "if", "isinstance", "(", "data", ",", "uuid", ".", "UUID", ")", ":", "return", "str", "(", "data", ")", "else", ":", "return", "data" ]
Converts uuid.UUID to string formatted UUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
[ "Converts", "uuid", ".", "UUID", "to", "string", "formatted", "UUID", "xxxxxxxx", "-", "xxxx", "-", "xxxx", "-", "xxxx", "-", "xxxxxxxxxxxx" ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L78-L85
train
227,689
fastavro/fastavro
fastavro/_write_py.py
prepare_time_millis
def prepare_time_millis(data, schema): """Convert datetime.time to int timestamp with milliseconds""" if isinstance(data, datetime.time): return int( data.hour * MLS_PER_HOUR + data.minute * MLS_PER_MINUTE + data.second * MLS_PER_SECOND + int(data.microsecond / 1000)) else: return data
python
def prepare_time_millis(data, schema): """Convert datetime.time to int timestamp with milliseconds""" if isinstance(data, datetime.time): return int( data.hour * MLS_PER_HOUR + data.minute * MLS_PER_MINUTE + data.second * MLS_PER_SECOND + int(data.microsecond / 1000)) else: return data
[ "def", "prepare_time_millis", "(", "data", ",", "schema", ")", ":", "if", "isinstance", "(", "data", ",", "datetime", ".", "time", ")", ":", "return", "int", "(", "data", ".", "hour", "*", "MLS_PER_HOUR", "+", "data", ".", "minute", "*", "MLS_PER_MINUTE"...
Convert datetime.time to int timestamp with milliseconds
[ "Convert", "datetime", ".", "time", "to", "int", "timestamp", "with", "milliseconds" ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L88-L95
train
227,690
fastavro/fastavro
fastavro/_write_py.py
prepare_time_micros
def prepare_time_micros(data, schema): """Convert datetime.time to int timestamp with microseconds""" if isinstance(data, datetime.time): return long(data.hour * MCS_PER_HOUR + data.minute * MCS_PER_MINUTE + data.second * MCS_PER_SECOND + data.microsecond) else: return data
python
def prepare_time_micros(data, schema): """Convert datetime.time to int timestamp with microseconds""" if isinstance(data, datetime.time): return long(data.hour * MCS_PER_HOUR + data.minute * MCS_PER_MINUTE + data.second * MCS_PER_SECOND + data.microsecond) else: return data
[ "def", "prepare_time_micros", "(", "data", ",", "schema", ")", ":", "if", "isinstance", "(", "data", ",", "datetime", ".", "time", ")", ":", "return", "long", "(", "data", ".", "hour", "*", "MCS_PER_HOUR", "+", "data", ".", "minute", "*", "MCS_PER_MINUTE...
Convert datetime.time to int timestamp with microseconds
[ "Convert", "datetime", ".", "time", "to", "int", "timestamp", "with", "microseconds" ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L98-L104
train
227,691
fastavro/fastavro
fastavro/_write_py.py
prepare_bytes_decimal
def prepare_bytes_decimal(data, schema): """Convert decimal.Decimal to bytes""" if not isinstance(data, decimal.Decimal): return data scale = schema.get('scale', 0) # based on https://github.com/apache/avro/pull/82/ sign, digits, exp = data.as_tuple() if -exp > scale: raise ValueError( 'Scale provided in schema does not match the decimal') delta = exp + scale if delta > 0: digits = digits + (0,) * delta unscaled_datum = 0 for digit in digits: unscaled_datum = (unscaled_datum * 10) + digit bits_req = unscaled_datum.bit_length() + 1 if sign: unscaled_datum = (1 << bits_req) - unscaled_datum bytes_req = bits_req // 8 padding_bits = ~((1 << bits_req) - 1) if sign else 0 packed_bits = padding_bits | unscaled_datum bytes_req += 1 if (bytes_req << 3) < bits_req else 0 tmp = MemoryIO() for index in range(bytes_req - 1, -1, -1): bits_to_write = packed_bits >> (8 * index) tmp.write(mk_bits(bits_to_write & 0xff)) return tmp.getvalue()
python
def prepare_bytes_decimal(data, schema): """Convert decimal.Decimal to bytes""" if not isinstance(data, decimal.Decimal): return data scale = schema.get('scale', 0) # based on https://github.com/apache/avro/pull/82/ sign, digits, exp = data.as_tuple() if -exp > scale: raise ValueError( 'Scale provided in schema does not match the decimal') delta = exp + scale if delta > 0: digits = digits + (0,) * delta unscaled_datum = 0 for digit in digits: unscaled_datum = (unscaled_datum * 10) + digit bits_req = unscaled_datum.bit_length() + 1 if sign: unscaled_datum = (1 << bits_req) - unscaled_datum bytes_req = bits_req // 8 padding_bits = ~((1 << bits_req) - 1) if sign else 0 packed_bits = padding_bits | unscaled_datum bytes_req += 1 if (bytes_req << 3) < bits_req else 0 tmp = MemoryIO() for index in range(bytes_req - 1, -1, -1): bits_to_write = packed_bits >> (8 * index) tmp.write(mk_bits(bits_to_write & 0xff)) return tmp.getvalue()
[ "def", "prepare_bytes_decimal", "(", "data", ",", "schema", ")", ":", "if", "not", "isinstance", "(", "data", ",", "decimal", ".", "Decimal", ")", ":", "return", "data", "scale", "=", "schema", ".", "get", "(", "'scale'", ",", "0", ")", "# based on https...
Convert decimal.Decimal to bytes
[ "Convert", "decimal", ".", "Decimal", "to", "bytes" ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L107-L145
train
227,692
fastavro/fastavro
fastavro/_write_py.py
prepare_fixed_decimal
def prepare_fixed_decimal(data, schema): """Converts decimal.Decimal to fixed length bytes array""" if not isinstance(data, decimal.Decimal): return data scale = schema.get('scale', 0) size = schema['size'] # based on https://github.com/apache/avro/pull/82/ sign, digits, exp = data.as_tuple() if -exp > scale: raise ValueError( 'Scale provided in schema does not match the decimal') delta = exp + scale if delta > 0: digits = digits + (0,) * delta unscaled_datum = 0 for digit in digits: unscaled_datum = (unscaled_datum * 10) + digit bits_req = unscaled_datum.bit_length() + 1 size_in_bits = size * 8 offset_bits = size_in_bits - bits_req mask = 2 ** size_in_bits - 1 bit = 1 for i in range(bits_req): mask ^= bit bit <<= 1 if bits_req < 8: bytes_req = 1 else: bytes_req = bits_req // 8 if bits_req % 8 != 0: bytes_req += 1 tmp = MemoryIO() if sign: unscaled_datum = (1 << bits_req) - unscaled_datum unscaled_datum = mask | unscaled_datum for index in range(size - 1, -1, -1): bits_to_write = unscaled_datum >> (8 * index) tmp.write(mk_bits(bits_to_write & 0xff)) else: for i in range(offset_bits // 8): tmp.write(mk_bits(0)) for index in range(bytes_req - 1, -1, -1): bits_to_write = unscaled_datum >> (8 * index) tmp.write(mk_bits(bits_to_write & 0xff)) return tmp.getvalue()
python
def prepare_fixed_decimal(data, schema): """Converts decimal.Decimal to fixed length bytes array""" if not isinstance(data, decimal.Decimal): return data scale = schema.get('scale', 0) size = schema['size'] # based on https://github.com/apache/avro/pull/82/ sign, digits, exp = data.as_tuple() if -exp > scale: raise ValueError( 'Scale provided in schema does not match the decimal') delta = exp + scale if delta > 0: digits = digits + (0,) * delta unscaled_datum = 0 for digit in digits: unscaled_datum = (unscaled_datum * 10) + digit bits_req = unscaled_datum.bit_length() + 1 size_in_bits = size * 8 offset_bits = size_in_bits - bits_req mask = 2 ** size_in_bits - 1 bit = 1 for i in range(bits_req): mask ^= bit bit <<= 1 if bits_req < 8: bytes_req = 1 else: bytes_req = bits_req // 8 if bits_req % 8 != 0: bytes_req += 1 tmp = MemoryIO() if sign: unscaled_datum = (1 << bits_req) - unscaled_datum unscaled_datum = mask | unscaled_datum for index in range(size - 1, -1, -1): bits_to_write = unscaled_datum >> (8 * index) tmp.write(mk_bits(bits_to_write & 0xff)) else: for i in range(offset_bits // 8): tmp.write(mk_bits(0)) for index in range(bytes_req - 1, -1, -1): bits_to_write = unscaled_datum >> (8 * index) tmp.write(mk_bits(bits_to_write & 0xff)) return tmp.getvalue()
[ "def", "prepare_fixed_decimal", "(", "data", ",", "schema", ")", ":", "if", "not", "isinstance", "(", "data", ",", "decimal", ".", "Decimal", ")", ":", "return", "data", "scale", "=", "schema", ".", "get", "(", "'scale'", ",", "0", ")", "size", "=", ...
Converts decimal.Decimal to fixed length bytes array
[ "Converts", "decimal", ".", "Decimal", "to", "fixed", "length", "bytes", "array" ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L148-L203
train
227,693
fastavro/fastavro
fastavro/_write_py.py
write_crc32
def write_crc32(fo, bytes): """A 4-byte, big-endian CRC32 checksum""" data = crc32(bytes) & 0xFFFFFFFF fo.write(pack('>I', data))
python
def write_crc32(fo, bytes): """A 4-byte, big-endian CRC32 checksum""" data = crc32(bytes) & 0xFFFFFFFF fo.write(pack('>I', data))
[ "def", "write_crc32", "(", "fo", ",", "bytes", ")", ":", "data", "=", "crc32", "(", "bytes", ")", "&", "0xFFFFFFFF", "fo", ".", "write", "(", "pack", "(", "'>I'", ",", "data", ")", ")" ]
A 4-byte, big-endian CRC32 checksum
[ "A", "4", "-", "byte", "big", "-", "endian", "CRC32", "checksum" ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L245-L248
train
227,694
fastavro/fastavro
fastavro/_write_py.py
write_union
def write_union(fo, datum, schema): """A union is encoded by first writing a long value indicating the zero-based position within the union of the schema of its value. The value is then encoded per the indicated schema within the union.""" if isinstance(datum, tuple): (name, datum) = datum for index, candidate in enumerate(schema): if extract_record_type(candidate) == 'record': schema_name = candidate['name'] else: schema_name = candidate if name == schema_name: break else: msg = 'provided union type name %s not found in schema %s' \ % (name, schema) raise ValueError(msg) else: pytype = type(datum) best_match_index = -1 most_fields = -1 for index, candidate in enumerate(schema): if validate(datum, candidate, raise_errors=False): if extract_record_type(candidate) == 'record': fields = len(candidate['fields']) if fields > most_fields: best_match_index = index most_fields = fields else: best_match_index = index break if best_match_index < 0: msg = '%r (type %s) do not match %s' % (datum, pytype, schema) raise ValueError(msg) index = best_match_index # write data write_long(fo, index) write_data(fo, datum, schema[index])
python
def write_union(fo, datum, schema): """A union is encoded by first writing a long value indicating the zero-based position within the union of the schema of its value. The value is then encoded per the indicated schema within the union.""" if isinstance(datum, tuple): (name, datum) = datum for index, candidate in enumerate(schema): if extract_record_type(candidate) == 'record': schema_name = candidate['name'] else: schema_name = candidate if name == schema_name: break else: msg = 'provided union type name %s not found in schema %s' \ % (name, schema) raise ValueError(msg) else: pytype = type(datum) best_match_index = -1 most_fields = -1 for index, candidate in enumerate(schema): if validate(datum, candidate, raise_errors=False): if extract_record_type(candidate) == 'record': fields = len(candidate['fields']) if fields > most_fields: best_match_index = index most_fields = fields else: best_match_index = index break if best_match_index < 0: msg = '%r (type %s) do not match %s' % (datum, pytype, schema) raise ValueError(msg) index = best_match_index # write data write_long(fo, index) write_data(fo, datum, schema[index])
[ "def", "write_union", "(", "fo", ",", "datum", ",", "schema", ")", ":", "if", "isinstance", "(", "datum", ",", "tuple", ")", ":", "(", "name", ",", "datum", ")", "=", "datum", "for", "index", ",", "candidate", "in", "enumerate", "(", "schema", ")", ...
A union is encoded by first writing a long value indicating the zero-based position within the union of the schema of its value. The value is then encoded per the indicated schema within the union.
[ "A", "union", "is", "encoded", "by", "first", "writing", "a", "long", "value", "indicating", "the", "zero", "-", "based", "position", "within", "the", "union", "of", "the", "schema", "of", "its", "value", ".", "The", "value", "is", "then", "encoded", "pe...
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L302-L341
train
227,695
fastavro/fastavro
fastavro/_write_py.py
write_data
def write_data(fo, datum, schema): """Write a datum of data to output stream. Paramaters ---------- fo: file-like Output file datum: object Data to write schema: dict Schemda to use """ record_type = extract_record_type(schema) logical_type = extract_logical_type(schema) fn = WRITERS.get(record_type) if fn: if logical_type: prepare = LOGICAL_WRITERS.get(logical_type) if prepare: datum = prepare(datum, schema) return fn(fo, datum, schema) else: return write_data(fo, datum, SCHEMA_DEFS[record_type])
python
def write_data(fo, datum, schema): """Write a datum of data to output stream. Paramaters ---------- fo: file-like Output file datum: object Data to write schema: dict Schemda to use """ record_type = extract_record_type(schema) logical_type = extract_logical_type(schema) fn = WRITERS.get(record_type) if fn: if logical_type: prepare = LOGICAL_WRITERS.get(logical_type) if prepare: datum = prepare(datum, schema) return fn(fo, datum, schema) else: return write_data(fo, datum, SCHEMA_DEFS[record_type])
[ "def", "write_data", "(", "fo", ",", "datum", ",", "schema", ")", ":", "record_type", "=", "extract_record_type", "(", "schema", ")", "logical_type", "=", "extract_logical_type", "(", "schema", ")", "fn", "=", "WRITERS", ".", "get", "(", "record_type", ")", ...
Write a datum of data to output stream. Paramaters ---------- fo: file-like Output file datum: object Data to write schema: dict Schemda to use
[ "Write", "a", "datum", "of", "data", "to", "output", "stream", "." ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L390-L414
train
227,696
fastavro/fastavro
fastavro/_write_py.py
null_write_block
def null_write_block(fo, block_bytes): """Write block in "null" codec.""" write_long(fo, len(block_bytes)) fo.write(block_bytes)
python
def null_write_block(fo, block_bytes): """Write block in "null" codec.""" write_long(fo, len(block_bytes)) fo.write(block_bytes)
[ "def", "null_write_block", "(", "fo", ",", "block_bytes", ")", ":", "write_long", "(", "fo", ",", "len", "(", "block_bytes", ")", ")", "fo", ".", "write", "(", "block_bytes", ")" ]
Write block in "null" codec.
[ "Write", "block", "in", "null", "codec", "." ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L426-L429
train
227,697
fastavro/fastavro
fastavro/_write_py.py
deflate_write_block
def deflate_write_block(fo, block_bytes): """Write block in "deflate" codec.""" # The first two characters and last character are zlib # wrappers around deflate data. data = compress(block_bytes)[2:-1] write_long(fo, len(data)) fo.write(data)
python
def deflate_write_block(fo, block_bytes): """Write block in "deflate" codec.""" # The first two characters and last character are zlib # wrappers around deflate data. data = compress(block_bytes)[2:-1] write_long(fo, len(data)) fo.write(data)
[ "def", "deflate_write_block", "(", "fo", ",", "block_bytes", ")", ":", "# The first two characters and last character are zlib", "# wrappers around deflate data.", "data", "=", "compress", "(", "block_bytes", ")", "[", "2", ":", "-", "1", "]", "write_long", "(", "fo",...
Write block in "deflate" codec.
[ "Write", "block", "in", "deflate", "codec", "." ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L432-L439
train
227,698
fastavro/fastavro
fastavro/_write_py.py
schemaless_writer
def schemaless_writer(fo, schema, record): """Write a single record without the schema or header information Parameters ---------- fo: file-like Output file schema: dict Schema record: dict Record to write Example:: parsed_schema = fastavro.parse_schema(schema) with open('file.avro', 'rb') as fp: fastavro.schemaless_writer(fp, parsed_schema, record) Note: The ``schemaless_writer`` can only write a single record. """ schema = parse_schema(schema) write_data(fo, record, schema)
python
def schemaless_writer(fo, schema, record): """Write a single record without the schema or header information Parameters ---------- fo: file-like Output file schema: dict Schema record: dict Record to write Example:: parsed_schema = fastavro.parse_schema(schema) with open('file.avro', 'rb') as fp: fastavro.schemaless_writer(fp, parsed_schema, record) Note: The ``schemaless_writer`` can only write a single record. """ schema = parse_schema(schema) write_data(fo, record, schema)
[ "def", "schemaless_writer", "(", "fo", ",", "schema", ",", "record", ")", ":", "schema", "=", "parse_schema", "(", "schema", ")", "write_data", "(", "fo", ",", "record", ",", "schema", ")" ]
Write a single record without the schema or header information Parameters ---------- fo: file-like Output file schema: dict Schema record: dict Record to write Example:: parsed_schema = fastavro.parse_schema(schema) with open('file.avro', 'rb') as fp: fastavro.schemaless_writer(fp, parsed_schema, record) Note: The ``schemaless_writer`` can only write a single record.
[ "Write", "a", "single", "record", "without", "the", "schema", "or", "header", "information" ]
bafe826293e19eb93e77bbb0f6adfa059c7884b2
https://github.com/fastavro/fastavro/blob/bafe826293e19eb93e77bbb0f6adfa059c7884b2/fastavro/_write_py.py#L636-L658
train
227,699