rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
Rot.__init__(this, axis = axis, angle = math.pi) class Refl(Transform): | Rot3.__init__(this, axis = axis, angle = math.pi) class Refl3(Transform3): | def __init__(this, axis): Rot.__init__(this, axis = axis, angle = math.pi) |
Transform.__init__(this, v) class RotInv(Transform): | Transform3.__init__(this, v) class RotInv3(Transform3): | def __init__(this, q = None, normal = None): Transform.__init__(this, v) |
Transform.__init__(this, qLeft, q) | Transform3.__init__(this, qLeft, q) | def __init__(this, q = None, axis = None, angle = None): try: qLeft = -q.conjugate() except AttributeError: # in case q is a Vec q = Quat(q) qLeft = -q.conjugate() Transform.__init__(this, qLeft, q) |
RotRefl = RotInv I = RotInv(Quat([1, 0, 0, 0])) E = Rot(Quat([1, 0, 0, 0])) | RotRefl = RotInv3 I = RotInv3(Quat([1, 0, 0, 0])) E = Rot3(Quat([1, 0, 0, 0])) | def __repr__(q): return '%s(%s, %s)' % (q.__class__.__name__, q.left, q.right) |
assert I.__repr__() == 'RotInv([-1.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0])' | def __repr__(q): return '%s(%s, %s)' % (q.__class__.__name__, q.left, q.right) | |
if len(wx.TextCtrl.GetValue(this)) <= 1: | if len(wx.TextCtrl.GetValue(this)) < 1: | def onChar(this, e): #print this.__class__, 'onChar' k = e.GetKeyCode() # ASCII is returned for ASCII values try: c = chr(k) except ValueError: c = 0 pass rkc = e.GetRawKeyCode() if c >= '0' and c <= '9': e.Skip() elif c in ['+', '-', '.']: # Handle selected text by replacing it by a '0', otherwise it may # prevent fro... |
assert v.__hoscCalled == True, 'if this exists it should be true' | assert v.__hospCalled == True, 'if this exists it should be true' | def higherOrderStabiliserProps(v): """Get possible sub orbit classes for higher order stabilisers |
v.__hosPropsCalled = True | v.__hospCalled = True | def higherOrderStabiliserProps(v): """Get possible sub orbit classes for higher order stabilisers |
assert v.__losPropsCalled == True, 'if this exists it should be true' | assert v.__lospCalled == True, 'if this exists it should be true' | def lowerOrderStabiliserProps(v): """Get possible sub orbit classes for alternative higher order stabilisers |
v.__losPropsCalled = True | v.__lospCalled = True | def lowerOrderStabiliserProps(v): """Get possible sub orbit classes for alternative higher order stabilisers |
obj = self.__class__(self.backend, self._username, copy.deepcopy(self._user, memo)) | obj = object.__new__(self.__class__) obj.backend = self.backend obj.ldap = self.ldap obj._user = copy.deepcopy(self._user, memo) | def __deepcopy__(self, memo): obj = self.__class__(self.backend, self._username, copy.deepcopy(self._user, memo)) |
actions[0]["description"]) | description) | def testSkinsMenuFindsSkins(self): st = getToolByName(self.folder, "portal_skins") skins = st.getSkinSelections() actions = self.menu.getMenuItems(self.folder, self.request) self.assertEqual(set(skins), set([a["title"] for a in actions])) self.assertEqual(u"Use '%s' skin for this folder" % actions[0]["title"], actions[... |
logger.info('NOT forcing login: %s is in page white list.', | logger.debug('NOT forcing login: %s is in page white list.', | def force_login(request, props): force_login_header = props.getProperty('force_login_header', None) if not force_login_header: return False # Note: to truly test what happens when forcing login via a header # on your local machine without any Apache setup, you should # comment out this condition: if not request.get_he... |
logger.info('NOT forcing login: suffix of %s is in white list.', | logger.debug('NOT forcing login: suffix of %s is in white list.', | def force_login(request, props): force_login_header = props.getProperty('force_login_header', None) if not force_login_header: return False # Note: to truly test what happens when forcing login via a header # on your local machine without any Apache setup, you should # comment out this condition: if not request.get_he... |
def anonymous(): return (getSecurityManager().getUser().getUserName() == 'Anonymous User') | def anonymous(request=None): if request is None: anon = (getSecurityManager().getUser().getUserName() == 'Anonymous User') elif request.cookies.get('__ac'): anon = False else: anon = True logger.debug("Anonymous? %s", anon) return anon | def anonymous(): return (getSecurityManager().getUser().getUserName() == 'Anonymous User') |
if anonymous(): | if anonymous(request): | def check_auth(request): if anonymous(): raise Unauthorized('Go away') |
return is_edit_url(request.getURL()) | val = is_edit_url(request.getURL()) logger.debug("Is edit url? %s", val) return val | def edit_url(request, props): ''' The default switch check based on a subdomain of cms, edit or manage''' from collective.editskinswitcher.utils import is_edit_url return is_edit_url(request.getURL()) |
def no_url(request, props): | def need_authentication(request, props): | def no_url(request, props): """This is for skin switching based on authentication only.""" return props.getProperty('need_authentication', False) |
return props.getProperty('need_authentication', False) | val = props.getProperty('need_authentication', False) logger.debug("Need authentication? %s", val) return val | def no_url(request, props): """This is for skin switching based on authentication only.""" return props.getProperty('need_authentication', False) |
'no URL based switching': no_url} | 'no URL based switching': need_authentication} | def no_url(request, props): """This is for skin switching based on authentication only.""" return props.getProperty('need_authentication', False) |
cssClass = "actionMenu" if not selected else "actionMenuSelected" | cssClass = selected and "actionMenuSelected" or "actionMenu" | def getMenuItems(self, context, request): """Return menu item entries in a TAL-friendly form.""" results = [] |
def really_switch_skin(object, request, skin_name): | def get_real_context(object): | def really_switch_skin(object, request, skin_name): # object might be a view, for instance a KSS view. Use the # context of that object then. try: changeSkin = object.changeSkin except AttributeError: changeSkin = object.context.changeSkin changeSkin(skin_name, request) |
changeSkin = object.changeSkin | getattr(object, 'changeSkin') | def really_switch_skin(object, request, skin_name): # object might be a view, for instance a KSS view. Use the # context of that object then. try: changeSkin = object.changeSkin except AttributeError: changeSkin = object.context.changeSkin changeSkin(skin_name, request) |
changeSkin = object.context.changeSkin changeSkin(skin_name, request) | return object.context return object | def really_switch_skin(object, request, skin_name): # object might be a view, for instance a KSS view. Use the # context of that object then. try: changeSkin = object.changeSkin except AttributeError: changeSkin = object.context.changeSkin changeSkin(skin_name, request) |
class TestSkinsMenu(ptc.PloneTestCase): | class TestSkinsMenu(base.BaseTestCase): | def testSkinsSubMenuNotIncludedWithoutPermission(self): # The skins menu is only available for someone that has the # 'Set default skin' permission in the folder. items = self.menu.getMenuItems(self.folder, self.request) skinsMenuItem = [ i for i in items if i["extra"]["id"] == "collective-editskinswitcher-menu-skins"]... |
class TestSelectSkinView(ptc.FunctionalTestCase): | class TestSelectSkinView(base.BaseFunctionalTestCase): | def testSelectedSkinHasProperCSSClass(self): st = getToolByName(self.folder, "portal_skins") skins = st.getSkinSelections() actions = self.menu.getMenuItems(self.folder, self.request) action = [a for a in actions if a["title"] == skins[0]][0] self.assertEqual("actionMenu", action["extra"]["class"]) set_selected_default... |
class TestSelectSkinFallbackForm(ptc.FunctionalTestCase): | class TestSelectSkinFallbackForm(base.BaseFunctionalTestCase): | def testSkinSwitchedOnRealTraversalEvent(self): # Create new skin based on Plone Default and make this the # default skin. new_default_skin(self.portal) response = self.publish( self.folder_path + '/getCurrentSkinName', basic=self.basic_auth) self.assertEqual("Monty Python Skin", response.getBody()) |
log.write("Read line '%s'" % line, LOG_DEBUG) | def read_headers(self, filename=""): if filename: try: file = open(filename, 'r') except IOError, e: log.write("Can't open file %s: %s" % (filename, e), LOG_ERR) sys.exit(1) else: log.write("No file name given. Reading from stdin.", LOG_DEBUG) file = sys.stdin | |
return "%s\n\n" % response | return "action=%s\n\n" % response | def perform_action(self): action = self.get_action() response = "" if action == 'TEST': log.write("Got action '%s', performing tests." % action, LOG_DEBUG) self._do_tests() self._handle_score() action = self.get_action() log.write("Rechecked action after tests, new action is '%s'" % action, LOG_DEBUG) else: log.write("... |
if isinstance(parent, QGroupBox): | try: child_title = parent.child_title except AttributeError: | def select_file(self): """Open a file selection dialog box""" fname = self.item.from_string(unicode(self.edit.text())) if isinstance(fname, list): fname = os.path.dirname(fname[0]) parent = self.parent_layout.parent _temp = sys.stdout sys.stdout = None if len(fname) == 0: fname = self.basedir _formats = self.item.get_p... |
else: child_title = parent.child_title | def select_file(self): """Open a file selection dialog box""" fname = self.item.from_string(unicode(self.edit.text())) if isinstance(fname, list): fname = os.path.dirname(fname[0]) parent = self.parent_layout.parent _temp = sys.stdout sys.stdout = None if len(fname) == 0: fname = self.basedir _formats = self.item.get_p... | |
self.item.set(self.value().T) | if self.item.get_prop_value("display", "transpose"): value = self.value().T else: value = self.value() self.item.set(value) | def set(self): """Override AbstractDataSetWidget method""" self.item.set(self.value().T) |
fname = self.filedialog(parent, parent.child_title(self.item), fname, | if isinstance(parent, QGroupBox): child_title = parent.parent().child_title else: child_title = parent.child_title fname = self.filedialog(parent, child_title(self.item), fname, | def select_file(self): """Open a file selection dialog box""" fname = self.item.from_string(unicode(self.edit.text())) if isinstance(fname, list): fname = os.path.dirname(fname[0]) parent = self.parent_layout.parent _temp = sys.stdout sys.stdout = None if len(fname) == 0: fname = self.basedir _formats = self.item.get_p... |
parent.child_title(self.item), | child_title(self.item), | def select_directory(self): """Open a directory selection dialog box""" value = self.item.from_string(unicode(self.edit.text())) parent = self.parent_layout.parent _temp = sys.stdout sys.stdout = None dname = QFileDialog.getExistingDirectory(parent, parent.child_title(self.item), os.path.basename(value)) sys.stdout = _... |
except Exception as e: | except Exception, e: | def __call__(self): try: logger.debug("Lookup the user agent against wurfl db.") wurfl_device = \ devices.select_ua(self.user_agent, search=JaroWinkler(accuracy=0.85)) return WDevice(wurfl_device) # this is bad but a weird but makes DeviceNotFound not catched if # except DeviceNotFound is used except Exception as e: lo... |
pattern_file_path = ('..', '..', '..', 'data', 'MIT', 'device_user_agent_patterns.json') | pattern_file_paths = [ '../../../data/MIT/device_user_agent_patterns.json', '../../../data/Infrae/device_user_agent_patterns.json', ] | def __call__(self): try: logger.debug("Lookup the user agent against wurfl db.") wurfl_device = \ devices.select_ua(self.user_agent, search=JaroWinkler(accuracy=0.85)) return WDevice(wurfl_device) # this is bad but a weird but makes DeviceNotFound not catched if # except DeviceNotFound is used except Exception as e: lo... |
filename = os.path.join(os.path.dirname(__file__), *self.pattern_file_path) fd = open(filename, 'r') try: data = json.load(fd) for item in data: item['pattern'] = self.__make_regex(item['pattern']) self.__patterns = data finally: fd.close() | self.__patterns = [] for path in self.pattern_file_paths: filepath = os.path.join(os.path.dirname(__file__), path) fd = open(filepath, 'r') try: data = json.load(fd) for item in data: item['matcher'] = self.__build_matcher(item['pattern']) self.__patterns += data finally: fd.close() | def load_patterns(self): filename = os.path.join(os.path.dirname(__file__), *self.pattern_file_path) fd = open(filename, 'r') try: data = json.load(fd) for item in data: item['pattern'] = self.__make_regex(item['pattern']) self.__patterns = data finally: fd.close() |
pattern = dev_info['pattern'] if re.match(pattern, ua): logger.debug("User Agent matched %s in MIT pattern list" % str(pattern)) | matcher = dev_info['matcher'] if matcher(ua): logger.debug("User Agent matched against MIT patterns") | def lookup(self, ua): # The order of the patterns is important for dev_info in self.__patterns: pattern = dev_info['pattern'] if re.match(pattern, ua): logger.debug("User Agent matched %s in MIT pattern list" % str(pattern)) logger.debug("Device info : %s" % dev_info) return dev_info logger.debug("Device lookup failed ... |
def __make_regex(self, pattern_string): | def __build_matcher(self, pattern_string): | def __make_regex(self, pattern_string): """ User agent in data can be either a regex e.g: /Opera/ or a string Opera. A string will be converted to a regex like this : |
which is what we want. | /Opera/ -> r/Opera/ | def __make_regex(self, pattern_string): """ User agent in data can be either a regex e.g: /Opera/ or a string Opera. A string will be converted to a regex like this : |
return re.compile(pattern_string) | if pattern_string.startswith('/') and pattern_string.endswith('/'): return RegexMatcher(pattern_string[1:-1]) return StringMatcher(pattern_string) | def __make_regex(self, pattern_string): """ User agent in data can be either a regex e.g: /Opera/ or a string Opera. A string will be converted to a regex like this : |
RouterMiddleWare(app, local_conf) | return RouterMiddleware(app, local_conf) | def filter(app): RouterMiddleWare(app, local_conf) |
hostname, port = environ.get('HTTP_HOST').split(':') | port = 80 hostname = environ.get('HTTP_HOST', '') if ":" in hostname: hostname, port = hostname.split(':', 1) | def __call__(self, environ, start_response): hostname, port = environ.get('HTTP_HOST').split(':') |
mapping = [ | _mapping = [ | def deserialize_cookie(data): return json.loads(base64.b64decode(data) or '{}') |
reverse_mapping = map(lambda (a,b,): (b,a,), mapping) | mapping = dict(_mapping) reverse_mapping = dict(map(lambda (a,b,): (b,a,), _mapping)) | def deserialize_cookie(data): return json.loads(base64.b64decode(data) or '{}') |
device = (self.debug and self.device_from_get_params(request)) or \ | device = self.device_from_get_params(request) or \ | def __call__(self, environ, start_response): request = Request(environ) device = (self.debug and self.device_from_get_params(request)) or \ self.device_from_cookie(request) or \ self.device_from_user_agent(request) |
dtype = device.get_type() or IBasicDeviceType request.environ['playmobile.devices.marker'] = dtype request.environ['playmobile.devices.marker_name'] = dtype.__name__ request.environ['playmobile.devices.platform'] = \ device.get_platform() | self.set_device_on_request(request, device) | def __call__(self, environ, start_response): request = Request(environ) device = (self.debug and self.device_from_get_params(request)) or \ self.device_from_cookie(request) or \ self.device_from_user_agent(request) |
logger.info('device: %s - %s' % (dtype.__name__, device.get_platform(),)) | logger.info('device: %s - %s' % (device.get_type(), device.get_platform(),)) | def __call__(self, environ, start_response): request = Request(environ) device = (self.debug and self.device_from_get_params(request)) or \ self.device_from_cookie(request) or \ self.device_from_user_agent(request) |
dtype = dict(self.mapping).get(cookie_val['type'], | dtype = self.mapping.get(cookie_val['type'], | def device_from_cookie(self, request): data = request.cookies.get(self.PARAM_NAME, None) if data is not None: cookie_val = deserialize_cookie(data) dtype = dict(self.mapping).get(cookie_val['type'], IBasicDeviceType) return Device(request.environ.get('HTTP_USER_AGENT'), dtype, platform=cookie_val['platform']) return No... |
dtype = dict(self.mapping).get(param) | dtype = self.mapping.get(param) platform = request.GET.get(self.PARAM_NAME + '_platform', '') | def device_from_get_params(self, request): param = request.GET.get(self.PARAM_NAME) if param == 'off': return self.device_from_user_agent(request) |
return Device(request.environ.get('HTTP_USER_AGENT'), dtype) | return Device(request.environ.get('HTTP_USER_AGENT'), dtype, platform) return None | def device_from_get_params(self, request): param = request.GET.get(self.PARAM_NAME) if param == 'off': return self.device_from_user_agent(request) |
type_val = dict(self.reverse_mapping).get(device.get_type(), | type_val = self.reverse_mapping.get(device.get_type(), | def set_device_on_cookie(self, response, device): type_val = dict(self.reverse_mapping).get(device.get_type(), 'basic') data = {'type': type_val, 'platform': device.get_platform()} encdata = response.request.cookies.get(self.PARAM_NAME) if encdata is None or \ deserialize_cookie(encdata) != data: response.set_cookie(se... |
pattern_file_path = ('data', 'MIT', 'device_user_agent_patterns.json') | pattern_file_path = ('..', '..', '..', 'data', 'MIT', 'device_user_agent_patterns.json') | def __call__(self): try: wurfl_device = \ devices.select_ua(self.user_agent, search=JaroWinkler(accuracy=0.85)) return WDevice(wurfl_device) # this is bad but a weird but makes DeviceNotFound not catched if # except DeviceNotFound is used except Exception: pass return None |
var='/var/db' | var='/var/db', | def __init__(self, app, cookie_cache=True, cache_opts=None, debug=False, cookie_max_age=0, var='/var/db' wurfl_file=None): self.debug = debug self.cookie_cache = cookie_cache cache_manager = CacheManager( **parse_cache_config_options(cache_opts or self.DEFAULT_CACHE_OPTIONS)) self.cache = cache_manager.get_cache('mobi.... |
device_type = params.get('dt', [None])[0] if device_type == 'basic': | self.DEBUG_DEVICE_TYPE = params.get('dt', [None])[0] \ or self.DEBUG_DEVICE_TYPE if self.DEBUG_DEVICE_TYPE == 'basic': | def get_from_params(self, query_string): from cgi import parse_qs from playmobile.interfaces.devices import ( IBasicDeviceType, IStandardDeviceType, IAdvancedDeviceType) params = parse_qs(query_string) device_type = params.get('dt', [None])[0] if device_type == 'basic': return IBasicDeviceType elif device_type == 'stan... |
elif device_type == 'standard': | elif self.DEBUG_DEVICE_TYPE == 'standard': | def get_from_params(self, query_string): from cgi import parse_qs from playmobile.interfaces.devices import ( IBasicDeviceType, IStandardDeviceType, IAdvancedDeviceType) params = parse_qs(query_string) device_type = params.get('dt', [None])[0] if device_type == 'basic': return IBasicDeviceType elif device_type == 'stan... |
elif device_type == 'advanced': | elif self.DEBUG_DEVICE_TYPE == 'advanced': | def get_from_params(self, query_string): from cgi import parse_qs from playmobile.interfaces.devices import ( IBasicDeviceType, IStandardDeviceType, IAdvancedDeviceType) params = parse_qs(query_string) device_type = params.get('dt', [None])[0] if device_type == 'basic': return IBasicDeviceType elif device_type == 'stan... |
return IAdvancedDeviceType | def get_from_params(self, query_string): from cgi import parse_qs from playmobile.interfaces.devices import ( IBasicDeviceType, IStandardDeviceType, IAdvancedDeviceType) params = parse_qs(query_string) self.DEBUG_DEVICE_TYPE = params.get('dt', [None])[0] \ or self.DEBUG_DEVICE_TYPE if self.DEBUG_DEVICE_TYPE == 'basic':... | |
device = self.cache('select_ua', lambda : get_device(ua)) | device = self.cache('select_ua:%s' % ua, lambda : get_device(ua)) | def __call__(self, environ, start_response): ua = environ.get('HTTP_USER_AGENT', '') device = self.cache('select_ua', lambda : get_device(ua)) dtype = device.get_type() environ['playmobile.devices.marker'] = dtype environ['playmobile.devices.marker_name'] = dtype.__name__ return self.app(environ, start_response) |
var='/var/db'): | var='/var/db' wurfl_file=None): | def __init__(self, app, cookie_cache=True, cache_opts=None, debug=False, cookie_max_age=0, var='/var/db'): self.debug = debug self.cookie_cache = cookie_cache cache_manager = CacheManager( **parse_cache_config_options(cache_opts or self.DEFAULT_CACHE_OPTIONS)) self.cache = cache_manager.get_cache('mobi.devices') |
self.classifiers = [MITClassifier(), WurflClassifier({'var': var})] | self.classifiers = [MITClassifier(), WurflClassifier({'var': var, 'wurfl_file': wurfl_file})] | def __init__(self, app, cookie_cache=True, cache_opts=None, debug=False, cookie_max_age=0, var='/var/db'): self.debug = debug self.cookie_cache = cookie_cache cache_manager = CacheManager( **parse_cache_config_options(cache_opts or self.DEFAULT_CACHE_OPTIONS)) self.cache = cache_manager.get_cache('mobi.devices') |
cookie_max_age=cookie_max_age) | cookie_max_age=cookie_max_age, var=var_opt) | def filter(app): debug = global_conf.get('debug', False) or \ local_conf.get('debug', False) cookie_max_age = int(local_conf.get('cookie_max_age', 0)) cookie_cache = local_conf.get('cookie_cache', not(debug)) cache_options = {} for key, value in local_conf.iteritems(): if key.startswith('cache'): cache_options[key] = v... |
request.environ['playmobile.devices.platform'] = device.get_platform() | request.environ['playmobile.devices.platform'] = \ device.get_platform() | def __call__(self, environ, start_response): request = Request(environ) device = (self.debug and self.device_from_get_params(request)) or \ self.device_from_cookie(request) or \ self.device_from_user_agent(request) |
debug = global_conf.get('debug', False) | debug = global_conf.get('debug', False) or \ local_conf.get('debug', False) | def filter(app): debug = global_conf.get('debug', False) return PlaymobileDeviceMiddleware(app, debug) |
data=np.genfromtxt(filename, delimiter=",", skiprows=1) | data=np.genfromtxt(filename, delimiter=",", dtype=float)[1:] | def __init__(self): # set up data # filename = os.path.join(os.path.dirname(os.path.abspath(__file__)), "inv_gaussian.csv") data=np.genfromtxt(filename, delimiter=",", skiprows=1) self.endog = data[:5000,0] self.exog = data[:5000,1:] self.exog = tools.add_constant(self.exog) # Results |
def het_breushpagan(y,x): | def het_breushpagan(resid, x, exog=None): | def het_breushpagan(y,x): '''Lagrange Multiplier Heteroscedasticity Test by Breush-Pagan Notes ----- assumes x contains constant (for counting dof) need to check this again, is different in Greene p224 References ---------- http://en.wikipedia.org/wiki/Breusch%E2%80%93Pagan_test Greene ''' x = np.asarray(x) y = np.... |
assumes x contains constant (for counting dof) need to check this again, is different in Greene p224 | Assumes x contains constant (for counting dof and calculation of R^2). In the general description of LM test, Greene mentions that this test exaggerates the significance of results in small or moderately large samples. In this case the F-statistic is preferrable. *Verification* Chisquare test statistic is exactly (<1... | def het_breushpagan(y,x): '''Lagrange Multiplier Heteroscedasticity Test by Breush-Pagan Notes ----- assumes x contains constant (for counting dof) need to check this again, is different in Greene p224 References ---------- http://en.wikipedia.org/wiki/Breusch%E2%80%93Pagan_test Greene ''' x = np.asarray(x) y = np.... |
Greene ''' | Greene 5th edition ''' if not exog is None: resid = sm.OLS(y, exog).fit() | def het_breushpagan(y,x): '''Lagrange Multiplier Heteroscedasticity Test by Breush-Pagan Notes ----- assumes x contains constant (for counting dof) need to check this again, is different in Greene p224 References ---------- http://en.wikipedia.org/wiki/Breusch%E2%80%93Pagan_test Greene ''' x = np.asarray(x) y = np.... |
y = np.asarray(y)**2 | y = np.asarray(resid)**2 | def het_breushpagan(y,x): '''Lagrange Multiplier Heteroscedasticity Test by Breush-Pagan Notes ----- assumes x contains constant (for counting dof) need to check this again, is different in Greene p224 References ---------- http://en.wikipedia.org/wiki/Breusch%E2%80%93Pagan_test Greene ''' x = np.asarray(x) y = np.... |
retres : boolean if true, then an instance of a result class is returned, otherwise 2 numbers, fvalue and p-value, are returned | drop : alternative : | def het_goldfeldquandt(y, x, idx, split=None, retres=False): '''test whether variance is the same in 2 subsamples Parameters ---------- y : array_like endogenous variable x : array_like exogenous variable, regressors idx : integer column index of variable according to which observations are sorted for the split split ... |
y = np.asarray(y)**2 | y = np.asarray(y) | def run(self, y, x, idx=None, split=None, drop=None, alternative='increasing', attach=True): '''see class docstring''' x = np.asarray(x) y = np.asarray(y)**2 nobs, nvars = x.shape if split is None: split = nobs//2 elif (0<split) and (split<1): split = int(nobs*split) if drop is None: start2 = split elif (0<split) and (... |
elif (0<split) and (split<1): | elif (0<drop) and (drop<1): | def run(self, y, x, idx=None, split=None, drop=None, alternative='increasing', attach=True): '''see class docstring''' x = np.asarray(x) y = np.asarray(y)**2 nobs, nvars = x.shape if split is None: split = nobs//2 elif (0<split) and (split<1): split = int(nobs*split) if drop is None: start2 = split elif (0<split) and (... |
fpval = min(fpval_sm, fpval_la) | fpval = 2*min(fpval_sm, fpval_la) | def run(self, y, x, idx=None, split=None, drop=None, alternative='increasing', attach=True): '''see class docstring''' x = np.asarray(x) y = np.asarray(y)**2 nobs, nvars = x.shape if split is None: split = nobs//2 elif (0<split) and (split<1): split = int(nobs*split) if drop is None: start2 = split elif (0<split) and (... |
def test_reset_trend(object): | def test_reset_trend(): | def test_reset_trend(object): endog = y_arma[:,0] mod = ARMA(endog) res1 = mod.fit(order=(1,1), trend="c") res2 = mod.fit(order=(1,1), trend="nc") assert_equal(len(res1.params), len(res2.params)+1) |
return np.dot(exog, self.results.params) | return np.dot(exog, self._results.params) | def predict(self, exog=None, linear=False): """ Predict response variable of a model given exogenous variables. |
Calculates the Durbin-Waston statistic | Calculates the Durbin-Watson statistic | def durbin_watson(resids): """ Calculates the Durbin-Waston statistic Parameters ----------- resids : array-like Returns -------- Durbin Watson statistic. This is defined as sum_(t=2)^(T)((e_t - e_(t-1))^(2))/sum_(t=1)^(T)e_t^(2) """ diff_resids = np.diff(resids,1) dw = np.dot(diff_resids,diff_resids) / \ np.dot(res... |
Example ----------simple >>> decstats(data.exog,v=['x_1','x_2','x_3']) | Examples -------- >>> descstats(data.exog,v=['x_1','x_2','x_3']) | def descstats(data, cols=None, axis=0): ''' Prints descriptive statistics for one or multiple variables. Parameters ------------ data: numpy array `x` is the data v: list, optional A list of the column number or field names (for a recarray) of variables. Default is all columns. axis: 1 or 0 axis order of data. Defa... |
return 2*np.sum(Y*np.log(Y/mu))/scale | Yin = np.clip(Y, 1e-12, np.inf) return 2*np.sum(Y*np.log(Yin/mu))/scale | def deviance(self, Y, mu, scale=1.): ''' Poisson deviance function |
exog = np.asarray(exog) | def __init__(self, endog, exog=None): endog = np.asarray(endog) endog = np.squeeze(endog) # for consistent outputs if endog is (n,1) exog = np.asarray(exog) | |
if exog.ndim == 1: exog = exog[:,None] if exog.ndim != 2: raise ValueError, "exog is not 1d or 2d" if endog.shape[0] != exog.shape[0]: raise ValueError, "endog and exog matrices are not aligned." | if not exog is None: exog = np.asarray(exog) if exog.ndim == 1: exog = exog[:,None] if exog.ndim != 2: raise ValueError, "exog is not 1d or 2d" if endog.shape[0] != exog.shape[0]: raise ValueError, "endog and exog matrices are not aligned." | def __init__(self, endog, exog=None): endog = np.asarray(endog) endog = np.squeeze(endog) # for consistent outputs if endog is (n,1) exog = np.asarray(exog) |
Normalized (before scaling) covariance of params normalized_cov_params is also known as the hat matrix or H (Semiparametric regression, Ruppert, Wand, Carroll; CUP 2003) | Normalized (before scaling) covariance of params. (dot(X.T,X))**-1 | def __init__(self, model, params, normalized_cov_params=None, scale=1.): """ Class to contain results from likelihood models |
>>> std_res = (mod_fit.resid - mod_fit.mean())/mod_fit.std() | >>> std_res = (mod_fit.resid - mod_fit.resid.mean())/mod_fit.resid.std() | def qqplot(data, dist=stats.distributions.norm, binom_n=None): """ qqplot of the quantiles of x versus the ppf of a distribution. Parameters ---------- data : array-like 1d data array dist : scipy.stats.distribution or string Compare x against dist. Strings aren't implemented yet. The default is scipy.stats.distribu... |
if confint: varacf = np.ones(nlags)/nobs varacf[1:] *= 1 + 2*np.cumsum(acf[1:-1]**2) | if not confint is None: varacf = np.ones(nlags+1)/nobs varacf[0] = 0 varacf[1:] *= 1 + 2*np.cumsum(acf[1:]**2) | def acf(x, unbiased=False, nlags=40, confint=None, qstat=False, fft=False): ''' Autocorrelation function for 1d arrays. Parameters ---------- x : array Time series data unbiased : bool If True, then denominators for autocovariance are n-k, otherwise n nlags: int, optional Number of lags to return autocorrelation for. ... |
acf1,ci1,Q,pvalue = acf(x, nlags=40, confint=95, qstat=True) acf2, ci2,Q2,pvalue2 = acf(x, nlags=40, confint=95, fft=True, qstat=True) acf3,ci3,Q3,pvalue3 = acf(x, nlags=40, confint=95, qstat=True, unbiased=True) acf4, ci4,Q4,pvalue4 = acf(x, nlags=40, confint=95, fft=True, qstat=True, unbiased=True) | def grangercausalitytests(x, maxlag): '''four tests for granger causality of 2 timeseries this is a proof-of concept implementation not cleaned up, has some duplicate calculations, memory intensive - builds full lag array for variables prints results not verified with other packages, all four tests give similar result... | |
newparams[k+p:j] = tmp[:j] | newparams[k+p:k+p+j] = tmp[:j] | def _transparams(self, params): """ Transforms params to induce stationarity/invertability. |
def _invtransparams(self, params): | def _invtransparams(self, start_params): | def _invtransparams(self, params): """ Inverse of the Jones reparameterization """ p,q,k = self.p, self.q, self.k arcoefs = params[k:k+p] macoefs = params[k+p:] # AR coeffs if p != 0: tmp = arcoefs.copy() newparams = arcoefs.copy() for j in range(p-1,0,-1): a = newparams[j] for k in range(j): tmp[k] = (newparams[k] + a... |
arcoefs = params[k:k+p] macoefs = params[k+p:] | newparams = start_params.copy() arcoefs = newparams[k:k+p] macoefs = newparams[k+p:] | def _invtransparams(self, params): """ Inverse of the Jones reparameterization """ p,q,k = self.p, self.q, self.k arcoefs = params[k:k+p] macoefs = params[k+p:] # AR coeffs if p != 0: tmp = arcoefs.copy() newparams = arcoefs.copy() for j in range(p-1,0,-1): a = newparams[j] for k in range(j): tmp[k] = (newparams[k] + a... |
newparams = arcoefs.copy() | def _invtransparams(self, params): """ Inverse of the Jones reparameterization """ p,q,k = self.p, self.q, self.k arcoefs = params[k:k+p] macoefs = params[k+p:] # AR coeffs if p != 0: tmp = arcoefs.copy() newparams = arcoefs.copy() for j in range(p-1,0,-1): a = newparams[j] for k in range(j): tmp[k] = (newparams[k] + a... | |
a = newparams[j] | a = arcoefs[j] | def _invtransparams(self, params): """ Inverse of the Jones reparameterization """ p,q,k = self.p, self.q, self.k arcoefs = params[k:k+p] macoefs = params[k+p:] # AR coeffs if p != 0: tmp = arcoefs.copy() newparams = arcoefs.copy() for j in range(p-1,0,-1): a = newparams[j] for k in range(j): tmp[k] = (newparams[k] + a... |
tmp[k] = (newparams[k] + a * newparams[j-k-1])/(1-a**2) newparams[:j] = tmp[:j] invarcoefs = -log((1-newparams)/(1+newparams)) start_params[k:k+p] = invarcoefs | tmp[k] = (arcoefs[k] + a * arcoefs[j-k-1])/(1-a**2) arcoefs[:j] = tmp[:j] invarcoefs = -log((1-arcoefs)/(1+arcoefs)) newparams[k:k+p] = invarcoefs | def _invtransparams(self, params): """ Inverse of the Jones reparameterization """ p,q,k = self.p, self.q, self.k arcoefs = params[k:k+p] macoefs = params[k+p:] # AR coeffs if p != 0: tmp = arcoefs.copy() newparams = arcoefs.copy() for j in range(p-1,0,-1): a = newparams[j] for k in range(j): tmp[k] = (newparams[k] + a... |
newparams = macoefs.copy() | def _invtransparams(self, params): """ Inverse of the Jones reparameterization """ p,q,k = self.p, self.q, self.k arcoefs = params[k:k+p] macoefs = params[k+p:] # AR coeffs if p != 0: tmp = arcoefs.copy() newparams = arcoefs.copy() for j in range(p-1,0,-1): a = newparams[j] for k in range(j): tmp[k] = (newparams[k] + a... | |
b = newparams[j] | b = macoefs[j] | def _invtransparams(self, params): """ Inverse of the Jones reparameterization """ p,q,k = self.p, self.q, self.k arcoefs = params[k:k+p] macoefs = params[k+p:] # AR coeffs if p != 0: tmp = arcoefs.copy() newparams = arcoefs.copy() for j in range(p-1,0,-1): a = newparams[j] for k in range(j): tmp[k] = (newparams[k] + a... |
tmp[k] = (newparams[k] - b * newparams[j-k-1])/(1-b**2) newparams[:j] = tmp[:j] invmacoefs = -log((1-newparams)/(1+newparams)) start_params[k+p:k+p+q] = invmacoefs return start_params | tmp[k] = (macoefs[k] - b * macoefs[j-k-1])/(1-b**2) macoefs[:j] = tmp[:j] invmacoefs = -log((1-macoefs)/(1+macoefs)) newparams[k+p:k+p+q] = invmacoefs return newparams | def _invtransparams(self, params): """ Inverse of the Jones reparameterization """ p,q,k = self.p, self.q, self.k arcoefs = params[k:k+p] macoefs = params[k+p:] # AR coeffs if p != 0: tmp = arcoefs.copy() newparams = arcoefs.copy() for j in range(p-1,0,-1): a = newparams[j] for k in range(j): tmp[k] = (newparams[k] + a... |
newparams = self._transparams(start_params) | newparams = self._transparams(params) | def loglike(self, params): |
resparams = results[0] newparams = np.zeros_like(resparams) if p != 0: newparams[k:k+p] = ((1-exp(-resparams[k:k+p]))/(1+exp(-resparams[k:k+p]))).copy() tmp = ((1-exp(-resparams[k:k+p]))/(1+exp(-resparams[k:k+p]))).copy() for j in range(1,p): a = newparams[k+j] for kiter in range(j): tmp[kiter] -= a * newparams[k+j-... | newparams = self._transparams(results[0]) | def fit(self, start_params=None, transparams=True): self.transparams = transparams r = self.r p = self.p q = self.q k = self.k |
self.nobs = nobs | self.nobs = n | def __init__(self, ar, ma, n): #duplicates now that are subclassing ArmaProcess super(ArmaFft, self).__init__(ar, ma) |
def padarr(self, arr, maxlag): | def padarr(self, arr, maxlag, atend=True): | def padarr(self, arr, maxlag): '''pad 1d array with zeros at end to have length maxlag function that is a method, no self used ''' return np.r_[arr, np.zeros(maxlag-len(arr))] |
''' return np.r_[arr, np.zeros(maxlag-len(arr))] | Parameters ---------- arr : array_like, 1d array that will be padded with zeros maxlag : int length of array after padding atend : boolean If True (default), then the zeros are added to the end, otherwise to the front of the array Returns ------- arrp : ndarray zero-padded array Notes ----- This is mainly written to ... | def padarr(self, arr, maxlag): '''pad 1d array with zeros at end to have length maxlag function that is a method, no self used ''' return np.r_[arr, np.zeros(maxlag-len(arr))] |
def fftar(self, n): | def fftar(self, n=None): '''Fourier transform of AR polynomial, zero-padded at end to n Parameters ---------- n : int length of array after zero-padding Returns ------- fftar : ndarray fft of zero-padded ar polynomial ''' if n is None: n = len(self.ar) | def fftar(self, n): return fft.fft(self.padarr(self.ar, n)) |
return (hw*hw.conj()).real[n//2-1:] | w = fft.fftfreq(n) wslice = slice(n//2-1, None, None) return (hw*hw.conj()).real[wslice], w[wslice] | def spdshift(self, n): #size = s1+s2-1 mapadded = self.padarr(self.ma, n) arpadded = self.padarr(self.ar, n) hw = fft.fft(fft.fftshift(mapadded)) / fft.fft(fft.fftshift(arpadded)) #return np.abs(spd)[n//2-1:] return (hw*hw.conj()).real[n//2-1:] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.