Advanced Computing Platform for Theoretical Physics

Commit 94ff9f8b authored by Justin Bayer's avatar Justin Bayer
Browse files

Merge pull request #36 from msoelch/fix-onsignal-windows

added OnSignalWindows/Unix
parents 942159e0 3e650f6e
# http://stackoverflow.com/questions/15457786/ctrl-c-crashes-python-after-importing-scipy-stats
import sys
import os
import imp
import ctypes
if sys.platform == 'win32':
basepath = imp.find_module('numpy')[1]
ctypes.CDLL(os.path.join(basepath, 'core', 'libmmd.dll'))
ctypes.CDLL(os.path.join(basepath, 'core', 'libifcoremd.dll'))
from bfgs import Bfgs, Lbfgs, Sbfgs
from cg import ConjugateGradient, NonlinearConjugateGradient
from gd import GradientDescent
......
......@@ -28,6 +28,7 @@ realized by generator functions or objects with a ``__call__`` magic method.
import itertools
import signal
import sys
import time
......@@ -260,7 +261,7 @@ class Patience(object):
return i >= self.patience
class OnSignal(object):
class OnUnixSignal(object):
"""Stopping criterion that is sensitive to some signal."""
def __init__(self, sig=signal.SIGINT):
......@@ -297,6 +298,49 @@ class OnSignal(object):
self._register()
class OnWindowsSignal(object):
"""Stopping criterion that is sensitive to signals Ctrl-C or Ctrl-Break
on Windows."""
def __init__(self, sig=None):
"""Return a stopping criterion that stops upon a signal.
Previous handlers will be overwritten.
Parameters
----------
sig : signal, optional [default: [0,1]]
Signal upon which to stop.
Default encodes signal.SIGINT and signal.SIGBREAK.
"""
self.sig = [0, 1] if sig is None else sig
self.stopped = False
self._register()
def _register(self):
import win32api
win32api.SetConsoleCtrlHandler(self.handler, 1)
def handler(self, ctrl_type):
if ctrl_type in self.sig: # Ctrl-C and Ctrl-Break
self.stopped = True
return 1 # don't chain to the next handler
return 0 # chain to the next handler
def __call__(self, info):
res, self.stopped = self.stopped, False
return res
def __setstate__(self, dct):
self.__dict__.update(dct)
self._register()
OnSignal = OnWindowsSignal if sys.platform == 'win32' else OnUnixSignal
def never(info):
return False
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment