From c8332efa7c9db7c157089bfea23b74ba328c4f35 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 8 Nov 2016 15:29:37 +0100 Subject: [PATCH 001/155] Inference with AD3 on CRF models now supports hard logic constraints. Note: This code requires the AD3 updated library currently availble at https://github.com/jlmeunier/AD3 --- pystruct/inference/inference_methods.py | 21 +++++++++++++++++++-- pystruct/learners/ssvm.py | 19 +++++++++++++++---- pystruct/models/base.py | 6 ++++-- pystruct/models/crf.py | 16 ++++++++++++---- pystruct/utils/inference.py | 7 +++++-- 5 files changed, 55 insertions(+), 14 deletions(-) diff --git a/pystruct/inference/inference_methods.py b/pystruct/inference/inference_methods.py index 8087ed20..7d23be13 100644 --- a/pystruct/inference/inference_methods.py +++ b/pystruct/inference/inference_methods.py @@ -311,7 +311,8 @@ def inference_lp(unary_potentials, pairwise_potentials, edges, relaxed=False, def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, - verbose=0, return_energy=False, branch_and_bound=False): + verbose=0, return_energy=False, branch_and_bound=False, + constraints=None): """Inference with AD3 dual decomposition subgradient solver. Parameters @@ -345,6 +346,18 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, Whether to attempt to produce an integral solution using branch-and-bound. + constraints : list of logical constraints or None (default:=None) + A logical constraint is tuple like ( , , , ) + where: + - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - unaries is a list of the index of each unary involved in this constraint + - states is a list of unary states (class), 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. + - negated is a list of boolean indicating if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list + + NOTE: this hard logic constraint mechanism relies on the binarisation method described by Martins et al. in their 2011 ICML paper. + It has been developed for the EU project READ, by JL Meunier (Xerox), in November 2016. + The READ project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. + Returns ------- labels : nd-array @@ -356,7 +369,11 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, _validate_params(unary_potentials, pairwise_potentials, edges) unaries = unary_potentials.reshape(-1, n_states) - res = ad3.general_graph(unaries, edges, pairwise_potentials, verbose=verbose, + if constraints: + res = ad3.general_constrained_graph(unaries, edges, pairwise_potentials, constraints, verbose=verbose, + n_iterations=4000, exact=branch_and_bound) + else: + res = ad3.general_graph(unaries, edges, pairwise_potentials, verbose=verbose, n_iterations=4000, exact=branch_and_bound) unary_marginals, pairwise_marginals, energy, solver_status = res if verbose: diff --git a/pystruct/learners/ssvm.py b/pystruct/learners/ssvm.py index 224754f8..d6c7c5e9 100644 --- a/pystruct/learners/ssvm.py +++ b/pystruct/learners/ssvm.py @@ -18,13 +18,15 @@ def __init__(self, model, max_iter=100, C=1.0, verbose=0, self.n_jobs = n_jobs self.logger = logger - def predict(self, X): + def predict(self, X, constraints=None): """Predict output on examples in X. Parameters ---------- X : iterable Traing instances. Contains the structured input objects. + + constraints : None or a list of hard logic constraints Returns ------- @@ -34,12 +36,21 @@ def predict(self, X): """ verbose = max(0, self.verbose - 3) if self.n_jobs != 1: - prediction = Parallel(n_jobs=self.n_jobs, verbose=verbose)( - delayed(inference)(self.model, x, self.w) for x in X) + if constraints: + prediction = Parallel(n_jobs=self.n_jobs, verbose=verbose)( + delayed(inference)(self.model, x, self.w, constraints=c) for x,c in zip(X, constraints)) + else: + prediction = Parallel(n_jobs=self.n_jobs, verbose=verbose)( + delayed(inference)(self.model, x, self.w) for x in X) return prediction else: if hasattr(self.model, 'batch_inference'): - return self.model.batch_inference(X, self.w) + if constraints: + return self.model.batch_inference(X, self.w, constraints=constraints) + else: + return self.model.batch_inference(X, self.w) + if constraints: + return [self.model.inference(x, self.w, constraints=c) for x,c in zip(X, constraints)] return [self.model.inference(x, self.w) for x in X] def score(self, X, Y): diff --git a/pystruct/models/base.py b/pystruct/models/base.py index c63fcdaf..a673d95e 100644 --- a/pystruct/models/base.py +++ b/pystruct/models/base.py @@ -46,11 +46,13 @@ def _loss_augmented_djoint_feature(self, x, y, y_hat, w): return (self.joint_feature(x_loss_augmented, y) - self.joint_feature(x_loss_augmented, y_hat)) - def inference(self, x, w, relaxed=None): + def inference(self, x, w, relaxed=None, constraints=None): raise NotImplementedError() - def batch_inference(self, X, w, relaxed=None): + def batch_inference(self, X, w, relaxed=None, constraints=None): # default implementation of batch inference + if constraints: + return [self.inference(x, w, relaxed=relaxed, constriants=c) for x,c in zip(X, constraints)] return [self.inference(x, w, relaxed=relaxed) for x in X] diff --git a/pystruct/models/crf.py b/pystruct/models/crf.py index 18dc7437..c042fe06 100644 --- a/pystruct/models/crf.py +++ b/pystruct/models/crf.py @@ -109,7 +109,7 @@ def loss_augmented_inference(self, x, y, w, relaxed=False, self.inference_method, relaxed=relaxed, return_energy=return_energy) - def inference(self, x, w, relaxed=False, return_energy=False): + def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): """Inference for x using parameters w. Finds (approximately) @@ -137,6 +137,9 @@ def inference(self, x, w, relaxed=False, return_energy=False): return_energy : bool, default=False Whether to return the energy of the solution (x, y) that was found. + constraints : None or list, default=False + hard logic constraints, if any + Returns ------- y_pred : ndarray or tuple @@ -156,6 +159,11 @@ def inference(self, x, w, relaxed=False, return_energy=False): pairwise_potentials = self._get_pairwise_potentials(x, w) edges = self._get_edges(x) - return inference_dispatch(unary_potentials, pairwise_potentials, edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy) + if constraints: + return inference_dispatch(unary_potentials, pairwise_potentials, edges, + self.inference_method, relaxed=relaxed, + return_energy=return_energy, constraints=constraints) + else: + return inference_dispatch(unary_potentials, pairwise_potentials, edges, + self.inference_method, relaxed=relaxed, + return_energy=return_energy) \ No newline at end of file diff --git a/pystruct/utils/inference.py b/pystruct/utils/inference.py index 89b14f64..e21c6561 100644 --- a/pystruct/utils/inference.py +++ b/pystruct/utils/inference.py @@ -100,8 +100,11 @@ def find_constraint_latent(model, x, y, w, relaxed=True): return h_hat, delta_joint_feature, slack, loss -def inference(model, x, w): - return model.inference(x, w) +def inference(model, x, w, constraints=None): + if constraints: + return model.inference(x, w, constraints=constraints) + else: + return model.inference(x, w) def loss_augmented_inference(model, x, y, w, relaxed=True): From 30739de521d7a2c8d1897b33c37743db41a5e2f3 Mon Sep 17 00:00:00 2001 From: meunier Date: Tue, 20 Dec 2016 14:03:46 +0100 Subject: [PATCH 002/155] The Snake example with logic constraints. --- examples/plot_snakes_constraints.py | 259 ++++++++++++++++++++++++++++ 1 file changed, 259 insertions(+) create mode 100644 examples/plot_snakes_constraints.py diff --git a/examples/plot_snakes_constraints.py b/examples/plot_snakes_constraints.py new file mode 100644 index 00000000..a15d0553 --- /dev/null +++ b/examples/plot_snakes_constraints.py @@ -0,0 +1,259 @@ +""" +============================================== +Conditional Interactions on the Snakes Dataset +============================================== +This example uses the snake dataset introduced in +Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 + +This dataset is specifically designed to require the pairwise interaction terms +to be conditioned on the input, in other words to use non-trival edge-features. + +The task is as following: a "snake" of length ten wandered over a grid. For +each cell, it had the option to go up, down, left or right (unless it came from +there). The input consists of these decisions, while the desired output is an +annotation of the snake from 0 (head) to 9 (tail). See the plots for an +example. + +As input features we use a 3x3 window around each pixel (and pad with background +where necessary). We code the five different input colors (for up, down, left, right, +background) using a one-hot encoding. This is a rather naive approach, not using any +information about the dataset (other than that it is a 2d grid). + +The task can not be solved using the simple DirectionalGridCRF - which can only +infer head and tail (which are also possible to infer just from the unary +features). If we add edge-features that contain the features of the nodes that are +connected by the edge, the CRF can solve the task. + +From an inference point of view, this task is very hard. QPBO move-making is +not able to solve it alone, so we use the relaxed AD3 inference for learning. + +PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). +But it does work as well as Decision Tree Fields ;) + +UPDATE: we also inject domain knowledge at inference time by telling that there +is at-most or exactly one of each annotation from 1 to 10 (0 is background). +""" +import time +import numpy as np +bPlot = False +if bPlot: + import matplotlib.pyplot as plt + +from sklearn.preprocessing import label_binarize +from sklearn.metrics import confusion_matrix, accuracy_score + +from pystruct.learners import OneSlackSSVM +from pystruct.datasets import load_snakes +from pystruct.utils import make_grid_edges, edge_list_to_features +from pystruct.models import EdgeFeatureGraphCRF + + +def one_hot_colors(x): + x = x / 255 + flat = np.dot(x.reshape(-1, 3), 2 ** np.arange(3)) + one_hot = label_binarize(flat, classes=[1, 2, 3, 4, 6]) + return one_hot.reshape(x.shape[0], x.shape[1], 5) + + +def neighborhood_feature(x): + """Add a 3x3 neighborhood around each pixel as a feature.""" + # we could also use a four neighborhood, that would work even better + # but one might argue then we are using domain knowledge ;) + features = np.zeros((x.shape[0], x.shape[1], 5, 9)) + # position 3 is background. + features[:, :, 3, :] = 1 + features[1:, 1:, :, 0] = x[:-1, :-1, :] + features[:, 1:, :, 1] = x[:, :-1, :] + features[:-1, 1:, :, 2] = x[1:, :-1, :] + features[1:, :, :, 3] = x[:-1, :, :] + features[:-1, :-1, :, 4] = x[1:, 1:, :] + features[:-1, :, :, 5] = x[1:, :, :] + features[1:, :-1, :, 6] = x[:-1, 1:, :] + features[:, :-1, :, 7] = x[:, 1:, :] + features[:, :, :, 8] = x[:, :, :] + return features.reshape(x.shape[0] * x.shape[1], -1) + + +def prepare_data(X): + X_directions = [] + X_edge_features = [] + for x in X: + # get edges in grid + right, down = make_grid_edges(x, return_lists=True) + edges = np.vstack([right, down]) + # use 3x3 patch around each point + features = neighborhood_feature(x) + # simple edge feature that encodes just if an edge is horizontal or + # vertical + edge_features_directions = edge_list_to_features([right, down]) + # edge feature that contains features from the nodes that the edge connects + edge_features = np.zeros((edges.shape[0], features.shape[1], 4)) + edge_features[:len(right), :, 0] = features[right[:, 0]] + edge_features[:len(right), :, 1] = features[right[:, 1]] + edge_features[len(right):, :, 0] = features[down[:, 0]] + edge_features[len(right):, :, 1] = features[down[:, 1]] + edge_features = edge_features.reshape(edges.shape[0], -1) + X_directions.append((features, edges, edge_features_directions)) + X_edge_features.append((features, edges, edge_features)) + return X_directions, X_edge_features + + +print("Please be patient. Learning will take 5-20 minutes.") +snakes = load_snakes() +X_train, Y_train = snakes['X_train'], snakes['Y_train'] + +X_train = [one_hot_colors(x) for x in X_train] +Y_train_flat = [y_.ravel() for y_ in Y_train] + +X_train_directions, X_train_edge_features = prepare_data(X_train) + +#inference = 'qpbo' +#I'm interested in AD3 inference. +inference = 'ad3' + +# first, train on X with directions only: +crf = EdgeFeatureGraphCRF(inference_method=inference) +ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, + n_jobs=1) +ssvm.fit(X_train_directions, Y_train_flat) + +# Evaluate using confusion matrix. +# Clearly the middel of the snake is the hardest part. +X_test, Y_test = snakes['X_test'], snakes['Y_test'] +X_test = [one_hot_colors(x) for x in X_test] +Y_test_flat = [y_.ravel() for y_ in Y_test] +X_test_directions, X_test_edge_features = prepare_data(X_test) + +t0 = time.time() +Y_pred = ssvm.predict(X_test_directions) +print("Results using only directional features for edges. %.1fs"%(time.time()-t0)) +print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) +print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) + +#Predict under constraints +def buildConstraints(X, bOne=True): + """ + We iterate over each graph, and make sure that for each, we constrain to have a single instances of classes 1 to 9 + (or atmost one) + + The constraints must be a list of tuples like ( , , , ) + where: + - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - unaries is a list of the index of the unaries involved in this constraint + - states is a list of unary states, 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. + - negated is a list of boolean indicated if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list + """ + sLogicOp = "XOR" if bOne else "ATMOSTONE" + lConstraint = [] + for (node_features, edges, edge_features) in X: + n_nodes = node_features.shape[0] + lConstraintPerGraph = [ (sLogicOp, range(n_nodes), i, False) for i in range(1,10) ] #only one + lConstraint.append( lConstraintPerGraph ) + return lConstraint + + +lConstraint = buildConstraints(X_test_directions) +t0 = time.time() +Y_predC = ssvm.predict(X_test_directions, lConstraint) +print("Same test with hard logic constraints. %.1fs"%(time.time()-t0)) +print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_predC))) +print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_predC))) + +# now, use more informative edge features: +crf = EdgeFeatureGraphCRF(inference_method=inference) +ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', + n_jobs=-1) +ssvm.fit(X_train_edge_features, Y_train_flat) +t0 = time.time() +Y_pred2 = ssvm.predict(X_test_edge_features) +print("Results using also input features for edges. %.1fs"%(time.time()-t0)) +print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) +print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + +#Predict under constraints +lConstraint = buildConstraints(X_test_edge_features) +t0 = time.time() +Y_pred2C = ssvm.predict(X_test_edge_features, lConstraint) +print("Same test with hard logic constraints. %.1fs"%(time.time()-t0)) +print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2C))) +print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2C))) + +if bPlot: + # plot stuff + fig, axes = plt.subplots(2, 2) + axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') + axes[0, 0].set_title('Input') + y = Y_test[0].astype(np.int) + bg = 2 * (y != 0) # enhance contrast + axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) + axes[0, 1].set_title("Ground Truth") + axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 0].set_title("Prediction w/o edge features") + axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 1].set_title("Prediction with edge features") + for a in axes.ravel(): + a.set_xticks(()) + a.set_yticks(()) + plt.show() + +""" +> python plot_snakes_constraints_DEVTEST.py +Please be patient. Learning will take 5-20 minutes. +Results using only directional features for edges. 1.0s +Test accuracy: 0.854 +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 59 0 22 4 6 1 7 1 0] + [ 0 3 1 29 5 31 8 18 1 3 1] + [ 0 1 13 2 30 11 25 1 13 3 1] + [ 0 1 1 9 4 46 11 15 3 9 1] + [ 0 1 7 2 24 10 21 7 23 2 3] + [ 0 0 1 6 7 35 10 17 3 21 0] + [ 0 0 7 2 14 10 16 4 25 0 22] + [ 0 0 0 3 7 14 4 12 2 58 0] + [ 0 0 5 3 11 3 7 0 5 0 66]] +Same test with hard logic constraints. 89.1s +Test accuracy: 0.871 +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 1 0 65 1 19 2 2 2 7 0 1] + [ 0 0 2 41 4 20 1 20 5 6 1] + [ 0 0 15 3 32 5 24 3 11 3 4] + [ 0 0 1 24 3 32 8 20 4 6 2] + [ 0 0 9 2 19 9 29 6 20 5 1] + [ 0 0 2 14 5 19 11 33 2 11 3] + [ 0 0 3 4 8 5 18 5 43 3 11] + [ 0 0 0 1 4 9 3 15 0 66 2] + [ 0 0 6 2 2 0 4 0 10 2 74]] +Results using also input features for edges. 2.2s +Test accuracy: 0.998 +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 100 0 0 0 0 0 0 0] + [ 0 0 0 0 98 0 1 0 1 0 0] + [ 0 0 0 2 0 98 0 0 0 0 0] + [ 0 0 0 0 2 0 98 0 0 0 0] + [ 0 0 0 0 0 2 0 98 0 0 0] + [ 0 0 0 0 0 0 1 0 99 0 0] + [ 0 0 0 0 0 0 0 0 0 100 0] + [ 0 0 0 0 0 0 0 0 0 0 100]] +Same test with hard logic constraints. 5.8s +Test accuracy: 0.998 +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 99 0 0 0 0 0 1 0] + [ 0 0 0 0 99 0 1 0 0 0 0] + [ 0 0 0 1 0 99 0 0 0 0 0] + [ 0 0 0 0 1 0 99 0 0 0 0] + [ 0 0 0 0 0 1 0 99 0 0 0] + [ 0 0 0 0 0 0 1 0 99 0 0] + [ 0 0 0 0 0 0 0 1 0 99 0] + [ 0 0 0 0 0 0 0 0 0 0 100]] + +""" \ No newline at end of file From 26d3c36adb686fefc52c89aa1d1fb5c33d75fdae Mon Sep 17 00:00:00 2001 From: meunier Date: Wed, 21 Dec 2016 10:52:58 +0100 Subject: [PATCH 003/155] bug fix: typo in parameter name --- pystruct/models/base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pystruct/models/base.py b/pystruct/models/base.py index a673d95e..76483bec 100644 --- a/pystruct/models/base.py +++ b/pystruct/models/base.py @@ -52,7 +52,7 @@ def inference(self, x, w, relaxed=None, constraints=None): def batch_inference(self, X, w, relaxed=None, constraints=None): # default implementation of batch inference if constraints: - return [self.inference(x, w, relaxed=relaxed, constriants=c) for x,c in zip(X, constraints)] + return [self.inference(x, w, relaxed=relaxed, constraints=c) for x,c in zip(X, constraints)] return [self.inference(x, w, relaxed=relaxed) for x in X] From 4538d4f109e2b6b2418d20c76a15c61148227d4f Mon Sep 17 00:00:00 2001 From: meunier Date: Wed, 11 Jan 2017 09:47:51 +0100 Subject: [PATCH 004/155] first version with joint_feature ok --- .../node_type_edge_feature_graph_crf.py | 332 ++++++++++ pystruct/models/typed_crf.py | 264 ++++++++ .../test_node_type_edge_feature_graph_crf.py | 567 ++++++++++++++++++ 3 files changed, 1163 insertions(+) create mode 100644 pystruct/models/node_type_edge_feature_graph_crf.py create mode 100644 pystruct/models/typed_crf.py create mode 100644 pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py new file mode 100644 index 00000000..7f70ac4e --- /dev/null +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -0,0 +1,332 @@ +import numpy as np + +from .typed_crf import TypedCRF + +class NodeTypeEdgeFeatureGraphCRF(TypedCRF): + """ + Pairwise CRF with features/strength associated to each edge and different types of nodes + + Pairwise potentials are asymmetric and shared over all edges of same type. + They are weighted by an edge-specific features, though. + This allows for contrast sensitive potentials or directional potentials + (using a {-1, +1} encoding of the direction for example). + + More complicated interactions are also possible, of course. + + n_types is the number of node types + + n_nodes is the number of nodes + + Nodes are given as an array of shape (n_nodes, 2). 1st columns gives the node type, second gives the index in the type. + + Node features are given as a list of n_types arrays of shape (n_type_nodes, n_type_features): + - n_type_nodes is the number of nodes of that type + - n_type_features is the number of features for this type of node + + Edges are given as an array of shape (n_edges, 3). Columns are resp.: node index, node index, edge type_type index + + Edge features are given as a list of n_types x n_types arrays of shape (n_type_type_edge, n_type_type_edge_features) + - n_type_type_edge is the number of edges of type type_type + - n_type_type_edge_features is the number of features for edge of type type_type + + An instance ``x`` is represented as a tuple ``(node, node_features, edges, edge_features)`` + + Labels ``y`` are given as array of shape (n_nodes) + + Parameters + ---------- + n_types : number of node types + + l_n_states : list of int, default=None + Number of states per type of variables. + + l_n_features : list of int, default=None + Number of features per type of node. + + a_n_edge_features: an array of shape (n_types, n_types) given the number of features as a function of the node types + + class_weight : None, or list of array-like + Class weights. If a list of array-like is passed, the Ith one must have length equal to l_n_states[i] + None means equal class weights (across node types) + + """ + def __init__(self + , n_types #how many node type? + , l_n_states #how many labels per node type? + , l_n_features #how many features per node type? + , a_n_edge_features #how many features per edge type? + , l_class_weight=None): #class_weight per node type or None or None + + #internal stuff + #how many features per node type X node type? (MUST be symmetric!) + self.a_n_edge_features = np.array(a_n_edge_features) + if self.a_n_edge_features.shape != (n_types, n_types): + raise ValueError("Expected a feature number matrix for edges of shape (%d, %d), got %s."%(n_types, n_types, self.a_n_edge_features.shape)) + self.a_n_edge_features = self.a_n_edge_features.reshape(n_types, n_types) + self._n_edge_features = self.a_n_edge_features.sum(axis=None) #total number of (edge) features + + TypedCRF.__init__(self, n_types, l_n_states, l_n_features, l_class_weight=l_class_weight) + + def _set_size_joint_feature(self): + """ + We have: + - 1 weight per node feature per label per node type + - 1 weight per edge feature per label of node1 type, per label of node2 type + """ + if self.l_n_features: + self.size_unaries = sum( n_states * n_features for n_states, n_features in zip(self.l_n_states, self.l_n_features) ) + + self.size_pairwise = 0 #detailed non-optimized computation to make things clear + for typ1,typ2 in self._iter_type_pairs(): + self.size_pairwise += self.a_n_edge_features[typ1,typ2] * self.l_n_states[typ1] * self.l_n_states[typ2] + #print "\t %d = %d x %d x %d"%(self.a_n_edge_features[typ1,typ2] * self.l_n_states[typ1] * self.l_n_states[typ2], self.a_n_edge_features[typ1,typ2] , self.l_n_states[typ1] , self.l_n_states[typ2]) + self.size_joint_feature = self.size_unaries + self.size_pairwise + + print "size = ", self.size_unaries, " + " , self.size_pairwise + + def __repr__(self): + return ("%s(n_states: %d, inference_method: %s, n_features: %d, " + "n_edge_features: %d)" + % (type(self).__name__, self.l_n_states, self.inference_method, + self.l_n_features, self.a_n_edge_features)) + + def _check_size_x(self, x): + l_edges = self._get_edges(x) + if len(l_edges) != self.n_types**2: + raise ValueError("Expected %d edge arrays"%(self.n_types**2)) + l_edge_features = self._get_edge_features(x) + if len(l_edge_features) != self.n_types**2: + raise ValueError("Expected %d edge feature arrays"%(self.n_types**2)) + + TypedCRF._check_size_x(self, x) + + #check that we have in total 1 feature vector per edge + for edges, edge_features in zip(l_edges, l_edge_features): + if edges is None or edge_features is None: + if edges is None and edge_features is None: continue + if edges is None: + raise ValueError("Empty edge array but non empty edge-feature array, for same type of edge") + else: + raise ValueError("Empty edge-feature array but non empty edge array, for same type of edge") + if edge_features.ndim != 2: + raise ValueError("Expected a 2 dimensions edge feature arrays") + if len(edges) != len(edge_features): + raise ValueError("Edge and edge feature matrices must have same size in 1st dimension") + + #check edge feature size + for typ1,typ2 in self._iter_type_pairs(): + edge_features = self._get_edge_features_by_type(x, typ1, typ2) + if edge_features is None: continue + if edge_features.shape[1] != self.a_n_edge_features[typ1,typ2]: + raise ValueError("Types %d x %d: bad number of edge features"%(typ1,typ2)) + + + def _get_edge_features(self, x, bClean=False): + if bClean: + return [ np.empty((0,0)) if o is None or len(o)==0 else o for o in x[2]] + else: + return x[2] + def _get_edge_features_by_type(self, x, typ1, typ2): + return x[2][typ1*self.n_types+typ2] + + def _get_pairwise_potentials(self, x, w): + """Computes pairwise potentials for x and w. + + Parameters + ---------- + x : tuple + Instance Representation. + + w : ndarray, shape=(size_joint_feature,) + Weight vector for CRF instance. + + Returns + ------- + pairwise : ndarray, shape=(n_states, n_states) + Pairwise weights. + """ + self._check_size_w(w) + self._check_size_x(x) + edge_features = self._get_edge_features(x) + pairwise = np.asarray(w[self.n_states * self.n_features:]) + pairwise = pairwise.reshape(self.n_edge_features, -1) + return np.dot(edge_features, pairwise).reshape( + edge_features.shape[0], self.n_states, self.n_states) + + +# def block_ravel(self, a, lij): +# """ +# Ravel the array block by block +# """ +# li, lj = zip(*lij) +# print "\t", `a` +# print "\t", li, lj +# print "\t", zip(li, li[1:]), zip(lj, lj[1:]) +# +# print "\t", zip( zip(li, li[1:]), zip(lj, lj[1:]) ) +# +# return np.hstack( [a[np.ix_(xrange(i0,i1), xrange(j0,j1))].ravel() +# for (i0, i1), (j0,j1) +# in zip( zip(li, li[1:]), zip(lj, lj[1:]) ) +# ]) + + def block_ravel(self, a, lij): + """ + Ravel the array block by block + """ + li, lj = zip(*lij) + return np.hstack( [a[i0:i1,j0:j1].ravel() + for (i0, i1), (j0,j1) + in zip( zip(li, li[1:]), zip(lj, lj[1:]) ) + ]) + + def joint_feature(self, x, y): + """Feature vector associated with instance (x, y). + + Feature representation joint_feature, such that the energy of the configuration + (x, y) and a weight vector w is given by np.dot(w, joint_feature(x, y)). + + Parameters + ---------- + x : tuple + Input representation. + + y : list of ndarrays or some tuple (internal use!) + Either y is a list of a integral ndarrays, giving a complete labeling for x. + Or it is the result of a linear programming relaxation. In this + case, ``y=(unary_marginals, pariwise_marginals)``. + + Returns + ------- + p : ndarray, shape (size_joint_feature,) + Feature vector associated with state (x, y). + + """ + + self._check_size_x(x) + self._check_size_y(x,y) + l_node_features = self._get_node_features(x) + l_edges, l_edge_features = self._get_edges(x), self._get_edge_features(x) + l_n_nodes = [len(o) for o in self._get_node_features(x, True)] + l_n_edges = [edges.shape[0] for edges in self._get_edges(x, True)] + n_nodes = sum(l_n_nodes) + n_edges = sum(l_n_edges) + + if isinstance(y, tuple): + # y is result of relaxation, tuple of unary and pairwise marginals + unary_marginals, pw = y + unary_marginals = unary_marginals.reshape(n_nodes, self._n_states) + else: + #make one hot encoding + #each type is assigned a range of columns, each starting at self._a_state_startindex_by_typ[ ] + #in the arnge column I is for state i of that type + unary_marginals = np.zeros((n_nodes, self._n_states), dtype=np.int) + i_start = 0 + print self.l_n_states, self._l_type_startindex, y + for node_features, typ_start_index, y_typ in zip(l_node_features, self._l_type_startindex, y): + if node_features is None: continue + i_stop = i_start + node_features.shape[0] +# for n_state, typ_start_index, y_typ in zip(self.l_n_states, self._l_type_startindex, y): +# i_stop = i_start + n_state + unary_marginals[ np.ogrid[i_start:i_stop] + , typ_start_index + y_typ[:] + ] = 1 + i_start = i_stop + print "--- unary_marginals \n", `unary_marginals` + + ## pairwise + #same thing, but the type of an edge is a pair of node types + pw = np.zeros((n_edges, self._n_states ** 2)) + i_start = 0 + for (typ1, typ2), edges, edgetype_start_index in zip(self._iter_type_pairs(), l_edges, self._l_edgetype_start_index): + if edges is None: continue + #we have edges from node typ1 to node typ2 + y_typ1, y_typ2 = y[typ1], y[typ2] #the labels of all nodes of those two types + #now keep only the label of the nodes of interest + y1,y2 = y_typ1[edges[:,0]], y_typ2[edges[:,1]] + #set the 1s where they should + i_stop = i_start + edges.shape[0] + pw[ np.ogrid[i_start:i_stop] + , edgetype_start_index + self.l_n_states[typ2] * y1[:] + y2[:] + ] = 1 + i_start = i_stop + print "--- pw = \n", `pw` + assert i_start == n_edges + + #UNARY + #assign the feature of each node t the right range of column according to the node type + all_node_features = np.zeros((n_nodes, self._n_features)) + i_start = 0 + for (_a_feature_slice, node_features) in zip(self._a_feature_slice_by_typ, l_node_features): + i_stop = i_start + node_features.shape[0] + all_node_features[ i_start:i_stop + , _a_feature_slice] = node_features + i_start = i_stop + assert i_start == n_nodes + print "--- all_node_features =\n", `all_node_features` + + unaries_acc = np.dot(unary_marginals.T, all_node_features) # node_states x sum_of_features matrix + print "--- unaries_acc =\n", `unaries_acc` + + #assign the edges feature to the right range of columns, depending on edge type + all_edge_features = np.zeros( (n_edges, self._n_edge_features) ) + i_start = 0 + i_col_start = 0 + for edge_features in l_edge_features: + if edge_features is None: continue + nb_edges, nb_features = edge_features.shape + i_stop = i_start + nb_edges + i_col_stop = i_col_start + nb_features + all_edge_features[ i_start:i_stop + , i_col_start:i_col_stop ] = edge_features + i_col_start = i_col_stop + i_start = i_stop + print "--- all_edge_features =\n", `all_edge_features` + + bTransp = False + if bTransp: + pairwise_acc = np.dot(all_edge_features.T, pw) # sum_of_features x edge_states + else: + pairwise_acc = np.dot(pw.T, all_edge_features) # sum_of_features x edge_states + print "--- pairwise_acc.shape = ", pairwise_acc.shape + print "--- pairwise_acc =\n", `pairwise_acc` + +# for i in self.symmetric_edge_features: +# pw_ = pw[i].reshape(self.n_states, self.n_states) +# pw[i] = (pw_ + pw_.T).ravel() / 2. +# +# for i in self.antisymmetric_edge_features: +# pw_ = pw[i].reshape(self.n_states, self.n_states) +# pw[i] = (pw_ - pw_.T).ravel() / 2. + + +# print `unaries_acc` +# print "unaries_acc.size = ", unaries_acc.size + + #we need to linearize it, while keeping only meaningful data + unaries_acc_ravelled = self.block_ravel(unaries_acc, [(0,0)]+zip(np.cumsum(self.l_n_states), np.cumsum(self.l_n_features))) + print "--- unaries_acc_ravelled =\n", `unaries_acc_ravelled` + assert len(unaries_acc_ravelled) == self.size_unaries + + L1 = np.cumsum(self.a_n_edge_features.ravel()) + L2 = np.cumsum([self.l_n_states[typ1] * self.l_n_states[typ2] for typ1, typ2 in self._iter_type_pairs() ]) + if not bTransp: + aux=L1; L1=L2; L2=aux + pairwise_acc_ravelled = self.block_ravel(pairwise_acc, [(0,0)]+zip(L1,L2)) + + print "--- pairwise_acc_ravelled =\n", `pairwise_acc_ravelled` + assert len(pairwise_acc_ravelled) == self.size_pairwise + +# print `unaries_acc_ravelled` +# print "unaries_acc_ravelled.size = ", unaries_acc_ravelled.size +# print "unaries_acc_ravelled.shape = ", unaries_acc_ravelled.shape + +# print "pairwise_acc_ravelled.size = ", pairwise_acc_ravelled.size +# print "pairwise_acc_ravelled.shape = ", pairwise_acc_ravelled.shape +# print `pairwise_acc_ravelled` + joint_feature_vector = np.hstack([unaries_acc_ravelled, pairwise_acc_ravelled]) + + assert joint_feature_vector.shape[0] == self.size_joint_feature, (joint_feature_vector.shape[0], self.size_joint_feature) + return joint_feature_vector + + diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py new file mode 100644 index 00000000..2003878f --- /dev/null +++ b/pystruct/models/typed_crf.py @@ -0,0 +1,264 @@ +import numpy as np + +from .base import StructuredModel +from ..inference import inference_dispatch, get_installed +from .utils import loss_augment_unaries +from numpy import dtype + + +class TypedCRF(StructuredModel): + """Abstract base class""" + def __init__(self + , n_types #how many node type? + , l_n_states #how many labels per node type? + , l_n_features #how many features per node type? + , l_class_weight=None): #class_weight per node type or None or None + if len(l_n_states) != n_types: + raise ValueError("Expected 1 number of states per node type.") + if l_n_features != None and len(l_n_features) != n_types: + raise ValueError("Expected 1 number pf features per node type.") + self.n_types = n_types + self.l_n_states = l_n_states + self._n_states = sum(l_n_states) #total number of states + self.l_n_features = l_n_features + self._n_features = sum(self.l_n_features) #total number of (node) features + + # check that ad3 is installed + inference_method = get_installed(['ad3']) + if not inference_method: raise Exception("ERROR: this model class requires AD3.") + self.inference_method = inference_method[0] + self.inference_calls = 0 + + #class weights: + # either we get class weights for all types of nodes, or for none of them! + if l_class_weight: + if len(l_class_weight) != self.n_types: + raise ValueError("Expected 1 class weight list per node type.") + for i, n_states in enumerate(self.l_n_states): + if len(l_class_weight[i]) != n_states: + raise ValueError("Expected 1 class weight per state per node type. Wrong for l_class_weight[%d]"%i) + + #class weights are computed by type and simply concatenated + self.class_weight = np.hstack([np.array(class_weight) for class_weight in l_class_weight]) + else: + n_things = sum(self.l_n_states) + self.class_weight = np.ones(n_things) + + self._set_size_joint_feature() + + #internal stuff + #when putting features in a single sequence, index of 1st state for type i + self._l_type_startindex = [ sum(self.l_n_states[:i]) for i in range(self.n_types)] + + #when putting states in a single sequence, index of 1st feature for type i (is at Ith position) + #we store the slice objects + self._a_feature_slice_by_typ = np.array([ slice(sum(self.l_n_features[:i]), sum(self.l_n_features[:i+1])) for i in range(self.n_types)]) + + #when putting edge states in a single sequence, index of 1st feature of an edge of type (typ1, typ2) + self._l_edgetype_start_index = [] + i_start = 0 + for typ1_n_states in self.l_n_states: + for typ2_n_states in self.l_n_states: + self._l_edgetype_start_index.append(i_start) + i_start += typ1_n_states*typ2_n_states + self._l_edgetype_start_index.append(i_start) + assert i_start == self._n_states**2 + + + def _set_size_joint_feature(self): + """ + We have: + - 1 weight per node feature per label per node type + """ + self.size_unaries = sum( n_states * n_features for n_states, n_features in zip(self.l_n_states, self.l_n_features) ) + self.size_joint_feature = self.size_unaries + + def __repr__(self): + return ("%s(n_states: %s, inference_method: %s)" + % (type(self).__name__, self.l_n_states, + self.inference_method)) + + def _check_size_x(self, x): + l_nodes = self._get_node_features(x) + + #node_features are [ i_in_typ -> features ] + l_features = self._get_node_features(x) + if len(l_features) != self.n_types: + raise ValueError("Expected one node feature array per node type.") + + for typ, typ_features in enumerate(l_features): + if typ_features.shape[1] != self.l_n_features[typ]: + raise ValueError("Expected %d features for type %d"%(self.l_n_features[typ], typ)) + + #edges + l_edges = self._get_edges(x) + for edges in l_edges: + if edges is None: continue + if edges.ndim != 2: + raise ValueError("Expected a 2 dimensions edge arrays") + if edges.shape[1] != 2: + raise ValueError("Expected 2 columns in edge arrays") + + for typ1,typ2 in self._iter_type_pairs(): + edges = self._get_edges_by_type(x, typ1, typ2) + + if edges is None or len(edges) == 0: continue + #edges should point to valid node indices + nodes1, nodes2 = edges[:,0], edges[:,1] + if min(nodes1) < 0 or min(nodes2) < 0: + raise ValueError("At least one edge points to negative and therefore invalid node index") + if max(nodes1) >= l_nodes[typ1].shape[0] or max(nodes2) > l_nodes[typ2].shape[0]: + raise ValueError("At least one edge points to non-existing node index") + + def _check_size_y(self, x, y): + + if not isinstance(y, list): + raise ValueError("Y must be a list of arrays") + + l_features = self._get_node_features(x) + + for typ, (features, y_typ) in enumerate(zip(l_features, y)): + if not isinstance(y_typ, np.ndarray): + raise ValueError("Y must be a list of arrays") + if features.shape[0] != len(y_typ): + raise ValueError("Node of type %d: Expected %d labels not %d"%(typ, features.shape[0], len(y_typ))) + + if min(y_typ) < 0 or max(y_typ) >=self.l_n_states[typ]: + raise ValueError("Type %d: Some invalid label") + + def _get_node_features(self, x, bClean=False): + if bClean: + return [ np.empty((0,0)) if node_features is None or len(node_features)==0 else node_features for node_features in x[0]] + else: + return x[0] + def _get_node_features_by_type(self, x, typ): + return x[0][typ] + def _get_edges(self, x, bClean=False): + if bClean: + return [ np.empty((0,0)) if edges is None or len(edges)==0 else edges for edges in x[1]] + else: + return x[1] + def _get_edges_by_type(self, x, typ1, typ2): + return x[1][typ1*self.n_types+typ2] + + def _iter_type_pairs(self): + for typ1 in range(self.n_types): + for typ2 in range(self.n_types): + yield (typ1, typ2) + raise StopIteration + + def loss_augmented_inference(self, x, y, w, relaxed=False, + return_energy=False): + """Loss-augmented Inference for x relative to y using parameters w. + + Finds (approximately) + armin_y_hat np.dot(w, joint_feature(x, y_hat)) + loss(y, y_hat) + using self.inference_method. + + + Parameters + ---------- + x : tuple + Instance of a graph with unary evidence. + x=(unaries, edges) + unaries are an nd-array of shape (n_nodes, n_features), + edges are an nd-array of shape (n_edges, 2) + + y : ndarray, shape (n_nodes,) + Ground truth labeling relative to which the loss + will be measured. + + w : ndarray, shape=(size_joint_feature,) + Parameters for the CRF energy function. + + relaxed : bool, default=False + Whether relaxed inference should be performed. + Only meaningful if inference method is 'lp' or 'ad3'. + By default fractional solutions are rounded. If relaxed=True, + fractional solutions are returned directly. + + return_energy : bool, default=False + Whether to return the energy of the solution (x, y) that was found. + + Returns + ------- + y_pred : ndarray or tuple + By default an inter ndarray of shape=(n_nodes) + of variable assignments for x is returned. + If ``relaxed=True`` and inference_method is ``lp`` or ``ad3``, + a tuple (unary_marginals, pairwise_marginals) + containing the relaxed inference result is returned. + unary marginals is an array of shape (n_nodes, n_states), + pairwise_marginals is an array of + shape (n_states, n_states) of accumulated pairwise marginals. + + """ + self.inference_calls += 1 + self._check_size_w(w) + unary_potentials = self._get_unary_potentials(x, w) + pairwise_potentials = self._get_pairwise_potentials(x, w) + edges = self._get_edges(x) + loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) + + return inference_dispatch(unary_potentials, pairwise_potentials, edges, + self.inference_method, relaxed=relaxed, + return_energy=return_energy) + + def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): + """Inference for x using parameters w. + + Finds (approximately) + armin_y np.dot(w, joint_feature(x, y)) + using self.inference_method. + + + Parameters + ---------- + x : tuple + Instance of a graph with unary evidence. + x=(unaries, edges) + unaries are an nd-array of shape (n_nodes, n_states), + edges are an nd-array of shape (n_edges, 2) + + w : ndarray, shape=(size_joint_feature,) + Parameters for the CRF energy function. + + relaxed : bool, default=False + Whether relaxed inference should be performed. + Only meaningful if inference method is 'lp' or 'ad3'. + By default fractional solutions are rounded. If relaxed=True, + fractional solutions are returned directly. + + return_energy : bool, default=False + Whether to return the energy of the solution (x, y) that was found. + + constraints : None or list, default=False + hard logic constraints, if any + + Returns + ------- + y_pred : ndarray or tuple + By default an inter ndarray of shape=(width, height) + of variable assignments for x is returned. + If ``relaxed=True`` and inference_method is ``lp`` or ``ad3``, + a tuple (unary_marginals, pairwise_marginals) + containing the relaxed inference result is returned. + unary marginals is an array of shape (width, height, n_states), + pairwise_marginals is an array of + shape (n_states, n_states) of accumulated pairwise marginals. + + """ + self._check_size_w(w) + self.inference_calls += 1 + unary_potentials = self._get_unary_potentials(x, w) + pairwise_potentials = self._get_pairwise_potentials(x, w) + edges = self._get_edges(x) + + if constraints: + return inference_dispatch(unary_potentials, pairwise_potentials, edges, + self.inference_method, relaxed=relaxed, + return_energy=return_energy, constraints=constraints) + else: + return inference_dispatch(unary_potentials, pairwise_potentials, edges, + self.inference_method, relaxed=relaxed, + return_energy=return_energy) \ No newline at end of file diff --git a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py new file mode 100644 index 00000000..232f1fa6 --- /dev/null +++ b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py @@ -0,0 +1,567 @@ +import pytest +import numpy as np +from numpy.testing import (assert_array_equal, assert_array_almost_equal, + assert_almost_equal, assert_equal) +from nose.tools import assert_raises + +from pystruct.models import NodeTypeEdgeFeatureGraphCRF + +from pystruct.inference.linear_programming import lp_general_graph +from pystruct.inference import compute_energy, get_installed +from pystruct.utils import make_grid_edges, edge_list_to_features +from pystruct.datasets import generate_blocks_multinomial + + + +def test_checks(): + g = NodeTypeEdgeFeatureGraphCRF( + 1 #how many node type? + , [4] #how many labels per node type? + , [3] #how many features per node type? + , np.array([[3]]) #how many features per node type X node type? + ) + + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3 ] #how many labels per node type? + , [4, 5] #how many features per node type? + , np.array([[1, 2], [2,4]]) #how many features per node type X node type? + ) + + with pytest.raises(ValueError): + g = NodeTypeEdgeFeatureGraphCRF( + 3 #how many node type? + , [2, 3 ] #how many labels per node type? + , [4, 5] #how many features per node type? + , np.array([[1, 2], [2,4]]) #how many features per node type X node type? + ) + + with pytest.raises(ValueError): + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3 ] #how many labels per node type? + , [4, 5, 3] #how many features per node type? + , np.array([[1, 2], [2,4]]) #how many features per node type X node type? + ) + + with pytest.raises(ValueError): + g = NodeTypeEdgeFeatureGraphCRF( + 3 #how many node type? + , [2, 3 ] #how many labels per node type? + , [4, 5] #how many features per node type? + , np.array([[1, 2], [2,4]]) #how many features per node type X node type? + ) + + with pytest.raises(ValueError): + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3 ] #how many labels per node type? + , [4, 5] #how many features per node type? + , np.array([[1, 2, 3], [2,3,4]]) #how many features per node type X node type? + ) + + with pytest.raises(ValueError): + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3 ] #how many labels per node type? + , [4, 5] #how many features per node type? + , np.array([[1, 2], [99,4]]) #how many features per node type X node type? + ) + +def test_debug(): + # ------------------------------------------------------------------------------------------- + print "---MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3] #how many possible labels per node type? + , [3, 4] #how many features per node type? + , np.array([ [1, 2] + , [2, 3]]) #how many features per node type X node type? + ) + + l_node_f = [ np.array([ [1,1,1], [2,2,2] ]) + , np.array([ [.11, .12, .13, .14], [.21, .22, .23, .24], [.31, .32, .33, .34]]) + ] + l_edges = [ np.array([[0, 1]]) #type 0 node 0 to type 0 node 0 + , np.array([[0, 1]]) + , None + , None + ] + l_edge_f = [ np.array([[.111]]) + , np.array([[.221, .222]]) + , None + , None + ] + + x = [l_node_f, l_edges, l_edge_f] + print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = [ np.array([1, 1]), + np.array([0, 2, 0]) + ] + print y + g.initialize(x, y) + jf = g.joint_feature(x,y) + print "joint_feature = \n", `jf` + print + assert_array_equal(jf, jf) + assert_array_almost_equal(jf + , np.array( + [ 1. , 1., 1. , 2., 2., 2. + , 0.11 , 0.12 , 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 , 0.33 , 0.34 + + , 0. , 0.111 , 0. , 0. + , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. + , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. + , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. + ])) + + +def test_joint_feature(): + + print "---SIMPLE---------------------------------------------------------------------" + g = NodeTypeEdgeFeatureGraphCRF( + 1 #how many node type? + , [4] #how many labels per node type? + , [3] #how many features per node type? + , np.array([[3]]) #how many features per node type X node type? + ) + + node_f = [ np.array([[1,1,1], + [2,2,2]]) + ] + edges = [ np.array([[0,1]]) + ] #an edge from 0 to 1 + edge_f = [ np.array([[3,3,3]]) + ] + + x = [node_f, edges, edge_f] + print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = [ np.array([1,2]) + ] +# y = np.array([1,0]) + print y + jf = g.joint_feature(x,y) + print "joint_feature = \n", `jf` + print + assert_array_equal(g.joint_feature(x,y) + , np.array([ 0., 0., 0., 1., 1.,1., 2.,2.,2., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 3.,3.,3., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0. + ]) + ) + + print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = [ np.array([0,0]) ] + print y + jf = g.joint_feature(x,y) + print "joint_feature = \n", `jf` + print + assert_array_equal(g.joint_feature(x,y) + , np.array([ 3., 3., 3., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 3.,3.,3., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0. + ]) + ) + + print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = [np.array([0,1])] + node_f = [ np.array([[1.1,1.2,1.3], [2.1,2.2,2.3]]) ] + edge_f = [ np.array([[3.1,3.2,3.3]]) ] + x = [node_f, edges, edge_f] + assert_array_equal(g.joint_feature(x,y) + , np.array([ 1.1,1.2,1.3, 2.1,2.2,2.3, 0.,0.,0., 0.,0.,0., + 0.,0.,0., 3.1,3.2,3.3, 0.,0.,0., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0. + ]) + ) + print "---SIMPLE + 2nd EDGE--------------------------------------------------------" + node_f = [ np.array([ [1,1,1] + , [2,2,2]]) ] + edges = [ np.array( [[0,1], #an edge from 0 to 1 + [0,0] #an edge from 0 to 0 + ]) ] + edge_f = [ np.array([ + [3,3,3], + [4,4,4] + ]) ] + x = [node_f, edges, edge_f] + print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = [ np.array([1,2]) ] + print y + print "joint_feature = \n", `g.joint_feature(x,y)` + print + assert_array_equal(g.joint_feature(x,y) + , np.array([ 0., 0., 0., 1., 1.,1., 2.,2.,2., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 0.,0.,0., 4.,4.,4., 3.,3.,3., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0. + ]) + ) + print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = [ np.array([0,0])] + print y + print "joint_feature = \n", `g.joint_feature(x,y)` + print + assert_array_equal(g.joint_feature(x,y) + , np.array([ 3., 3., 3., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 7.,7.,7., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., + 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0. + ]) + ) + +def test_joint_feature2(): + + # ------------------------------------------------------------------------------------------- + print "---MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3] #how many labels per node type? + , [3, 4] #how many features per node type? + , np.array([ [1, 2] + , [2, 3]]) #how many features per node type X node type? + ) + +# nodes = np.array( [[0,0], [0,1], [1, 0], [1, 1], [1, 2]] ) + node_f = [ np.array([ [1,1,1], [2,2,2] ]) + , np.array([ [.11, .12, .13, .14], [.21, .22, .23, .24], [.31, .32, .33, .34]]) + ] + edges = [ np.array( [ [0,1] #an edge from 0 to 1 + ]) + , np.array( [ + [0,0] #an edge from typ0:0 to typ1:0 + ]) + , None + , None + ] + edge_f = [ np.array([[.111]]) + , np.array([[.221, .222]]) + , None + , None + ] + + x = [node_f, edges, edge_f] + print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = [ np.array([0, 0]) + , np.array([0, 0, 0]) + ] + print y + jf = g.joint_feature(x,y) + print "joint_feature = \n", `jf` + print + assert_array_equal(jf, jf) + assert_array_almost_equal(jf + , np.array( + [ 3. , 3., 3. , 0., 0., 0. + , 0.63 , 0.66 , 0.69 , 0.72 , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. + + , 0.111 , 0. , 0. , 0. + , 0.221,0.222 , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. + , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. + , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. + ])) + + print "---MORE COMPLEX GRAPH :) -- BIS -------------------------------------------------------------------" + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3] #how many labels per node type? + , [3, 4] #how many features per node type? + , np.array([ [1, 2] + , [2, 3]]) #how many features per node type X node type? + ) + + node_f = [ np.array([ [1,1,1], [2,2,2] ]) + , np.array([ [.11, .12, .13, .14], [.21, .22, .23, .24], [.31, .32, .33, .34]]) + ] + edges = [ np.array( [ [0,1]] ), #an edge from 0 to 1 + np.array( [ [0,2]] ) #an edge from 0 to 2 + , None, None + ] + edge_f = [ np.array([[.111]]) + , np.array([[.221, .222]]) + , None + , None + ] + + x = [ node_f, edges, edge_f] + print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = [np.array([0, 1]), + np.array([0, 1, 2])] + print y + jf = g.joint_feature(x,y) + print "joint_feature = \n", `jf` + print + assert_array_equal(jf, jf) + assert_array_almost_equal(jf + , np.array( + [ 1. , 1., 1. , 2., 2., 2. + , 0.11 , 0.12 , 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 , 0.33 , 0.34 + + , 0. , 0.111 , 0. , 0. + , 0.,0. , 0.,0. , 0.221,0.222 , 0.,0. , 0.,0. , 0.,0. + , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0., 0.,0. + , 0. ,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. + ])) + print "MORE COMPLEX GRAPH :) -- BIS OK" + print "--- REORDERED MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" + node_f = [ np.array([ [2,2,2], [1,1,1] ]) + , np.array([ [.31, .32, .33, .34], [.11, .12, .13, .14], [.21, .22, .23, .24]]) + ] + edges = [ np.array( [ [1, 0]] ), + np.array( [ [1,0]] ) #an edge from 0 to 2 + , None, None + ] + edge_f = [ np.array([[.111]]) + , np.array([[.221, .222]]) + , None + , None + ] + + x = [ node_f, edges, edge_f] + print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = [np.array([1, 0]), + np.array([2, 0, 1])] + print y + jf = g.joint_feature(x,y) + print "joint_feature = \n", `jf` + print + assert_array_equal(jf, jf) + assert_array_almost_equal(jf + , np.array( + [ 1. , 1., 1. , 2., 2., 2. + , 0.11 , 0.12 , 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 , 0.33 , 0.34 + + , 0. , 0.111 , 0. , 0. + , 0.,0. , 0.,0. , 0.221,0.222 , 0.,0. , 0.,0. , 0.,0. + , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0., 0.,0. + , 0. ,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. + ])) + + + + + + +if __name__ == "__main__": + #test_debug() + test_joint_feature() + test_joint_feature2() + +""" +def test_initialization(): + X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1) + x, y = X[0], Y[0] + n_states = x.shape[-1] + + edge_list = make_grid_edges(x, 4, return_lists=True) + edges = np.vstack(edge_list) + + edge_features = edge_list_to_features(edge_list) + x = (x.reshape(-1, n_states), edges, edge_features) + y = y.ravel() + crf = EdgeFeatureGraphCRF() + crf.initialize([x], [y]) + assert_equal(crf.n_edge_features, 2) + assert_equal(crf.n_features, 3) + assert_equal(crf.n_states, 3) + + crf = EdgeFeatureGraphCRF(n_states=3, + n_features=3, + n_edge_features=2) + # no-op + crf.initialize([x], [y]) + + crf = EdgeFeatureGraphCRF(n_states=4, + n_edge_features=2) + # incompatible + assert_raises(ValueError, crf.initialize, X=[x], Y=[y]) + + +def test_inference(): + # Test inference with different weights in different directions + + X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1) + x, y = X[0], Y[0] + n_states = x.shape[-1] + + edge_list = make_grid_edges(x, 4, return_lists=True) + edges = np.vstack(edge_list) + + pw_horz = -1 * np.eye(n_states) + xx, yy = np.indices(pw_horz.shape) + # linear ordering constraint horizontally + pw_horz[xx > yy] = 1 + + # high cost for unequal labels vertically + pw_vert = -1 * np.eye(n_states) + pw_vert[xx != yy] = 1 + pw_vert *= 10 + + # generate edge weights + edge_weights_horizontal = np.repeat(pw_horz[np.newaxis, :, :], + edge_list[0].shape[0], axis=0) + edge_weights_vertical = np.repeat(pw_vert[np.newaxis, :, :], + edge_list[1].shape[0], axis=0) + edge_weights = np.vstack([edge_weights_horizontal, edge_weights_vertical]) + + # do inference + res = lp_general_graph(-x.reshape(-1, n_states), edges, edge_weights) + + edge_features = edge_list_to_features(edge_list) + x = (x.reshape(-1, n_states), edges, edge_features) + y = y.ravel() + + for inference_method in get_installed(["lp", "ad3"]): + # same inference through CRF inferface + crf = EdgeFeatureGraphCRF(inference_method=inference_method) + crf.initialize([x], [y]) + w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) + y_pred = crf.inference(x, w, relaxed=True) + if isinstance(y_pred, tuple): + # ad3 produces an integer result if it found the exact solution + assert_array_almost_equal(res[1], y_pred[1]) + assert_array_almost_equal(res[0], y_pred[0].reshape(-1, n_states)) + assert_array_equal(y, np.argmax(y_pred[0], axis=-1)) + + for inference_method in get_installed(["lp", "ad3", "qpbo"]): + # again, this time discrete predictions only + crf = EdgeFeatureGraphCRF(n_states=3, + inference_method=inference_method, + n_edge_features=2) + crf.initialize([x], [y]) + w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) + y_pred = crf.inference(x, w, relaxed=False) + assert_array_equal(y, y_pred) + + +def test_joint_feature_discrete(): + X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1) + x, y = X[0], Y[0] + edge_list = make_grid_edges(x, 4, return_lists=True) + edges = np.vstack(edge_list) + edge_features = edge_list_to_features(edge_list) + x = (x.reshape(-1, 3), edges, edge_features) + y_flat = y.ravel() + for inference_method in get_installed(["lp", "ad3", "qpbo"]): + crf = EdgeFeatureGraphCRF(inference_method=inference_method) + crf.initialize([x], [y_flat]) + joint_feature_y = crf.joint_feature(x, y_flat) + assert_equal(joint_feature_y.shape, (crf.size_joint_feature,)) + # first horizontal, then vertical + # we trust the unaries ;) + pw_joint_feature_horz, pw_joint_feature_vert = joint_feature_y[crf.n_states * + crf.n_features:].reshape( + 2, crf.n_states, crf.n_states) + xx, yy = np.indices(y.shape) + assert_array_equal(pw_joint_feature_vert, np.diag([9 * 4, 9 * 4, 9 * 4])) + vert_joint_feature = np.diag([10 * 3, 10 * 3, 10 * 3]) + vert_joint_feature[0, 1] = 10 + vert_joint_feature[1, 2] = 10 + assert_array_equal(pw_joint_feature_horz, vert_joint_feature) + + +def test_joint_feature_continuous(): + # FIXME + # first make perfect prediction, including pairwise part + X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1) + x, y = X[0], Y[0] + n_states = x.shape[-1] + edge_list = make_grid_edges(x, 4, return_lists=True) + edges = np.vstack(edge_list) + edge_features = edge_list_to_features(edge_list) + x = (x.reshape(-1, 3), edges, edge_features) + y = y.ravel() + + pw_horz = -1 * np.eye(n_states) + xx, yy = np.indices(pw_horz.shape) + # linear ordering constraint horizontally + pw_horz[xx > yy] = 1 + + # high cost for unequal labels vertically + pw_vert = -1 * np.eye(n_states) + pw_vert[xx != yy] = 1 + pw_vert *= 10 + + # create crf, assemble weight, make prediction + for inference_method in get_installed(["lp", "ad3"]): + crf = EdgeFeatureGraphCRF(inference_method=inference_method) + w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) + crf.initialize([x], [y]) + y_pred = crf.inference(x, w, relaxed=True) + + # compute joint_feature for prediction + joint_feature_y = crf.joint_feature(x, y_pred) + assert_equal(joint_feature_y.shape, (crf.size_joint_feature,)) + # FIXME + # first horizontal, then vertical + # we trust the unaries ;) + #pw_joint_feature_horz, pw_joint_feature_vert = joint_feature_y[crf.n_states * + #crf.n_features:].reshape(2, + #crf.n_states, + #crf.n_states) + + +def test_energy_continuous(): + # make sure that energy as computed by ssvm is the same as by lp + np.random.seed(0) + for inference_method in get_installed(["lp", "ad3"]): + found_fractional = False + crf = EdgeFeatureGraphCRF(n_states=3, + inference_method=inference_method, + n_edge_features=2, n_features=3) + while not found_fractional: + x = np.random.normal(size=(7, 8, 3)) + edge_list = make_grid_edges(x, 4, return_lists=True) + edges = np.vstack(edge_list) + edge_features = edge_list_to_features(edge_list) + x = (x.reshape(-1, 3), edges, edge_features) + + unary_params = np.random.normal(size=(3, 3)) + pw1 = np.random.normal(size=(3, 3)) + pw2 = np.random.normal(size=(3, 3)) + w = np.hstack([unary_params.ravel(), pw1.ravel(), pw2.ravel()]) + res, energy = crf.inference(x, w, relaxed=True, return_energy=True) + found_fractional = np.any(np.max(res[0], axis=-1) != 1) + + joint_feature = crf.joint_feature(x, res) + energy_svm = np.dot(joint_feature, w) + + assert_almost_equal(energy, -energy_svm) + + +def test_energy_discrete(): + for inference_method in get_installed(["qpbo", "ad3"]): + crf = EdgeFeatureGraphCRF(n_states=3, + inference_method=inference_method, + n_edge_features=2, n_features=3) + for i in range(10): + x = np.random.normal(size=(7, 8, 3)) + edge_list = make_grid_edges(x, 4, return_lists=True) + edges = np.vstack(edge_list) + edge_features = edge_list_to_features(edge_list) + x = (x.reshape(-1, 3), edges, edge_features) + + unary_params = np.random.normal(size=(3, 3)) + pw1 = np.random.normal(size=(3, 3)) + pw2 = np.random.normal(size=(3, 3)) + w = np.hstack([unary_params.ravel(), pw1.ravel(), pw2.ravel()]) + y_hat = crf.inference(x, w, relaxed=False) + energy = compute_energy(crf._get_unary_potentials(x, w), + crf._get_pairwise_potentials(x, w), edges, + y_hat) + + joint_feature = crf.joint_feature(x, y_hat) + energy_svm = np.dot(joint_feature, w) + + assert_almost_equal(energy, energy_svm) + + +""" \ No newline at end of file From 5a12ff6396ac3961d74895d5bf975c5b76d0a5a0 Mon Sep 17 00:00:00 2001 From: meunier Date: Wed, 11 Jan 2017 09:48:15 +0100 Subject: [PATCH 005/155] forgot to commit __init__ --- pystruct/models/__init__.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pystruct/models/__init__.py b/pystruct/models/__init__.py index d1632d4f..00ebe47f 100644 --- a/pystruct/models/__init__.py +++ b/pystruct/models/__init__.py @@ -9,9 +9,11 @@ from .unstructured_svm import BinaryClf, MultiClassClf from .multilabel_svm import MultiLabelClf from .edge_feature_graph_crf import EdgeFeatureGraphCRF +from .node_type_edge_feature_graph_crf import NodeTypeEdgeFeatureGraphCRF __all__ = ["StructuredModel", "CRF", "GridCRF", "GraphCRF", "DirectionalGridCRF", "BinaryClf", "LatentGridCRF", "LatentDirectionalGridCRF", "MultiClassClf", "LatentGraphCRF", "MultiLabelClf", "ChainCRF", "LatentNodeCRF", "EdgeFeatureGraphCRF", - "EdgeFeatureLatentNodeCRF"] + "EdgeFeatureLatentNodeCRF", "NodeTypeEdgeFeatureGraphCRF", + "NodeTypeEdgeFeatureGraphCRF"] From 56f1e68a67f7a0dc9a690c9bbef6d584645a6c22 Mon Sep 17 00:00:00 2001 From: meunier Date: Wed, 11 Jan 2017 10:00:33 +0100 Subject: [PATCH 006/155] cosmetic --- .../node_type_edge_feature_graph_crf.py | 86 ++++++++----------- .../test_node_type_edge_feature_graph_crf.py | 2 + 2 files changed, 38 insertions(+), 50 deletions(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index 7f70ac4e..49f7b936 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -13,25 +13,6 @@ class NodeTypeEdgeFeatureGraphCRF(TypedCRF): More complicated interactions are also possible, of course. - n_types is the number of node types - - n_nodes is the number of nodes - - Nodes are given as an array of shape (n_nodes, 2). 1st columns gives the node type, second gives the index in the type. - - Node features are given as a list of n_types arrays of shape (n_type_nodes, n_type_features): - - n_type_nodes is the number of nodes of that type - - n_type_features is the number of features for this type of node - - Edges are given as an array of shape (n_edges, 3). Columns are resp.: node index, node index, edge type_type index - - Edge features are given as a list of n_types x n_types arrays of shape (n_type_type_edge, n_type_type_edge_features) - - n_type_type_edge is the number of edges of type type_type - - n_type_type_edge_features is the number of features for edge of type type_type - - An instance ``x`` is represented as a tuple ``(node, node_features, edges, edge_features)`` - - Labels ``y`` are given as array of shape (n_nodes) Parameters ---------- @@ -49,7 +30,29 @@ class NodeTypeEdgeFeatureGraphCRF(TypedCRF): Class weights. If a list of array-like is passed, the Ith one must have length equal to l_n_states[i] None means equal class weights (across node types) + + X and Y + ------- + Node features are given as a list of n_types arrays of shape (n_type_nodes, n_type_features): + - n_type_nodes is the number of nodes of that type + - n_type_features is the number of features for this type of node + + Edges are given as a list of n_types x n_types arrays of shape (n_type_edges, 2). + Columns are resp.: node index (in corresponding node type), node index (in corresponding node type) + + Edge features are given as a list of n_types x n_types arrays of shape (n_type_type_edge, n_type_type_edge_features) + - n_type_type_edge is the number of edges of type type_type + - n_type_type_edge_features is the number of features for edge of type type_type + + An instance ``X`` is represented as a tuple ``([node_features, ..], [edges, ..], [edge_features, ..])`` + + Labels ``Y`` are given as a list of array of shape (n_type_nodes) + """ + + #do we transpose the pairwise as done in original pystruct or not? (False for pytest...) + bPW_std = True + def __init__(self , n_types #how many node type? , l_n_states #how many labels per node type? @@ -82,7 +85,7 @@ def _set_size_joint_feature(self): #print "\t %d = %d x %d x %d"%(self.a_n_edge_features[typ1,typ2] * self.l_n_states[typ1] * self.l_n_states[typ2], self.a_n_edge_features[typ1,typ2] , self.l_n_states[typ1] , self.l_n_states[typ2]) self.size_joint_feature = self.size_unaries + self.size_pairwise - print "size = ", self.size_unaries, " + " , self.size_pairwise + #print "size = ", self.size_unaries, " + " , self.size_pairwise def __repr__(self): return ("%s(n_states: %d, inference_method: %s, n_features: %d, " @@ -153,23 +156,6 @@ def _get_pairwise_potentials(self, x, w): return np.dot(edge_features, pairwise).reshape( edge_features.shape[0], self.n_states, self.n_states) - -# def block_ravel(self, a, lij): -# """ -# Ravel the array block by block -# """ -# li, lj = zip(*lij) -# print "\t", `a` -# print "\t", li, lj -# print "\t", zip(li, li[1:]), zip(lj, lj[1:]) -# -# print "\t", zip( zip(li, li[1:]), zip(lj, lj[1:]) ) -# -# return np.hstack( [a[np.ix_(xrange(i0,i1), xrange(j0,j1))].ravel() -# for (i0, i1), (j0,j1) -# in zip( zip(li, li[1:]), zip(lj, lj[1:]) ) -# ]) - def block_ravel(self, a, lij): """ Ravel the array block by block @@ -222,7 +208,7 @@ def joint_feature(self, x, y): #in the arnge column I is for state i of that type unary_marginals = np.zeros((n_nodes, self._n_states), dtype=np.int) i_start = 0 - print self.l_n_states, self._l_type_startindex, y + #print self.l_n_states, self._l_type_startindex, y for node_features, typ_start_index, y_typ in zip(l_node_features, self._l_type_startindex, y): if node_features is None: continue i_stop = i_start + node_features.shape[0] @@ -232,7 +218,7 @@ def joint_feature(self, x, y): , typ_start_index + y_typ[:] ] = 1 i_start = i_stop - print "--- unary_marginals \n", `unary_marginals` + #print "--- unary_marginals \n", `unary_marginals` ## pairwise #same thing, but the type of an edge is a pair of node types @@ -250,7 +236,7 @@ def joint_feature(self, x, y): , edgetype_start_index + self.l_n_states[typ2] * y1[:] + y2[:] ] = 1 i_start = i_stop - print "--- pw = \n", `pw` + #print "--- pw = \n", `pw` assert i_start == n_edges #UNARY @@ -263,10 +249,10 @@ def joint_feature(self, x, y): , _a_feature_slice] = node_features i_start = i_stop assert i_start == n_nodes - print "--- all_node_features =\n", `all_node_features` + #print "--- all_node_features =\n", `all_node_features` unaries_acc = np.dot(unary_marginals.T, all_node_features) # node_states x sum_of_features matrix - print "--- unaries_acc =\n", `unaries_acc` + #print "--- unaries_acc =\n", `unaries_acc` #assign the edges feature to the right range of columns, depending on edge type all_edge_features = np.zeros( (n_edges, self._n_edge_features) ) @@ -281,15 +267,15 @@ def joint_feature(self, x, y): , i_col_start:i_col_stop ] = edge_features i_col_start = i_col_stop i_start = i_stop - print "--- all_edge_features =\n", `all_edge_features` + #print "--- all_edge_features =\n", `all_edge_features` - bTransp = False - if bTransp: + if self.bPW_std: + #as in edge_feature_graph_crf pairwise_acc = np.dot(all_edge_features.T, pw) # sum_of_features x edge_states else: pairwise_acc = np.dot(pw.T, all_edge_features) # sum_of_features x edge_states - print "--- pairwise_acc.shape = ", pairwise_acc.shape - print "--- pairwise_acc =\n", `pairwise_acc` + #print "--- pairwise_acc.shape = ", pairwise_acc.shape + #print "--- pairwise_acc =\n", `pairwise_acc` # for i in self.symmetric_edge_features: # pw_ = pw[i].reshape(self.n_states, self.n_states) @@ -305,16 +291,16 @@ def joint_feature(self, x, y): #we need to linearize it, while keeping only meaningful data unaries_acc_ravelled = self.block_ravel(unaries_acc, [(0,0)]+zip(np.cumsum(self.l_n_states), np.cumsum(self.l_n_features))) - print "--- unaries_acc_ravelled =\n", `unaries_acc_ravelled` + #print "--- unaries_acc_ravelled =\n", `unaries_acc_ravelled` assert len(unaries_acc_ravelled) == self.size_unaries L1 = np.cumsum(self.a_n_edge_features.ravel()) L2 = np.cumsum([self.l_n_states[typ1] * self.l_n_states[typ2] for typ1, typ2 in self._iter_type_pairs() ]) - if not bTransp: + if not self.bPW_std: aux=L1; L1=L2; L2=aux pairwise_acc_ravelled = self.block_ravel(pairwise_acc, [(0,0)]+zip(L1,L2)) - print "--- pairwise_acc_ravelled =\n", `pairwise_acc_ravelled` + #print "--- pairwise_acc_ravelled =\n", `pairwise_acc_ravelled` assert len(pairwise_acc_ravelled) == self.size_pairwise # print `unaries_acc_ravelled` diff --git a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py index 232f1fa6..6ffef96d 100644 --- a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py +++ b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py @@ -6,6 +6,8 @@ from pystruct.models import NodeTypeEdgeFeatureGraphCRF +NodeTypeEdgeFeatureGraphCRF.bPW_std = False + from pystruct.inference.linear_programming import lp_general_graph from pystruct.inference import compute_energy, get_installed from pystruct.utils import make_grid_edges, edge_list_to_features From 18fab2aa7ec9deda61b7cfb22f157c50ac65fe12 Mon Sep 17 00:00:00 2001 From: meunier Date: Wed, 11 Jan 2017 17:24:53 +0100 Subject: [PATCH 007/155] joint_feature, inference are ok, as per AM tests that use single type graphs --- .../node_type_edge_feature_graph_crf.py | 73 +++- pystruct/models/typed_crf.py | 85 +++- .../test_node_type_edge_feature_graph_crf.py | 387 +++++++++++------- 3 files changed, 361 insertions(+), 184 deletions(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index 49f7b936..9403e057 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -50,9 +50,6 @@ class NodeTypeEdgeFeatureGraphCRF(TypedCRF): """ - #do we transpose the pairwise as done in original pystruct or not? (False for pytest...) - bPW_std = True - def __init__(self , n_types #how many node type? , l_n_states #how many labels per node type? @@ -66,6 +63,9 @@ def __init__(self if self.a_n_edge_features.shape != (n_types, n_types): raise ValueError("Expected a feature number matrix for edges of shape (%d, %d), got %s."%(n_types, n_types, self.a_n_edge_features.shape)) self.a_n_edge_features = self.a_n_edge_features.reshape(n_types, n_types) + if not (self.a_n_edge_features == self.a_n_edge_features.T).all(): + raise ValueError("Expected a symmetric array of edge feature numbers") + self._n_edge_features = self.a_n_edge_features.sum(axis=None) #total number of (edge) features TypedCRF.__init__(self, n_types, l_n_states, l_n_features, l_class_weight=l_class_weight) @@ -123,7 +123,6 @@ def _check_size_x(self, x): if edge_features.shape[1] != self.a_n_edge_features[typ1,typ2]: raise ValueError("Types %d x %d: bad number of edge features"%(typ1,typ2)) - def _get_edge_features(self, x, bClean=False): if bClean: return [ np.empty((0,0)) if o is None or len(o)==0 else o for o in x[2]] @@ -132,6 +131,7 @@ def _get_edge_features(self, x, bClean=False): def _get_edge_features_by_type(self, x, typ1, typ2): return x[2][typ1*self.n_types+typ2] + def _get_pairwise_potentials(self, x, w): """Computes pairwise potentials for x and w. @@ -150,13 +150,50 @@ def _get_pairwise_potentials(self, x, w): """ self._check_size_w(w) self._check_size_x(x) - edge_features = self._get_edge_features(x) - pairwise = np.asarray(w[self.n_states * self.n_features:]) - pairwise = pairwise.reshape(self.n_edge_features, -1) - return np.dot(edge_features, pairwise).reshape( - edge_features.shape[0], self.n_states, self.n_states) + # edge_features = self._get_edge_features(x) + # pairwise = np.asarray(w[self.n_states * self.n_features:]) + # pairwise = pairwise.reshape(self.n_edge_features, -1) + # return np.dot(edge_features, pairwise).reshape( + # edge_features.shape[0], self.n_states, self.n_states) + + l_edge_features = self._get_edge_features(x) + n_edges_total = sum(0 if e is None else e.shape[0] for e in l_edge_features) + wpw = w[self.size_unaries:] + a_edges_states_states = np.zeros((n_edges_total, self._n_states, self._n_states), dtype=w.dtype) + + i_w, i_edges, i_states1, i_states2 = 0, 0, 0, 0 +# for (typ1, typ2), edge_features, edgetype_start_index in zip(self._iter_type_pairs(), l_edge_features, self._l_edgetype_start_index): + for (typ1, typ2), edge_features in zip(self._iter_type_pairs(), l_edge_features): + if edge_features is None: continue + + n_edges, n_features = edge_features.shape + n_states1 = self.l_n_states[typ1] + n_states2 = self.l_n_states[typ2] + i_w_stop = i_w + self.a_n_edge_features[typ1,typ2] * n_states1 * n_states2 + i_edges_stop = i_edges + n_edges + i_states1_stop = i_states1 + n_states1 + i_states2_stop = i_states2 + n_states2 + +# print "wpw ", wpw.size, wpw.shape +# print "n_features ", n_features +# print edgetype_start_index,edgetype_start_index+n_states1*n_states2 +# print wpw[edgetype_start_index:edgetype_start_index+n_states1*n_states2] + pw_typ_typ = wpw[i_w:i_w_stop].reshape(n_features, -1) # n_states1*n_states2 x nb_feat +# print "pw_typ_typ ", pw_typ_typ + pot_typ_typ = np.dot(edge_features, pw_typ_typ).reshape(n_edges, n_states1, n_states2) +# print "pot_typ_typ ", pot_typ_typ +# print (i_edges,i_edges_stop) +# print (i_states1,i_states1_stop) +# print (i_states2,i_states2_stop) +# print a_edges_states_states.shape +# print pot_typ_typ.shape + a_edges_states_states[ i_edges:i_edges_stop, i_states1:i_states1_stop , i_states2:i_states2_stop ] = pot_typ_typ + + i_w, i_edges, i_states1, i_states2 = i_w_stop, i_edges_stop, i_states1_stop, i_states2_stop + + return a_edges_states_states.reshape(n_edges_total, self._n_states, self._n_states) - def block_ravel(self, a, lij): + def _block_ravel(self, a, lij): """ Ravel the array block by block """ @@ -190,7 +227,7 @@ def joint_feature(self, x, y): """ self._check_size_x(x) - self._check_size_y(x,y) + if not isinstance(y, tuple): self._check_size_y(x,y) l_node_features = self._get_node_features(x) l_edges, l_edge_features = self._get_edges(x), self._get_edge_features(x) l_n_nodes = [len(o) for o in self._get_node_features(x, True)] @@ -269,11 +306,8 @@ def joint_feature(self, x, y): i_start = i_stop #print "--- all_edge_features =\n", `all_edge_features` - if self.bPW_std: - #as in edge_feature_graph_crf - pairwise_acc = np.dot(all_edge_features.T, pw) # sum_of_features x edge_states - else: - pairwise_acc = np.dot(pw.T, all_edge_features) # sum_of_features x edge_states + pairwise_acc = np.dot(all_edge_features.T, pw) # sum_of_features x edge_states + #easier to read... :-( pairwise_acc = np.dot(pw.T, all_edge_features) # sum_of_features x edge_states #print "--- pairwise_acc.shape = ", pairwise_acc.shape #print "--- pairwise_acc =\n", `pairwise_acc` @@ -290,15 +324,14 @@ def joint_feature(self, x, y): # print "unaries_acc.size = ", unaries_acc.size #we need to linearize it, while keeping only meaningful data - unaries_acc_ravelled = self.block_ravel(unaries_acc, [(0,0)]+zip(np.cumsum(self.l_n_states), np.cumsum(self.l_n_features))) + unaries_acc_ravelled = self._block_ravel(unaries_acc, [(0,0)]+zip(np.cumsum(self.l_n_states), np.cumsum(self.l_n_features))) #print "--- unaries_acc_ravelled =\n", `unaries_acc_ravelled` assert len(unaries_acc_ravelled) == self.size_unaries L1 = np.cumsum(self.a_n_edge_features.ravel()) L2 = np.cumsum([self.l_n_states[typ1] * self.l_n_states[typ2] for typ1, typ2 in self._iter_type_pairs() ]) - if not self.bPW_std: - aux=L1; L1=L2; L2=aux - pairwise_acc_ravelled = self.block_ravel(pairwise_acc, [(0,0)]+zip(L1,L2)) +# easier to read... aux=L1; L1=L2; L2=aux + pairwise_acc_ravelled = self._block_ravel(pairwise_acc, [(0,0)]+zip(L1,L2)) #print "--- pairwise_acc_ravelled =\n", `pairwise_acc_ravelled` assert len(pairwise_acc_ravelled) == self.size_pairwise diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index 2003878f..a8be1b83 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -80,7 +80,7 @@ def __repr__(self): def _check_size_x(self, x): l_nodes = self._get_node_features(x) - + #node_features are [ i_in_typ -> features ] l_features = self._get_node_features(x) if len(l_features) != self.n_types: @@ -112,7 +112,7 @@ def _check_size_x(self, x): def _check_size_y(self, x, y): - if not isinstance(y, list): + if not isinstance(y, list): raise ValueError("Y must be a list of arrays") l_features = self._get_node_features(x) @@ -138,6 +138,25 @@ def _get_edges(self, x, bClean=False): return [ np.empty((0,0)) if edges is None or len(edges)==0 else edges for edges in x[1]] else: return x[1] + def _index_all_edges(self, x): + """ + return all edges as a single 2-column matrix, taking care of indices!! + """ + n_edges_total = sum(0 if e is None else e.shape[0] for e in x[1]) + all_edges = np.zeros((n_edges_total, 2), dtype=np.int32) + + node_offset_by_typ = np.cumsum([0]+[0 if n is None else n.shape[0] for n in x[0]]) + i_start = 0 + for edges, (typ1, typ2) in zip(x[1], self._iter_type_pairs()): + if edges is None: continue + n_edges = edges.shape[0] + i_stop = i_start + n_edges + all_edges[i_start:i_stop, 0] = edges[:,0] + node_offset_by_typ[typ1] + all_edges[i_start:i_stop, 1] = edges[:,1] + node_offset_by_typ[typ2] + i_start = i_stop + return all_edges + + def _get_edges_by_type(self, x, typ1, typ2): return x[1][typ1*self.n_types+typ2] @@ -146,7 +165,52 @@ def _iter_type_pairs(self): for typ2 in range(self.n_types): yield (typ1, typ2) raise StopIteration - + + def _get_unary_potentials(self, x, w): + """Computes unary potentials for x and w. + + Parameters + ---------- + x : tuple + Instance Representation. + + w : ndarray, shape=(size_joint_feature,) + Weight vector for CRF instance. + + Returns + ------- + unary : ndarray, shape=(sum_over_types(n_states_of_type) + Unary weights. + """ + self._check_size_w(w) + self._check_size_x(x) + l_node_features = self._get_node_features(x) + #code for single type CRF + # unary_params = w[:self.n_states * self.n_features].reshape( + # self.n_states, self.n_features) + # return np.dot(features, unary_params.T) + + #self.size_unaries == sum( n_states * n_features for n_states, n_features in zip(self.l_n_states, self.l_n_features) ) + w_unaries = w[:self.size_unaries] + a_nodes_states = np.zeros((sum(nf.shape[0] for nf in l_node_features) + , self._n_states), dtype=w.dtype) + #we work type by type and assemble the unaries + #"irrelevant" unaries (i.e. for state not applicable to a type, will get a 0 + i_w, i_nodes, i_states = 0, 0, 0 + for features, n_states, n_features in zip(l_node_features, self.l_n_states, self.l_n_features): + i_w2 = i_w + n_states*n_features #number of weights for the type + i_nodes2 = i_nodes + features.shape[0] #number of nodes of that type + i_states2 = i_states + n_states #number of state of that type + w_unaries_type = w_unaries[i_w:i_w2] #range for weights for that type + #back to "usual" code! + unary_params = w_unaries_type.reshape(n_states, n_features) + #apart that we fill a sub-part of the unaries matrix + a_nodes_states[i_nodes:i_nodes2, i_states:i_states2] = np.dot(features, unary_params.T) + i_w, i_nodes, i_states = i_w2, i_nodes2, i_states2 + + # nodes x features . features x states --> nodes x states + return a_nodes_states + def loss_augmented_inference(self, x, y, w, relaxed=False, return_energy=False): """Loss-augmented Inference for x relative to y using parameters w. @@ -197,10 +261,12 @@ def loss_augmented_inference(self, x, y, w, relaxed=False, self._check_size_w(w) unary_potentials = self._get_unary_potentials(x, w) pairwise_potentials = self._get_pairwise_potentials(x, w) - edges = self._get_edges(x) - loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) + flat_edges = self._index_all_edges(x) + flat_y = np.hstack(y) + #loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) + loss_augment_unaries(unary_potentials, flat_y, self.class_weight) - return inference_dispatch(unary_potentials, pairwise_potentials, edges, + return inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, self.inference_method, relaxed=relaxed, return_energy=return_energy) @@ -252,13 +318,14 @@ def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): self.inference_calls += 1 unary_potentials = self._get_unary_potentials(x, w) pairwise_potentials = self._get_pairwise_potentials(x, w) - edges = self._get_edges(x) + + flat_edges = self._index_all_edges(x) if constraints: - return inference_dispatch(unary_potentials, pairwise_potentials, edges, + return inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, self.inference_method, relaxed=relaxed, return_energy=return_energy, constraints=constraints) else: - return inference_dispatch(unary_potentials, pairwise_potentials, edges, + return inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, self.inference_method, relaxed=relaxed, return_energy=return_energy) \ No newline at end of file diff --git a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py index 6ffef96d..54f5b3ba 100644 --- a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py +++ b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py @@ -4,9 +4,7 @@ assert_almost_equal, assert_equal) from nose.tools import assert_raises -from pystruct.models import NodeTypeEdgeFeatureGraphCRF - -NodeTypeEdgeFeatureGraphCRF.bPW_std = False +from pystruct.models import NodeTypeEdgeFeatureGraphCRF, EdgeFeatureGraphCRF from pystruct.inference.linear_programming import lp_general_graph from pystruct.inference import compute_energy, get_installed @@ -70,7 +68,7 @@ def test_checks(): , np.array([[1, 2], [99,4]]) #how many features per node type X node type? ) -def test_debug(): +def debug_joint_feature(): # ------------------------------------------------------------------------------------------- print "---MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" g = NodeTypeEdgeFeatureGraphCRF( @@ -117,17 +115,17 @@ def test_debug(): , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. ])) - -def test_joint_feature(): - - print "---SIMPLE---------------------------------------------------------------------" + +def get_simple_graph_structure(): g = NodeTypeEdgeFeatureGraphCRF( 1 #how many node type? , [4] #how many labels per node type? , [3] #how many features per node type? , np.array([[3]]) #how many features per node type X node type? ) - + return g + +def get_simple_graph(): node_f = [ np.array([[1,1,1], [2,2,2]]) ] @@ -135,6 +133,24 @@ def test_joint_feature(): ] #an edge from 0 to 1 edge_f = [ np.array([[3,3,3]]) ] + return (node_f, edges, edge_f) + +def get_simple_graph2(): + node_f = [ np.array([ [1,1,1] + , [2,2,2]]) ] + edges = [ np.array( [[0,1], #an edge from 0 to 1 + [0,0] #an edge from 0 to 0 + ]) ] + edge_f = [ np.array([ + [3,3,3], + [4,4,4] + ]) ] + return (node_f, edges, edge_f) + +def test_joint_feature(): + + print "---SIMPLE---------------------------------------------------------------------" + g, (node_f, edges, edge_f) = get_simple_graph_structure(), get_simple_graph() x = [node_f, edges, edge_f] print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " @@ -146,12 +162,11 @@ def test_joint_feature(): print "joint_feature = \n", `jf` print assert_array_equal(g.joint_feature(x,y) - , np.array([ 0., 0., 0., 1., 1.,1., 2.,2.,2., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 3.,3.,3., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0. - ]) + , np.array([ 0., 0., 0., 1., 1., 1., 2., 2., 2., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 3., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0., 3., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 3., 0., + 0., 0., 0., 0., 0., 0., 0., 0.]) ) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " @@ -161,12 +176,11 @@ def test_joint_feature(): print "joint_feature = \n", `jf` print assert_array_equal(g.joint_feature(x,y) - , np.array([ 3., 3., 3., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 3.,3.,3., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0. - ]) + , np.array([ 3., 3., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 3., + 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 3., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0.]) ) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " @@ -174,37 +188,33 @@ def test_joint_feature(): node_f = [ np.array([[1.1,1.2,1.3], [2.1,2.2,2.3]]) ] edge_f = [ np.array([[3.1,3.2,3.3]]) ] x = [node_f, edges, edge_f] + jf = g.joint_feature(x,y) + print "joint_feature = \n", `jf` + assert_array_equal(g.joint_feature(x,y) - , np.array([ 1.1,1.2,1.3, 2.1,2.2,2.3, 0.,0.,0., 0.,0.,0., - 0.,0.,0., 3.1,3.2,3.3, 0.,0.,0., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0. - ]) + , np.array([ 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 3.1, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 3.2, 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 3.3, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. ]) ) print "---SIMPLE + 2nd EDGE--------------------------------------------------------" - node_f = [ np.array([ [1,1,1] - , [2,2,2]]) ] - edges = [ np.array( [[0,1], #an edge from 0 to 1 - [0,0] #an edge from 0 to 0 - ]) ] - edge_f = [ np.array([ - [3,3,3], - [4,4,4] - ]) ] + node_f, edges, edge_f = get_simple_graph2() + x = [node_f, edges, edge_f] print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = [ np.array([1,2]) ] print y - print "joint_feature = \n", `g.joint_feature(x,y)` + jf = g.joint_feature(x,y) + print "joint_feature = \n", `jf` print - assert_array_equal(g.joint_feature(x,y) - , np.array([ 0., 0., 0., 1., 1.,1., 2.,2.,2., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 0.,0.,0., 4.,4.,4., 3.,3.,3., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0. - ]) + assert_array_equal(jf + , np.array([ 0., 0., 0., 1., 1., 1., 2., 2., 2., 0., 0., 0., 0., + 0., 0., 0., 0., 4., 3., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 4., 3., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 4., 3., 0., + 0., 0., 0., 0., 0., 0., 0., 0.]) ) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = [ np.array([0,0])] @@ -212,12 +222,11 @@ def test_joint_feature(): print "joint_feature = \n", `g.joint_feature(x,y)` print assert_array_equal(g.joint_feature(x,y) - , np.array([ 3., 3., 3., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 7.,7.,7., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0., - 0.,0.,0., 0.,0.,0., 0.,0.,0., 0.,0.,0. - ]) + , np.array([ 3., 3., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 7., + 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 7., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 7., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0.]) ) def test_joint_feature2(): @@ -261,15 +270,15 @@ def test_joint_feature2(): print assert_array_equal(jf, jf) assert_array_almost_equal(jf - , np.array( - [ 3. , 3., 3. , 0., 0., 0. - , 0.63 , 0.66 , 0.69 , 0.72 , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. - - , 0.111 , 0. , 0. , 0. - , 0.221,0.222 , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. - , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. - , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. - ])) + , np.array([ 3. , 3. , 3. , 0. , 0. , 0. , 0.63 , 0.66 , + 0.69 , 0.72 , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0.111, 0. , 0. , 0. , 0.221, 0. , + 0. , 0. , 0. , 0. , 0.222, 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ])) print "---MORE COMPLEX GRAPH :) -- BIS -------------------------------------------------------------------" g = NodeTypeEdgeFeatureGraphCRF( @@ -303,15 +312,15 @@ def test_joint_feature2(): print assert_array_equal(jf, jf) assert_array_almost_equal(jf - , np.array( - [ 1. , 1., 1. , 2., 2., 2. - , 0.11 , 0.12 , 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 , 0.33 , 0.34 - - , 0. , 0.111 , 0. , 0. - , 0.,0. , 0.,0. , 0.221,0.222 , 0.,0. , 0.,0. , 0.,0. - , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0., 0.,0. - , 0. ,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. - ])) + , np.array([ 1. , 1. , 1. , 2. , 2. , 2. , 0.11 , 0.12 , + 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 , + 0.33 , 0.34 , 0. , 0.111, 0. , 0. , 0. , 0. , + 0.221, 0. , 0. , 0. , 0. , 0. , 0.222, 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ])) print "MORE COMPLEX GRAPH :) -- BIS OK" print "--- REORDERED MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" node_f = [ np.array([ [2,2,2], [1,1,1] ]) @@ -337,57 +346,103 @@ def test_joint_feature2(): print assert_array_equal(jf, jf) assert_array_almost_equal(jf - , np.array( - [ 1. , 1., 1. , 2., 2., 2. - , 0.11 , 0.12 , 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 , 0.33 , 0.34 - - , 0. , 0.111 , 0. , 0. - , 0.,0. , 0.,0. , 0.221,0.222 , 0.,0. , 0.,0. , 0.,0. - , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0., 0.,0. - , 0. ,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. - ])) + , np.array([ 1. , 1. , 1. , 2. , 2. , 2. , 0.11 , 0.12 , + 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 , + 0.33 , 0.34 , 0. , 0.111, 0. , 0. , 0. , 0. , + 0.221, 0. , 0. , 0. , 0. , 0. , 0.222, 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ])) - +def test_unary_potentials(): + print "---SIMPLE---------------------------------------------------------------------" + #g, (node_f, edges, edge_f) = get_simple_graph_structure(), get_simple_graph() + g = NodeTypeEdgeFeatureGraphCRF( + 1 #how many node type? + , [4] #how many labels per node type? + , [3] #how many features per node type? + , np.array([[3]]) #how many features per node type X node type? + ) + node_f = [ np.array([[1,1,1], + [2,2,2]]) + ] + edges = [ np.array([[0,1]]) + ] #an edge from 0 to 1 + edge_f = [ np.array([[3,3,3]]) + ] + x = [node_f, edges, edge_f] + print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = [ np.array([1,2]) + ] +# y = np.array([1,0]) + print y + + gref = EdgeFeatureGraphCRF(4,3,3) + xref = (node_f[0], edges[0], edge_f[0]) + wref = np.arange(gref.size_joint_feature) + potref = gref._get_unary_potentials(xref, wref) + print `potref` + + w = np.arange(g.size_joint_feature) + pot = g._get_unary_potentials(x, w) + print `pot` + assert_array_equal(pot, potref) + + pwpotref = gref._get_pairwise_potentials(xref, wref) + print `pwpotref` + pwpot = g._get_pairwise_potentials(x, w) + print `pwpot` + assert_array_equal(pwpot, pwpotref) -if __name__ == "__main__": - #test_debug() - test_joint_feature() - test_joint_feature2() +def test_inference_util(): + g = NodeTypeEdgeFeatureGraphCRF( + 3 #how many node type? + , [2, 3, 1] #how many labels per node type? + , [3, 4, 1] #how many features per node type? + , np.array([ [1, 2, 2] + , [2, 3, 2] + , [2, 2, 1]]) #how many features per node type X node type? + ) + node_f = [ np.array([ [2,2,2], [1,1,1] ]) + , np.array([ [.31, .32, .33, .34], [.11, .12, .13, .14], [.21, .22, .23, .24]]) + , np.array([ [77], [88], [99]]) + ] + edges = [ np.array( [ [1, 0]] ), + np.array( [ [1,0]] ) #an edge from 0 to 2 + , None + + , None + , None + , None + + , np.array( [[1,1]] ) + , None + , None ] + + x = [ node_f, edges, None] + + reindexed_exdges = g._index_all_edges(x) + #print `reindexed_exdges` + assert_array_equal(reindexed_exdges, + np.array( [[1,0], + [1,2], + [6,1]])) -""" -def test_initialization(): - X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1) - x, y = X[0], Y[0] - n_states = x.shape[-1] - - edge_list = make_grid_edges(x, 4, return_lists=True) - edges = np.vstack(edge_list) - - edge_features = edge_list_to_features(edge_list) - x = (x.reshape(-1, n_states), edges, edge_features) - y = y.ravel() - crf = EdgeFeatureGraphCRF() - crf.initialize([x], [y]) - assert_equal(crf.n_edge_features, 2) - assert_equal(crf.n_features, 3) - assert_equal(crf.n_states, 3) - - crf = EdgeFeatureGraphCRF(n_states=3, - n_features=3, - n_edge_features=2) - # no-op - crf.initialize([x], [y]) - - crf = EdgeFeatureGraphCRF(n_states=4, - n_edge_features=2) - # incompatible - assert_raises(ValueError, crf.initialize, X=[x], Y=[y]) - +def report_model_config(crf): + print crf.n_states + print crf.n_features + print crf.n_edge_features + def test_inference(): + """ + Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF + """ # Test inference with different weights in different directions X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1) @@ -418,13 +473,13 @@ def test_inference(): res = lp_general_graph(-x.reshape(-1, n_states), edges, edge_weights) edge_features = edge_list_to_features(edge_list) - x = (x.reshape(-1, n_states), edges, edge_features) - y = y.ravel() - - for inference_method in get_installed(["lp", "ad3"]): + x = ([x.reshape(-1, n_states)], [edges], [edge_features]) + y = [y.ravel()] + #for inference_method in get_installed(["lp", "ad3"]): + if True: # same inference through CRF inferface - crf = EdgeFeatureGraphCRF(inference_method=inference_method) - crf.initialize([x], [y]) + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) # ad3 only is supported..., inference_method=inference_method) + #crf.initialize([x], [y]) w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) y_pred = crf.inference(x, w, relaxed=True) if isinstance(y_pred, tuple): @@ -433,44 +488,47 @@ def test_inference(): assert_array_almost_equal(res[0], y_pred[0].reshape(-1, n_states)) assert_array_equal(y, np.argmax(y_pred[0], axis=-1)) - for inference_method in get_installed(["lp", "ad3", "qpbo"]): + #for inference_method in get_installed(["lp", "ad3", "qpbo"]): # again, this time discrete predictions only - crf = EdgeFeatureGraphCRF(n_states=3, - inference_method=inference_method, - n_edge_features=2) - crf.initialize([x], [y]) + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) + #crf.initialize([x], [y]) w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) y_pred = crf.inference(x, w, relaxed=False) - assert_array_equal(y, y_pred) - + assert_array_equal(y[0], y_pred) def test_joint_feature_discrete(): + """ + Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF + """ X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1) x, y = X[0], Y[0] edge_list = make_grid_edges(x, 4, return_lists=True) edges = np.vstack(edge_list) edge_features = edge_list_to_features(edge_list) - x = (x.reshape(-1, 3), edges, edge_features) + x = ([x.reshape(-1, 3)], [edges], [edge_features]) y_flat = y.ravel() - for inference_method in get_installed(["lp", "ad3", "qpbo"]): - crf = EdgeFeatureGraphCRF(inference_method=inference_method) - crf.initialize([x], [y_flat]) - joint_feature_y = crf.joint_feature(x, y_flat) + #for inference_method in get_installed(["lp", "ad3", "qpbo"]): + if True: + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) + joint_feature_y = crf.joint_feature(x, [y_flat]) assert_equal(joint_feature_y.shape, (crf.size_joint_feature,)) # first horizontal, then vertical # we trust the unaries ;) - pw_joint_feature_horz, pw_joint_feature_vert = joint_feature_y[crf.n_states * - crf.n_features:].reshape( - 2, crf.n_states, crf.n_states) - xx, yy = np.indices(y.shape) + n_states = crf.l_n_states[0] + n_features = crf.l_n_features[0] + pw_joint_feature_horz, pw_joint_feature_vert = joint_feature_y[n_states * + n_features:].reshape( + 2, n_states, n_states) assert_array_equal(pw_joint_feature_vert, np.diag([9 * 4, 9 * 4, 9 * 4])) vert_joint_feature = np.diag([10 * 3, 10 * 3, 10 * 3]) vert_joint_feature[0, 1] = 10 vert_joint_feature[1, 2] = 10 assert_array_equal(pw_joint_feature_horz, vert_joint_feature) - def test_joint_feature_continuous(): + """ + Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF + """ # FIXME # first make perfect prediction, including pairwise part X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1) @@ -479,7 +537,8 @@ def test_joint_feature_continuous(): edge_list = make_grid_edges(x, 4, return_lists=True) edges = np.vstack(edge_list) edge_features = edge_list_to_features(edge_list) - x = (x.reshape(-1, 3), edges, edge_features) + #x = (x.reshape(-1, 3), edges, edge_features) + x = ([x.reshape(-1, 3)], [edges], [edge_features]) y = y.ravel() pw_horz = -1 * np.eye(n_states) @@ -493,14 +552,18 @@ def test_joint_feature_continuous(): pw_vert *= 10 # create crf, assemble weight, make prediction - for inference_method in get_installed(["lp", "ad3"]): - crf = EdgeFeatureGraphCRF(inference_method=inference_method) +# for inference_method in get_installed(["lp", "ad3"]): +# crf = EdgeFeatureGraphCRF(inference_method=inference_method) + if True: + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) + w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) - crf.initialize([x], [y]) + #crf.initialize([x], [y]) + #report_model_config(crf) y_pred = crf.inference(x, w, relaxed=True) # compute joint_feature for prediction - joint_feature_y = crf.joint_feature(x, y_pred) + joint_feature_y = crf.joint_feature(x, [y_pred]) assert_equal(joint_feature_y.shape, (crf.size_joint_feature,)) # FIXME # first horizontal, then vertical @@ -510,21 +573,20 @@ def test_joint_feature_continuous(): #crf.n_states, #crf.n_states) - def test_energy_continuous(): # make sure that energy as computed by ssvm is the same as by lp np.random.seed(0) - for inference_method in get_installed(["lp", "ad3"]): + #for inference_method in get_installed(["lp", "ad3"]): + if True: found_fractional = False - crf = EdgeFeatureGraphCRF(n_states=3, - inference_method=inference_method, - n_edge_features=2, n_features=3) + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) + while not found_fractional: x = np.random.normal(size=(7, 8, 3)) edge_list = make_grid_edges(x, 4, return_lists=True) edges = np.vstack(edge_list) edge_features = edge_list_to_features(edge_list) - x = (x.reshape(-1, 3), edges, edge_features) + x = ([x.reshape(-1, 3)], [edges], [edge_features]) unary_params = np.random.normal(size=(3, 3)) pw1 = np.random.normal(size=(3, 3)) @@ -532,38 +594,53 @@ def test_energy_continuous(): w = np.hstack([unary_params.ravel(), pw1.ravel(), pw2.ravel()]) res, energy = crf.inference(x, w, relaxed=True, return_energy=True) found_fractional = np.any(np.max(res[0], axis=-1) != 1) - joint_feature = crf.joint_feature(x, res) energy_svm = np.dot(joint_feature, w) assert_almost_equal(energy, -energy_svm) - def test_energy_discrete(): - for inference_method in get_installed(["qpbo", "ad3"]): - crf = EdgeFeatureGraphCRF(n_states=3, - inference_method=inference_method, - n_edge_features=2, n_features=3) +# for inference_method in get_installed(["qpbo", "ad3"]): +# crf = EdgeFeatureGraphCRF(n_states=3, +# inference_method=inference_method, +# n_edge_features=2, n_features=3) + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) + for i in range(10): x = np.random.normal(size=(7, 8, 3)) edge_list = make_grid_edges(x, 4, return_lists=True) edges = np.vstack(edge_list) edge_features = edge_list_to_features(edge_list) - x = (x.reshape(-1, 3), edges, edge_features) + x = ([x.reshape(-1, 3)], [edges], [edge_features]) unary_params = np.random.normal(size=(3, 3)) pw1 = np.random.normal(size=(3, 3)) pw2 = np.random.normal(size=(3, 3)) w = np.hstack([unary_params.ravel(), pw1.ravel(), pw2.ravel()]) y_hat = crf.inference(x, w, relaxed=False) + flat_edges = crf._index_all_edges(x) energy = compute_energy(crf._get_unary_potentials(x, w), - crf._get_pairwise_potentials(x, w), edges, + crf._get_pairwise_potentials(x, w), flat_edges, #CAUTION: pass the flatened edges!! y_hat) - joint_feature = crf.joint_feature(x, y_hat) + joint_feature = crf.joint_feature(x, [y_hat]) energy_svm = np.dot(joint_feature, w) assert_almost_equal(energy, energy_svm) -""" \ No newline at end of file +if __name__ == "__main__": + + if False: debug_joint_feature() + + if False: + test_joint_feature() + test_joint_feature2() + + if 0: test_unary_potentials() + if 1: test_inference_util() + if 0: test_inference() + if 0: test_joint_feature_discrete() + if 1: test_joint_feature_continuous() + if 1: test_energy_continuous() + if 1: test_energy_discrete() From a808ddc807b3736b64bb22c57897f65ed35db745 Mon Sep 17 00:00:00 2001 From: meunier Date: Thu, 12 Jan 2017 15:42:49 +0100 Subject: [PATCH 008/155] caching the output of _index_all_edges --- pystruct/models/typed_crf.py | 36 +++++++++++++++--------------------- 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index a8be1b83..7ba71d7f 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -23,6 +23,7 @@ def __init__(self self.l_n_features = l_n_features self._n_features = sum(self.l_n_features) #total number of (node) features + # check that ad3 is installed inference_method = get_installed(['ad3']) if not inference_method: raise Exception("ERROR: this model class requires AD3.") @@ -30,6 +31,8 @@ def __init__(self self.inference_calls = 0 #class weights: + self._cached_all_edge, self._cached_all_edge_id = None, None + # either we get class weights for all types of nodes, or for none of them! if l_class_weight: if len(l_class_weight) != self.n_types: @@ -54,7 +57,7 @@ def __init__(self #we store the slice objects self._a_feature_slice_by_typ = np.array([ slice(sum(self.l_n_features[:i]), sum(self.l_n_features[:i+1])) for i in range(self.n_types)]) - #when putting edge states in a single sequence, index of 1st feature of an edge of type (typ1, typ2) + #when putting edge states in a single sequence, index of 1st state of an edge of type (typ1, typ2) self._l_edgetype_start_index = [] i_start = 0 for typ1_n_states in self.l_n_states: @@ -63,8 +66,10 @@ def __init__(self i_start += typ1_n_states*typ2_n_states self._l_edgetype_start_index.append(i_start) assert i_start == self._n_states**2 - + def initialize(self, X, Y): + self._cached_all_edge, self._cached_all_edge_id = None, None + def _set_size_joint_feature(self): """ We have: @@ -110,22 +115,6 @@ def _check_size_x(self, x): if max(nodes1) >= l_nodes[typ1].shape[0] or max(nodes2) > l_nodes[typ2].shape[0]: raise ValueError("At least one edge points to non-existing node index") - def _check_size_y(self, x, y): - - if not isinstance(y, list): - raise ValueError("Y must be a list of arrays") - - l_features = self._get_node_features(x) - - for typ, (features, y_typ) in enumerate(zip(l_features, y)): - if not isinstance(y_typ, np.ndarray): - raise ValueError("Y must be a list of arrays") - if features.shape[0] != len(y_typ): - raise ValueError("Node of type %d: Expected %d labels not %d"%(typ, features.shape[0], len(y_typ))) - - if min(y_typ) < 0 or max(y_typ) >=self.l_n_states[typ]: - raise ValueError("Type %d: Some invalid label") - def _get_node_features(self, x, bClean=False): if bClean: return [ np.empty((0,0)) if node_features is None or len(node_features)==0 else node_features for node_features in x[0]] @@ -140,8 +129,10 @@ def _get_edges(self, x, bClean=False): return x[1] def _index_all_edges(self, x): """ - return all edges as a single 2-column matrix, taking care of indices!! + return all edges as a single 2-column matrix, taking care of node indices!! """ + if self._cached_all_edge_id == id(x): return self._cached_all_edge + n_edges_total = sum(0 if e is None else e.shape[0] for e in x[1]) all_edges = np.zeros((n_edges_total, 2), dtype=np.int32) @@ -154,9 +145,11 @@ def _index_all_edges(self, x): all_edges[i_start:i_stop, 0] = edges[:,0] + node_offset_by_typ[typ1] all_edges[i_start:i_stop, 1] = edges[:,1] + node_offset_by_typ[typ2] i_start = i_stop + + self._cached_all_edge, self._cached_all_edge_id = all_edges, id(x) + return all_edges - def _get_edges_by_type(self, x, typ1, typ2): return x[1][typ1*self.n_types+typ2] @@ -328,4 +321,5 @@ def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): else: return inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, self.inference_method, relaxed=relaxed, - return_energy=return_energy) \ No newline at end of file + return_energy=return_energy) + From f2400c696d7def34ab8645400147437bc61b430d Mon Sep 17 00:00:00 2001 From: meunier Date: Thu, 12 Jan 2017 16:23:45 +0100 Subject: [PATCH 009/155] OK!! --- examples/plot_snakes.py | 120 +++++++++-------- examples/plot_snakes_typed.py | 126 ++++++++++++++++++ .../node_type_edge_feature_graph_crf.py | 24 ++-- pystruct/models/typed_crf.py | 2 +- .../test_node_type_edge_feature_graph_crf.py | 65 ++++----- 5 files changed, 238 insertions(+), 99 deletions(-) create mode 100644 examples/plot_snakes_typed.py diff --git a/examples/plot_snakes.py b/examples/plot_snakes.py index 0292aec9..57201fc3 100644 --- a/examples/plot_snakes.py +++ b/examples/plot_snakes.py @@ -91,59 +91,67 @@ def prepare_data(X): X_edge_features.append((features, edges, edge_features)) return X_directions, X_edge_features - -print("Please be patient. Learning will take 5-20 minutes.") -snakes = load_snakes() -X_train, Y_train = snakes['X_train'], snakes['Y_train'] - -X_train = [one_hot_colors(x) for x in X_train] -Y_train_flat = [y_.ravel() for y_ in Y_train] - -X_train_directions, X_train_edge_features = prepare_data(X_train) - -inference = 'qpbo' -# first, train on X with directions only: -crf = EdgeFeatureGraphCRF(inference_method=inference) -ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, - n_jobs=1) -ssvm.fit(X_train_directions, Y_train_flat) - -# Evaluate using confusion matrix. -# Clearly the middel of the snake is the hardest part. -X_test, Y_test = snakes['X_test'], snakes['Y_test'] -X_test = [one_hot_colors(x) for x in X_test] -Y_test_flat = [y_.ravel() for y_ in Y_test] -X_test_directions, X_test_edge_features = prepare_data(X_test) -Y_pred = ssvm.predict(X_test_directions) -print("Results using only directional features for edges") -print("Test accuracy: %.3f" - % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) -print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) - -# now, use more informative edge features: -crf = EdgeFeatureGraphCRF(inference_method=inference) -ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', - n_jobs=-1) -ssvm.fit(X_train_edge_features, Y_train_flat) -Y_pred2 = ssvm.predict(X_test_edge_features) -print("Results using also input features for edges") -print("Test accuracy: %.3f" - % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) -print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) - -# plot stuff -fig, axes = plt.subplots(2, 2) -axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') -axes[0, 0].set_title('Input') -y = Y_test[0].astype(np.int) -bg = 2 * (y != 0) # enhance contrast -axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) -axes[0, 1].set_title("Ground Truth") -axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) -axes[1, 0].set_title("Prediction w/o edge features") -axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) -axes[1, 1].set_title("Prediction with edge features") -for a in axes.ravel(): - a.set_xticks(()) - a.set_yticks(()) -plt.show() +if __name__ == '__main__': + print("Please be patient. Learning will take 5-20 minutes.") + snakes = load_snakes() + X_train, Y_train = snakes['X_train'], snakes['Y_train'] + + #JL + X_train, Y_train = X_train[:40], Y_train[:40] + print len(X_train), len(Y_train) + print X_train[0].shape + print Y_train[0].shape + + X_train = [one_hot_colors(x) for x in X_train] + Y_train_flat = [y_.ravel() for y_ in Y_train] + + X_train_directions, X_train_edge_features = prepare_data(X_train) + + inference = 'qpbo' + # first, train on X with directions only: + crf = EdgeFeatureGraphCRF(inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, + n_jobs=1) + ssvm.fit(X_train_directions, Y_train_flat) + + # Evaluate using confusion matrix. + # Clearly the middel of the snake is the hardest part. + X_test, Y_test = snakes['X_test'], snakes['Y_test'] + X_test = [one_hot_colors(x) for x in X_test] + Y_test_flat = [y_.ravel() for y_ in Y_test] + X_test_directions, X_test_edge_features = prepare_data(X_test) + Y_pred = ssvm.predict(X_test_directions) + print("Results using only directional features for edges") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) + + # now, use more informative edge features: + crf = EdgeFeatureGraphCRF(inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', + #JL + max_iter=20, + n_jobs=-1) + ssvm.fit(X_train_edge_features, Y_train_flat) + Y_pred2 = ssvm.predict(X_test_edge_features) + print("Results using also input features for edges") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + + # plot stuff + fig, axes = plt.subplots(2, 2) + axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') + axes[0, 0].set_title('Input') + y = Y_test[0].astype(np.int) + bg = 2 * (y != 0) # enhance contrast + axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) + axes[0, 1].set_title("Ground Truth") + axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 0].set_title("Prediction w/o edge features") + axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 1].set_title("Prediction with edge features") + for a in axes.ravel(): + a.set_xticks(()) + a.set_yticks(()) + plt.show() diff --git a/examples/plot_snakes_typed.py b/examples/plot_snakes_typed.py new file mode 100644 index 00000000..e2b25f38 --- /dev/null +++ b/examples/plot_snakes_typed.py @@ -0,0 +1,126 @@ +""" +============================================== +Conditional Interactions on the Snakes Dataset +============================================== + +This is a varaint of plot_snakes.py where we use the NodeTypeEdgeFeatureGraphCRF +class instead of EdgeFeatureGraphCRF, despite there is only 1 type of nodes. + + +This example uses the snake dataset introduced in +Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 + +This dataset is specifically designed to require the pairwise interaction terms +to be conditioned on the input, in other words to use non-trival edge-features. + +The task is as following: a "snake" of length ten wandered over a grid. For +each cell, it had the option to go up, down, left or right (unless it came from +there). The input consists of these decisions, while the desired output is an +annotation of the snake from 0 (head) to 9 (tail). See the plots for an +example. + +As input features we use a 3x3 window around each pixel (and pad with background +where necessary). We code the five different input colors (for up, down, left, right, +background) using a one-hot encoding. This is a rather naive approach, not using any +information about the dataset (other than that it is a 2d grid). + +The task can not be solved using the simple DirectionalGridCRF - which can only +infer head and tail (which are also possible to infer just from the unary +features). If we add edge-features that contain the features of the nodes that are +connected by the edge, the CRF can solve the task. + +From an inference point of view, this task is very hard. QPBO move-making is +not able to solve it alone, so we use the relaxed AD3 inference for learning. + +PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). +But it does work as well as Decision Tree Fields ;) +""" +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.preprocessing import label_binarize +from sklearn.metrics import confusion_matrix, accuracy_score + +from pystruct.learners import OneSlackSSVM +from pystruct.datasets import load_snakes +from pystruct.utils import make_grid_edges, edge_list_to_features +#from pystruct.models import EdgeFeatureGraphCRF +from pystruct.models import NodeTypeEdgeFeatureGraphCRF + +from plot_snakes import one_hot_colors, neighborhood_feature, prepare_data + +def convertToSingleTypeX(X): + """ + For NodeTypeEdgeFeatureGraphCRF X is structured differently. + But NodeTypeEdgeFeatureGraphCRF can handle graph with a single node type. One needs to convert X to the new structure using this method. + """ + return [([nf], [e], [ef]) for (nf,e,ef) in X] + +if __name__ == '__main__': + print("Please be patient. Learning will take 5-20 minutes.") + snakes = load_snakes() + X_train, Y_train = snakes['X_train'], snakes['Y_train'] + + #JL +# X_train, Y_train = X_train[:40], Y_train[:40] +# print len(X_train), len(Y_train) +# print X_train[0].shape +# print Y_train[0].shape + + X_train = [one_hot_colors(x) for x in X_train] + Y_train_flat = [y_.ravel() for y_ in Y_train] + + X_train_directions, X_train_edge_features = prepare_data(X_train) + + #CHANGE!! + #We require AD3 and NodeTypeEdgeFeatureGraphCRF + #inference = 'qpbo' + # first, train on X with directions only: + #crf = NodeTypeEdgeFeatureGraphCRF(inference_method=inference) + crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[2]]) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, + n_jobs=1) + ssvm.fit(convertToSingleTypeX(X_train_directions), Y_train_flat) + + # Evaluate using confusion matrix. + # Clearly the middel of the snake is the hardest part. + X_test, Y_test = snakes['X_test'], snakes['Y_test'] + X_test = [one_hot_colors(x) for x in X_test] + Y_test_flat = [y_.ravel() for y_ in Y_test] + X_test_directions, X_test_edge_features = prepare_data(X_test) + Y_pred = ssvm.predict( convertToSingleTypeX(X_test_directions) ) + print("Results using only directional features for edges") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) + + # now, use more informative edge features: + crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]]) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + #switch_to='ad3', + #CHANGE: AD3 by default and only 100 iterations to save time and energy... + max_iter=100, + n_jobs=-1) + ssvm.fit( convertToSingleTypeX(X_train_edge_features), Y_train_flat) + Y_pred2 = ssvm.predict( convertToSingleTypeX(X_test_edge_features) ) + print("Results using also input features for edges") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + + # plot stuff + fig, axes = plt.subplots(2, 2) + axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') + axes[0, 0].set_title('Input') + y = Y_test[0].astype(np.int) + bg = 2 * (y != 0) # enhance contrast + axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) + axes[0, 1].set_title("Ground Truth") + axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 0].set_title("Prediction w/o edge features") + axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 1].set_title("Prediction with edge features") + for a in axes.ravel(): + a.set_xticks(()) + a.set_yticks(()) + plt.show() diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index 9403e057..e091e3d0 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -46,7 +46,7 @@ class NodeTypeEdgeFeatureGraphCRF(TypedCRF): An instance ``X`` is represented as a tuple ``([node_features, ..], [edges, ..], [edge_features, ..])`` - Labels ``Y`` are given as a list of array of shape (n_type_nodes) + Labels ``Y`` are given as one array of shape (n_nodes) The meaning of a label depends upon the node type. """ @@ -225,9 +225,7 @@ def joint_feature(self, x, y): Feature vector associated with state (x, y). """ - self._check_size_x(x) - if not isinstance(y, tuple): self._check_size_y(x,y) l_node_features = self._get_node_features(x) l_edges, l_edge_features = self._get_edges(x), self._get_edge_features(x) l_n_nodes = [len(o) for o in self._get_node_features(x, True)] @@ -246,13 +244,11 @@ def joint_feature(self, x, y): unary_marginals = np.zeros((n_nodes, self._n_states), dtype=np.int) i_start = 0 #print self.l_n_states, self._l_type_startindex, y - for node_features, typ_start_index, y_typ in zip(l_node_features, self._l_type_startindex, y): + for node_features, typ_start_index in zip(l_node_features, self._l_type_startindex): if node_features is None: continue i_stop = i_start + node_features.shape[0] -# for n_state, typ_start_index, y_typ in zip(self.l_n_states, self._l_type_startindex, y): -# i_stop = i_start + n_state unary_marginals[ np.ogrid[i_start:i_stop] - , typ_start_index + y_typ[:] + , typ_start_index + y[i_start:i_stop] ] = 1 i_start = i_stop #print "--- unary_marginals \n", `unary_marginals` @@ -260,17 +256,17 @@ def joint_feature(self, x, y): ## pairwise #same thing, but the type of an edge is a pair of node types pw = np.zeros((n_edges, self._n_states ** 2)) + node_offset_by_typ = np.cumsum([0]+[0 if n is None else n.shape[0] for n in x[0]]) i_start = 0 for (typ1, typ2), edges, edgetype_start_index in zip(self._iter_type_pairs(), l_edges, self._l_edgetype_start_index): if edges is None: continue - #we have edges from node typ1 to node typ2 - y_typ1, y_typ2 = y[typ1], y[typ2] #the labels of all nodes of those two types - #now keep only the label of the nodes of interest - y1,y2 = y_typ1[edges[:,0]], y_typ2[edges[:,1]] + #the label of those pairs of nodes + y1 = y[node_offset_by_typ[typ1] + edges[:,0]] + y2 = y[node_offset_by_typ[typ2] + edges[:,1]] #set the 1s where they should i_stop = i_start + edges.shape[0] pw[ np.ogrid[i_start:i_stop] - , edgetype_start_index + self.l_n_states[typ2] * y1[:] + y2[:] + , edgetype_start_index + self.l_n_states[typ2] * y1 + y2 ] = 1 i_start = i_stop #print "--- pw = \n", `pw` @@ -307,6 +303,10 @@ def joint_feature(self, x, y): #print "--- all_edge_features =\n", `all_edge_features` pairwise_acc = np.dot(all_edge_features.T, pw) # sum_of_features x edge_states +# print '-'*30 +# print np.dot(pw.T, all_edge_features).T +# print '-'*30 + #easier to read... :-( pairwise_acc = np.dot(pw.T, all_edge_features) # sum_of_features x edge_states #print "--- pairwise_acc.shape = ", pairwise_acc.shape #print "--- pairwise_acc =\n", `pairwise_acc` diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index 7ba71d7f..1fbcf850 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -149,7 +149,7 @@ def _index_all_edges(self, x): self._cached_all_edge, self._cached_all_edge_id = all_edges, id(x) return all_edges - + def _get_edges_by_type(self, x, typ1, typ2): return x[1][typ1*self.n_types+typ2] diff --git a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py index 54f5b3ba..675cb5d7 100644 --- a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py +++ b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py @@ -95,9 +95,9 @@ def debug_joint_feature(): x = [l_node_f, l_edges, l_edge_f] print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " - y = [ np.array([1, 1]), - np.array([0, 2, 0]) - ] + y = np.hstack([ np.array([0, 1]), + np.array([0, 1, 2]) + ]) print y g.initialize(x, y) jf = g.joint_feature(x,y) @@ -109,10 +109,13 @@ def debug_joint_feature(): [ 1. , 1., 1. , 2., 2., 2. , 0.11 , 0.12 , 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 , 0.33 , 0.34 - , 0. , 0.111 , 0. , 0. - , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. - , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. , 0.,0. - , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. , 0.,0.,0. + , 0. , 0.111, 0. , 0. , 0. , 0.221, + 0. , 0. , 0. , 0. , 0. , 0.222, 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ])) @@ -154,8 +157,8 @@ def test_joint_feature(): x = [node_f, edges, edge_f] print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " - y = [ np.array([1,2]) - ] + y = np.array([1,2]) + # y = np.array([1,0]) print y jf = g.joint_feature(x,y) @@ -170,7 +173,7 @@ def test_joint_feature(): ) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " - y = [ np.array([0,0]) ] + y = np.array([0,0]) print y jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` @@ -184,7 +187,7 @@ def test_joint_feature(): ) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " - y = [np.array([0,1])] + y = np.array([0,1]) node_f = [ np.array([[1.1,1.2,1.3], [2.1,2.2,2.3]]) ] edge_f = [ np.array([[3.1,3.2,3.3]]) ] x = [node_f, edges, edge_f] @@ -204,7 +207,7 @@ def test_joint_feature(): x = [node_f, edges, edge_f] print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " - y = [ np.array([1,2]) ] + y = np.array([1,2]) print y jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` @@ -217,7 +220,7 @@ def test_joint_feature(): 0., 0., 0., 0., 0., 0., 0., 0.]) ) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " - y = [ np.array([0,0])] + y = np.array([0,0]) print y print "joint_feature = \n", `g.joint_feature(x,y)` print @@ -261,9 +264,9 @@ def test_joint_feature2(): x = [node_f, edges, edge_f] print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " - y = [ np.array([0, 0]) - , np.array([0, 0, 0]) - ] + y = np.hstack([ np.array([0, 0]) + , np.array([0, 0, 0]) + ]) print y jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` @@ -304,8 +307,8 @@ def test_joint_feature2(): x = [ node_f, edges, edge_f] print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " - y = [np.array([0, 1]), - np.array([0, 1, 2])] + y = np.hstack([np.array([0, 1]), + np.array([0, 1, 2])]) print y jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` @@ -321,6 +324,7 @@ def test_joint_feature2(): 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ])) + print "MORE COMPLEX GRAPH :) -- BIS OK" print "--- REORDERED MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" node_f = [ np.array([ [2,2,2], [1,1,1] ]) @@ -338,8 +342,8 @@ def test_joint_feature2(): x = [ node_f, edges, edge_f] print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " - y = [np.array([1, 0]), - np.array([2, 0, 1])] + y = np.hstack([np.array([1, 0]), + np.array([2, 0, 1])]) print y jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` @@ -377,8 +381,7 @@ def test_unary_potentials(): ] x = [node_f, edges, edge_f] print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " - y = [ np.array([1,2]) - ] + y = np.hstack([ np.array([1,2])]) # y = np.array([1,0]) print y @@ -510,7 +513,7 @@ def test_joint_feature_discrete(): #for inference_method in get_installed(["lp", "ad3", "qpbo"]): if True: crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) - joint_feature_y = crf.joint_feature(x, [y_flat]) + joint_feature_y = crf.joint_feature(x, y_flat) assert_equal(joint_feature_y.shape, (crf.size_joint_feature,)) # first horizontal, then vertical # we trust the unaries ;) @@ -563,7 +566,7 @@ def test_joint_feature_continuous(): y_pred = crf.inference(x, w, relaxed=True) # compute joint_feature for prediction - joint_feature_y = crf.joint_feature(x, [y_pred]) + joint_feature_y = crf.joint_feature(x, y_pred) assert_equal(joint_feature_y.shape, (crf.size_joint_feature,)) # FIXME # first horizontal, then vertical @@ -623,7 +626,7 @@ def test_energy_discrete(): crf._get_pairwise_potentials(x, w), flat_edges, #CAUTION: pass the flatened edges!! y_hat) - joint_feature = crf.joint_feature(x, [y_hat]) + joint_feature = crf.joint_feature(x, y_hat) energy_svm = np.dot(joint_feature, w) assert_almost_equal(energy, energy_svm) @@ -631,16 +634,18 @@ def test_energy_discrete(): if __name__ == "__main__": - if False: debug_joint_feature() + if 1: + debug_joint_feature() - if False: + if 1: test_joint_feature() + if 1: test_joint_feature2() - if 0: test_unary_potentials() + if 1: test_unary_potentials() if 1: test_inference_util() - if 0: test_inference() - if 0: test_joint_feature_discrete() + if 1: test_inference() + if 1: test_joint_feature_discrete() if 1: test_joint_feature_continuous() if 1: test_energy_continuous() if 1: test_energy_discrete() From dd9d95e8063dc4e736cef96a4940ceffd33ba2bb Mon Sep 17 00:00:00 2001 From: meunier Date: Fri, 13 Jan 2017 11:05:40 +0100 Subject: [PATCH 010/155] - inference is not forced to ad3 - some caching change --- pystruct/models/typed_crf.py | 105 +++++++++++++++++++++++------------ 1 file changed, 68 insertions(+), 37 deletions(-) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index 1fbcf850..71cac805 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -12,7 +12,17 @@ def __init__(self , n_types #how many node type? , l_n_states #how many labels per node type? , l_n_features #how many features per node type? + , inference_method="ad3" , l_class_weight=None): #class_weight per node type or None or None + + StructuredModel.__init__(self) + + if inference_method is None: + # get first in list that is installed + inference_method = get_installed(['ad3', 'max-product', 'lp'])[0] + self.inference_method = inference_method + self.inference_calls = 0 + if len(l_n_states) != n_types: raise ValueError("Expected 1 number of states per node type.") if l_n_features != None and len(l_n_features) != n_types: @@ -23,16 +33,10 @@ def __init__(self self.l_n_features = l_n_features self._n_features = sum(self.l_n_features) #total number of (node) features - - # check that ad3 is installed - inference_method = get_installed(['ad3']) - if not inference_method: raise Exception("ERROR: this model class requires AD3.") - self.inference_method = inference_method[0] - self.inference_calls = 0 + #Caching some heavily used values + self._get_unary_potentials_initialize() #class weights: - self._cached_all_edge, self._cached_all_edge_id = None, None - # either we get class weights for all types of nodes, or for none of them! if l_class_weight: if len(l_class_weight) != self.n_types: @@ -44,8 +48,7 @@ def __init__(self #class weights are computed by type and simply concatenated self.class_weight = np.hstack([np.array(class_weight) for class_weight in l_class_weight]) else: - n_things = sum(self.l_n_states) - self.class_weight = np.ones(n_things) + self.class_weight = np.ones(self._n_states) self._set_size_joint_feature() @@ -67,9 +70,9 @@ def __init__(self self._l_edgetype_start_index.append(i_start) assert i_start == self._n_states**2 - def initialize(self, X, Y): - self._cached_all_edge, self._cached_all_edge_id = None, None - + def initialize(self, X, Y=None): + pass + def _set_size_joint_feature(self): """ We have: @@ -131,8 +134,6 @@ def _index_all_edges(self, x): """ return all edges as a single 2-column matrix, taking care of node indices!! """ - if self._cached_all_edge_id == id(x): return self._cached_all_edge - n_edges_total = sum(0 if e is None else e.shape[0] for e in x[1]) all_edges = np.zeros((n_edges_total, 2), dtype=np.int32) @@ -146,8 +147,6 @@ def _index_all_edges(self, x): all_edges[i_start:i_stop, 1] = edges[:,1] + node_offset_by_typ[typ2] i_start = i_stop - self._cached_all_edge, self._cached_all_edge_id = all_edges, id(x) - return all_edges def _get_edges_by_type(self, x, typ1, typ2): @@ -159,17 +158,45 @@ def _iter_type_pairs(self): yield (typ1, typ2) raise StopIteration +# +# def _get_unary_potentials_slow(self, x, w): +# self._check_size_w(w) +# self._check_size_x(x) +# l_node_features = self._get_node_features(x) +# a_nodes_features = scipy.sparse.block_diag(l_node_features) #.toarray() +# w_unaries = w[:self.size_unaries] +# l_w_block = [] +# for ((i_w,i_w2), (n_states, n_features)) in self._cache_unary_potentials: +# unary_params = w_unaries[i_w:i_w2].reshape(n_states, n_features) +# l_w_block.append(unary_params.T) +# a_features_states = scipy.sparse.block_diag(l_w_block) +# return a_nodes_features.dot(a_features_states).toarray() + + def _get_unary_potentials_initialize(self): + """ + pre-compute iteration params + """ + self._cache_unary_potentials = list() + + #l_w_block = [] + i_w, i_states = 0, 0 + for n_states, n_features in zip(self.l_n_states, self.l_n_features): + i_w2 = i_w + n_states*n_features #number of weights for the type + i_states2 = i_states + n_states #number of state of that type + self._cache_unary_potentials.append( ((i_w,i_w2), (i_states, i_states2), (n_states, n_features)) ) + i_w, i_states = i_w2, i_states2 + def _get_unary_potentials(self, x, w): """Computes unary potentials for x and w. - + Parameters ---------- x : tuple Instance Representation. - + w : ndarray, shape=(size_joint_feature,) Weight vector for CRF instance. - + Returns ------- unary : ndarray, shape=(sum_over_types(n_states_of_type) @@ -182,25 +209,29 @@ def _get_unary_potentials(self, x, w): # unary_params = w[:self.n_states * self.n_features].reshape( # self.n_states, self.n_features) # return np.dot(features, unary_params.T) - + #self.size_unaries == sum( n_states * n_features for n_states, n_features in zip(self.l_n_states, self.l_n_features) ) w_unaries = w[:self.size_unaries] a_nodes_states = np.zeros((sum(nf.shape[0] for nf in l_node_features) , self._n_states), dtype=w.dtype) - #we work type by type and assemble the unaries - #"irrelevant" unaries (i.e. for state not applicable to a type, will get a 0 - i_w, i_nodes, i_states = 0, 0, 0 - for features, n_states, n_features in zip(l_node_features, self.l_n_states, self.l_n_features): - i_w2 = i_w + n_states*n_features #number of weights for the type +# #we work type by type and assemble the unaries +# #"irrelevant" unaries (i.e. for state not applicable to a type, will get a 0 +# i_w, i_nodes, i_states = 0, 0, 0 +# for features, n_states, n_features in zip(l_node_features, self.l_n_states, self.l_n_features): +# i_w2 = i_w + n_states*n_features #number of weights for the type +# i_nodes2 = i_nodes + features.shape[0] #number of nodes of that type +# i_states2 = i_states + n_states #number of state of that type +# w_unaries_type = w_unaries[i_w:i_w2] #range for weights for that type +# #back to "usual" code! +# unary_params = w_unaries_type.reshape(n_states, n_features) +# #apart that we fill a sub-part of the unaries matrix +# a_nodes_states[i_nodes:i_nodes2, i_states:i_states2] = np.dot(features, unary_params.T) +# i_w, i_nodes, i_states = i_w2, i_nodes2, i_states2 + i_nodes = 0 + for features, ((i_w,i_w2), (i_states, i_states2), (n_states, n_features)) in zip(l_node_features, self._cache_unary_potentials): i_nodes2 = i_nodes + features.shape[0] #number of nodes of that type - i_states2 = i_states + n_states #number of state of that type - w_unaries_type = w_unaries[i_w:i_w2] #range for weights for that type - #back to "usual" code! - unary_params = w_unaries_type.reshape(n_states, n_features) - #apart that we fill a sub-part of the unaries matrix - a_nodes_states[i_nodes:i_nodes2, i_states:i_states2] = np.dot(features, unary_params.T) - i_w, i_nodes, i_states = i_w2, i_nodes2, i_states2 - + a_nodes_states[i_nodes:i_nodes2, i_states:i_states2] = np.dot(features, w_unaries[i_w:i_w2].reshape(n_states, n_features).T) + i_nodes = i_nodes2 # nodes x features . features x states --> nodes x states return a_nodes_states @@ -252,7 +283,7 @@ def loss_augmented_inference(self, x, y, w, relaxed=False, """ self.inference_calls += 1 self._check_size_w(w) - unary_potentials = self._get_unary_potentials(x, w) + unary_potentials = self._get_unary_potentials(x, w) pairwise_potentials = self._get_pairwise_potentials(x, w) flat_edges = self._index_all_edges(x) flat_y = np.hstack(y) @@ -309,9 +340,9 @@ def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): """ self._check_size_w(w) self.inference_calls += 1 - unary_potentials = self._get_unary_potentials(x, w) + self.initialize(x) + unary_potentials = self._get_unary_potentials(x, w) pairwise_potentials = self._get_pairwise_potentials(x, w) - flat_edges = self._index_all_edges(x) if constraints: From 4d2a61fd8bc5d20ae911ce4024657eee8d5908ef Mon Sep 17 00:00:00 2001 From: meunier Date: Fri, 13 Jan 2017 11:06:23 +0100 Subject: [PATCH 011/155] - inference not forced to ad3 - caching --- .../node_type_edge_feature_graph_crf.py | 84 +++++++++++++------ 1 file changed, 57 insertions(+), 27 deletions(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index e091e3d0..c4340651 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -55,6 +55,7 @@ def __init__(self , l_n_states #how many labels per node type? , l_n_features #how many features per node type? , a_n_edge_features #how many features per edge type? + , inference_method="ad3" , l_class_weight=None): #class_weight per node type or None or None #internal stuff @@ -68,7 +69,9 @@ def __init__(self self._n_edge_features = self.a_n_edge_features.sum(axis=None) #total number of (edge) features - TypedCRF.__init__(self, n_types, l_n_states, l_n_features, l_class_weight=l_class_weight) + TypedCRF.__init__(self, n_types, l_n_states, l_n_features, inference_method=inference_method, l_class_weight=l_class_weight) + + self._get_pairwise_potentials_initialize() def _set_size_joint_feature(self): """ @@ -131,7 +134,28 @@ def _get_edge_features(self, x, bClean=False): def _get_edge_features_by_type(self, x, typ1, typ2): return x[2][typ1*self.n_types+typ2] - + def _get_pairwise_potentials_initialize(self): + """ + Putting in cache the params required to build the pairwise potentials given x and w + """ + self._cache_pairwise_potentials = list() + i_w, n_states1, n_states2, i_states1, i_states2 = 0, 0, 0, 0, 0 +# for (typ1, typ2), edge_features, edgetype_start_index in zip(self._iter_type_pairs(), l_edge_features, self._l_edgetype_start_index): + for (typ1, typ2) in self._iter_type_pairs(): + + n_features = self.a_n_edge_features[typ1, typ2] + n_states1 = self.l_n_states[typ1] + n_states2 = self.l_n_states[typ2] + i_w_stop = i_w + n_features * n_states1 * n_states2 + i_states1_stop = i_states1 + n_states1 + i_states2_stop = i_states2 + n_states2 + + self._cache_pairwise_potentials.append( (n_features + , n_states1, n_states2, i_states1, i_states1_stop, i_states2, i_states2_stop + , i_w, i_w_stop) ) + + i_w, i_states1, i_states2 = i_w_stop, i_states1_stop, i_states2_stop + def _get_pairwise_potentials(self, x, w): """Computes pairwise potentials for x and w. @@ -156,41 +180,47 @@ def _get_pairwise_potentials(self, x, w): # return np.dot(edge_features, pairwise).reshape( # edge_features.shape[0], self.n_states, self.n_states) - l_edge_features = self._get_edge_features(x) - n_edges_total = sum(0 if e is None else e.shape[0] for e in l_edge_features) + l_edge_features = self._get_edge_features(x) + l_edge_nb = [0 if ef is None else ef.shape[0] for ef in l_edge_features] + n_edges_total = sum(l_edge_nb) + wpw = w[self.size_unaries:] a_edges_states_states = np.zeros((n_edges_total, self._n_states, self._n_states), dtype=w.dtype) - i_w, i_edges, i_states1, i_states2 = 0, 0, 0, 0 -# for (typ1, typ2), edge_features, edgetype_start_index in zip(self._iter_type_pairs(), l_edge_features, self._l_edgetype_start_index): - for (typ1, typ2), edge_features in zip(self._iter_type_pairs(), l_edge_features): - if edge_features is None: continue +# i_w, i_edges, i_states1, i_states2 = 0, 0, 0, 0 +# # for (typ1, typ2), edge_features, edgetype_start_index in zip(self._iter_type_pairs(), l_edge_features, self._l_edgetype_start_index): +# for (typ1, typ2), edge_features in zip(self._iter_type_pairs(), l_edge_features): +# if edge_features is None: continue +# +# n_edges, n_features = edge_features.shape +# n_states1 = self.l_n_states[typ1] +# n_states2 = self.l_n_states[typ2] +# i_w_stop = i_w + self.a_n_edge_features[typ1,typ2] * n_states1 * n_states2 +# i_edges_stop = i_edges + n_edges +# i_states1_stop = i_states1 + n_states1 +# i_states2_stop = i_states2 + n_states2 +# +# pw_typ_typ = wpw[i_w:i_w_stop].reshape(n_features, -1) # n_states1*n_states2 x nb_feat +# pot_typ_typ = np.dot(edge_features, pw_typ_typ).reshape(n_edges, n_states1, n_states2) +# +# a_edges_states_states[ i_edges:i_edges_stop, i_states1:i_states1_stop , i_states2:i_states2_stop ] = pot_typ_typ +# +# i_w, i_edges, i_states1, i_states2 = i_w_stop, i_edges_stop, i_states1_stop, i_states2_stop + + i_edges = 0 + for ((n_features, n_states1, n_states2, i_states1, i_states1_stop, i_states2, i_states2_stop, i_w, i_w_stop) + , edge_features, n_edges) in zip(self._cache_pairwise_potentials, l_edge_features, l_edge_nb): - n_edges, n_features = edge_features.shape - n_states1 = self.l_n_states[typ1] - n_states2 = self.l_n_states[typ2] - i_w_stop = i_w + self.a_n_edge_features[typ1,typ2] * n_states1 * n_states2 + if edge_features is None: continue i_edges_stop = i_edges + n_edges - i_states1_stop = i_states1 + n_states1 - i_states2_stop = i_states2 + n_states2 -# print "wpw ", wpw.size, wpw.shape -# print "n_features ", n_features -# print edgetype_start_index,edgetype_start_index+n_states1*n_states2 -# print wpw[edgetype_start_index:edgetype_start_index+n_states1*n_states2] pw_typ_typ = wpw[i_w:i_w_stop].reshape(n_features, -1) # n_states1*n_states2 x nb_feat -# print "pw_typ_typ ", pw_typ_typ pot_typ_typ = np.dot(edge_features, pw_typ_typ).reshape(n_edges, n_states1, n_states2) -# print "pot_typ_typ ", pot_typ_typ -# print (i_edges,i_edges_stop) -# print (i_states1,i_states1_stop) -# print (i_states2,i_states2_stop) -# print a_edges_states_states.shape -# print pot_typ_typ.shape + a_edges_states_states[ i_edges:i_edges_stop, i_states1:i_states1_stop , i_states2:i_states2_stop ] = pot_typ_typ - i_w, i_edges, i_states1, i_states2 = i_w_stop, i_edges_stop, i_states1_stop, i_states2_stop - + i_edges = i_edges_stop + return a_edges_states_states.reshape(n_edges_total, self._n_states, self._n_states) def _block_ravel(self, a, lij): From 607559070eb6a83e18193853151ecd33d47e093d Mon Sep 17 00:00:00 2001 From: meunier Date: Fri, 13 Jan 2017 11:06:50 +0100 Subject: [PATCH 012/155] calling initialize --- .../test_node_type_edge_feature_graph_crf.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py index 675cb5d7..c8389437 100644 --- a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py +++ b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py @@ -161,6 +161,7 @@ def test_joint_feature(): # y = np.array([1,0]) print y + g.initialize(x, y) jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` print @@ -175,6 +176,7 @@ def test_joint_feature(): print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.array([0,0]) print y + g.initialize(x, y) jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` print @@ -191,6 +193,7 @@ def test_joint_feature(): node_f = [ np.array([[1.1,1.2,1.3], [2.1,2.2,2.3]]) ] edge_f = [ np.array([[3.1,3.2,3.3]]) ] x = [node_f, edges, edge_f] + g.initialize(x, y) jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` @@ -209,6 +212,7 @@ def test_joint_feature(): print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.array([1,2]) print y + g.initialize(x, y) jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` print @@ -222,6 +226,7 @@ def test_joint_feature(): print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.array([0,0]) print y + g.initialize(x, y) print "joint_feature = \n", `g.joint_feature(x,y)` print assert_array_equal(g.joint_feature(x,y) @@ -268,6 +273,7 @@ def test_joint_feature2(): , np.array([0, 0, 0]) ]) print y + g.initialize(x, y) jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` print @@ -310,6 +316,7 @@ def test_joint_feature2(): y = np.hstack([np.array([0, 1]), np.array([0, 1, 2])]) print y + g.initialize(x, y) jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` print @@ -345,6 +352,7 @@ def test_joint_feature2(): y = np.hstack([np.array([1, 0]), np.array([2, 0, 1])]) print y + g.initialize(x, y) jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` print @@ -384,6 +392,7 @@ def test_unary_potentials(): y = np.hstack([ np.array([1,2])]) # y = np.array([1,0]) print y + g.initialize(x, y) gref = EdgeFeatureGraphCRF(4,3,3) xref = (node_f[0], edges[0], edge_f[0]) @@ -478,10 +487,12 @@ def test_inference(): edge_features = edge_list_to_features(edge_list) x = ([x.reshape(-1, n_states)], [edges], [edge_features]) y = [y.ravel()] + #for inference_method in get_installed(["lp", "ad3"]): if True: # same inference through CRF inferface crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) # ad3 only is supported..., inference_method=inference_method) + crf.initialize(x, y) #crf.initialize([x], [y]) w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) y_pred = crf.inference(x, w, relaxed=True) @@ -496,6 +507,7 @@ def test_inference(): crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) #crf.initialize([x], [y]) w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) + crf.initialize(x) y_pred = crf.inference(x, w, relaxed=False) assert_array_equal(y[0], y_pred) @@ -563,6 +575,8 @@ def test_joint_feature_continuous(): w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) #crf.initialize([x], [y]) #report_model_config(crf) + crf.initialize(x, y) + y_pred = crf.inference(x, w, relaxed=True) # compute joint_feature for prediction @@ -595,6 +609,7 @@ def test_energy_continuous(): pw1 = np.random.normal(size=(3, 3)) pw2 = np.random.normal(size=(3, 3)) w = np.hstack([unary_params.ravel(), pw1.ravel(), pw2.ravel()]) + crf.initialize(x) res, energy = crf.inference(x, w, relaxed=True, return_energy=True) found_fractional = np.any(np.max(res[0], axis=-1) != 1) joint_feature = crf.joint_feature(x, res) @@ -620,6 +635,7 @@ def test_energy_discrete(): pw1 = np.random.normal(size=(3, 3)) pw2 = np.random.normal(size=(3, 3)) w = np.hstack([unary_params.ravel(), pw1.ravel(), pw2.ravel()]) + crf.initialize(x) y_hat = crf.inference(x, w, relaxed=False) flat_edges = crf._index_all_edges(x) energy = compute_energy(crf._get_unary_potentials(x, w), From fa47c1263948479dcb5e7a1f5bdcdebf9b67f56b Mon Sep 17 00:00:00 2001 From: meunier Date: Sat, 14 Jan 2017 11:15:25 +0100 Subject: [PATCH 013/155] -snakes now hide in the sand. So half of the picture do not contain any snake, despite some colored cells. --- examples/plot_hidden_snakes.py | 429 +++++++++++++++++++++++++++++++++ 1 file changed, 429 insertions(+) create mode 100644 examples/plot_hidden_snakes.py diff --git a/examples/plot_hidden_snakes.py b/examples/plot_hidden_snakes.py new file mode 100644 index 00000000..f101c9d2 --- /dev/null +++ b/examples/plot_hidden_snakes.py @@ -0,0 +1,429 @@ +""" +============================================== +Conditional Interactions on the Snakes Dataset +============================================== + +This is a variant of plot_snakes.py + +Snake are hidding, so another task is both to determine if a snake is in the picture, and +identify its head to tail body. + +We use the NodeTypeEdgeFeatureGraphCRF class with 2 type of nodes. + + +This example uses the snake dataset introduced in +Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 + +This dataset is specifically designed to require the pairwise interaction terms +to be conditioned on the input, in other words to use non-trival edge-features. + +The task is as following: a "snake" of length ten wandered over a grid. For +each cell, it had the option to go up, down, left or right (unless it came from +there). The input consists of these decisions, while the desired output is an +annotation of the snake from 0 (head) to 9 (tail). See the plots for an +example. + +As input features we use a 3x3 window around each pixel (and pad with background +where necessary). We code the five different input colors (for up, down, left, right, +background) using a one-hot encoding. This is a rather naive approach, not using any +information about the dataset (other than that it is a 2d grid). + +The task can not be solved using the simple DirectionalGridCRF - which can only +infer head and tail (which are also possible to infer just from the unary +features). If we add edge-features that contain the features of the nodes that are +connected by the edge, the CRF can solve the task. + +From an inference point of view, this task is very hard. QPBO move-making is +not able to solve it alone, so we use the relaxed AD3 inference for learning. + +PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). +But it does work as well as Decision Tree Fields ;) +""" +import numpy as np +import matplotlib.pyplot as plt +import random +from sklearn.preprocessing import label_binarize +from sklearn.metrics import confusion_matrix, accuracy_score +import time + +from pystruct.learners import OneSlackSSVM +from pystruct.datasets import load_snakes +from pystruct.utils import make_grid_edges, edge_list_to_features +#from pystruct.models import EdgeFeatureGraphCRF +from pystruct.models import NodeTypeEdgeFeatureGraphCRF + +from plot_snakes import one_hot_colors, neighborhood_feature, prepare_data + +def isSnakePresent(a_hot_picture): + """ + Algorithmic check, to make sure that after shuffling we do not have a snake! :-) + work on the 1-hot encoded picture + """ + try: + ai, aj = np.where(a_hot_picture[...,3] != 1) + if len(ai) != 10: return False + lij = zip(ai, aj) + for n in range(10): + _lij = shiftSnake(a_hot_picture, lij) + if len(_lij) != len(lij)-1: return False + lij = _lij + if len(_lij) != 0: return False + return True + except: + return False + +def shiftSnake(a_hot_picture, lij): + #the snake moves by one cell, head disappearing in sand + _lij = list() + for i,j in lij: + color_index = np.where(a_hot_picture[i,j,:]==1)[0][0] + dj = np.array( [ 0, 0, 1, None, -1])[color_index] + di = np.array( [-1, 1, 0, None, 0])[color_index] + i,j = i+di,j+dj + if a_hot_picture[i,j,3] != 1: #backgroun + _lij.append((i,j)) + return _lij + +def shufflePictureCells(a_picture): #in place!! + """ + Shuffle the pixels + """ + n = random.randint(1,4) + if n == 1: + map(np.random.shuffle, a_picture) + elif n == 2: + map(np.random.shuffle, np.transpose(a_picture, (1,0,2))) + else: + map(np.random.shuffle, a_picture) + map(np.random.shuffle, np.transpose(a_picture, (1,0,2))) + + return a_picture + +def shuffleSnakeCells(a_picture, bOneHot=True): #in place!! + """ + Shuffle the colors of the 10 snake cells + """ + if bOneHot: + ai, aj = np.where(a_picture[...,3] != 1) + else: + _p = np.copy(a_picture) + _p = one_hot_colors(_p) + ai, aj = np.where(_p[...,3] != 1) + assert len(ai) == 10 + + l_shuffled_aij = zip(ai,aj) + random.shuffle( l_shuffled_aij ) + _ai, _aj = zip(*l_shuffled_aij) + + a_picture[_ai,_aj,:] = a_picture[ai,aj,:] + return a_picture + +def shuffleSnake(a_picture, bOneHot=True): + """ + Shuffle either the snake's cells or the pcitures' pixels. + """ + if random.randint(0,1): + shuffleSnakeCells(a_picture, bOneHot) + else: + shufflePictureCells(a_picture) + +def convertToSingleTypeX(X): + """ + For NodeTypeEdgeFeatureGraphCRF X is structured differently. + But NodeTypeEdgeFeatureGraphCRF can handle graph with a single node type. One needs to convert X to the new structure using this method. + """ + return [([nf], [e], [ef]) for (nf,e,ef) in X] + +def plot_snake(picture): + plt.imshow(picture, interpolation='nearest') + plt.show() + +def augmentWithNoSnakeImages(X,Y, name, bOneHot=True): + print "ADDING PICTURE WIHOUT SNAKES!!! %d elements in %s"%(len(X), name) + + X_NoSnake = [np.copy(x) for x in X] + for x in X_NoSnake: shuffleSnake(x, bOneHot) + #map(shufflePictureCells, X_NoSnake) + + newX = list() + Y_NoSnake = list() + for x,y in zip(X_NoSnake, Y): + if isSnakePresent(x): + print "\t- DISCARDING a shuffled snake which is still a snake!!!!" + else: + newX.append(x) + Y_NoSnake.append(np.zeros(y.shape, dtype=np.int8)) + X_NoSnake = newX + + return X+X_NoSnake, Y+Y_NoSnake + +def shuffle_XY(X,Y): + lxy = zip(X, Y) + random.shuffle(lxy) + X, Y = zip(*lxy) + return X, Y + +if __name__ == '__main__': + print("Please be patient. Learning will take 5-20 minutes.") + snakes = load_snakes() + X_train, Y_train = snakes['X_train'], snakes['Y_train'] + + bSHUFFLE = True + + bADD_HIDDEN_SNAKES = True + #bADD_HIDDEN_SNAKES = False + #JL + #X_train, Y_train = X_train[:10], Y_train[:10] + print len(X_train), len(Y_train) + #print `X_train[0]` + + if bADD_HIDDEN_SNAKES: + X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False) + print len(X_train), len(Y_train) + + if False: + #show the faked pictures + for ix, x in enumerate(X_train): plot_snake(shufflePictureCells(x)) + + X_train_hot = [one_hot_colors(x) for x in X_train] + + if False: + for ix, x in enumerate(X_train_hot): + if not isSnakePresent(x): plot_snake(X_train[ix]) + + X_train = X_train_hot + print "Snakes are ok" + + + if bSHUFFLE: + #let's shuffle our data + X_train, Y_train = shuffle_XY(X_train, Y_train) + + # ------------------------------------------------------------------------------------- + X_train_directions, X_train_edge_features = prepare_data(X_train) + + Y_train_flat = [y_.ravel() for y_ in Y_train] + + inference = 'qpbo' + # first, train on X with directions only: + #CHANGE!! + #We require NodeTypeEdgeFeatureGraphCRF + #crf = NodeTypeEdgeFeatureGraphCRF(inference_method=inference) + crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[2]], inference_method=inference) + XX = convertToSingleTypeX(X_train_directions) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + max_iter=100, + n_jobs=1) + print len(XX), len(Y_train), len(Y_train_flat) + ssvm.fit(XX, Y_train_flat) + + # Evaluate using confusion matrix. + # Clearly the middel of the snake is the hardest part. + X_test, Y_test = snakes['X_test'], snakes['Y_test'] + print "TEST len=", len(X_test) + if bADD_HIDDEN_SNAKES: + X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", bOneHot=False) + print "TEST len=", len(X_test) + + X_test = [one_hot_colors(x) for x in X_test] + Y_test_flat = [y_.ravel() for y_ in Y_test] + X_test_directions, X_test_edge_features = prepare_data(X_test) + Y_pred = ssvm.predict( convertToSingleTypeX(X_test_directions) ) + print("Results using only directional features for edges") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) + + # now, use more informative edge features: + crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]], inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + switch_to='ad3', + #JL adds a max-iter sometimes + #max_iter=100, + n_jobs=1) + t0 = time.time() + ssvm.fit( convertToSingleTypeX(X_train_edge_features) , Y_train_flat) + print "Training time = %.1fs"%(time.time()-t0) + + Y_pred2 = ssvm.predict( convertToSingleTypeX(X_test_edge_features) ) + print("Results using also input features for edges") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + + if False: + # plot stuff + fig, axes = plt.subplots(2, 2) + axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') + axes[0, 0].set_title('Input') + y = Y_test[0].astype(np.int) + bg = 2 * (y != 0) # enhance contrast + axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) + axes[0, 1].set_title("Ground Truth") + axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 0].set_title("Prediction w/o edge features") + axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 1].set_title("Prediction with edge features") + for a in axes.ravel(): + a.set_xticks(()) + a.set_yticks(()) + plt.show() + + + + +""" +---------------------------------------------------------------- +ALWAYS SHUFFLING!! + +WITHOUT HIDDEN SNAKES + +Please be patient. Learning will take 5-20 minutes. +200 200 +Snakes are ok +200 200 200 +TEST len= 100 +Results using only directional features for edges +Test accuracy: 0.847 +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 99 0 0 1 0 0 0 0 0 0] + [ 0 2 68 3 9 4 6 4 3 1 0] + [ 0 4 11 45 8 14 5 6 0 6 1] + [ 0 1 22 18 31 2 14 4 3 5 0] + [ 0 3 7 38 12 22 5 4 2 7 0] + [ 0 2 19 16 26 8 16 2 9 2 0] + [ 0 6 14 26 10 15 5 12 2 10 0] + [ 0 0 12 15 16 4 16 2 18 4 13] + [ 0 2 5 18 6 8 5 3 2 50 1] + [ 0 1 11 4 13 1 2 0 2 2 64]] +Training time = 37.5s +Results using also input features for edges +Test accuracy: 0.907 +[[2749 0 0 0 0 0 0 0 1 0 0] + [ 0 99 0 1 0 0 0 0 0 0 0] + [ 0 0 98 0 1 0 0 1 0 0 0] + [ 0 9 2 79 1 6 0 2 1 0 0] + [ 0 1 38 4 38 0 15 2 2 0 0] + [ 1 5 3 41 2 30 1 13 1 3 0] + [ 1 0 17 7 12 1 44 1 15 0 2] + [ 1 3 1 19 5 7 2 52 2 8 0] + [ 0 2 10 1 9 2 4 2 63 1 6] + [ 2 0 2 14 0 5 0 3 2 71 1] + [ 1 0 2 2 12 0 5 0 1 0 77]] + + -------------------------- +switch_to='ad3', + max-iter=100 + Results using also input features for edges +Test accuracy: 0.870 +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 1 94 2 1 0 0 1 0 0 1 0] + [ 0 7 88 0 0 0 2 0 2 0 1] + [ 0 30 11 41 0 7 0 9 0 2 0] + [ 4 6 38 11 17 3 7 0 13 0 1] + [ 2 9 10 25 4 24 3 13 2 8 0] + [ 0 9 18 9 8 6 23 1 19 1 6] + [ 2 9 9 12 6 10 4 34 2 11 1] + [ 0 8 13 3 4 3 4 1 54 2 8] + [ 10 8 6 6 1 3 1 4 2 57 2] + [ 1 3 3 4 4 0 0 0 6 0 79]] + + +-------------------------- +switch_to='ad3', +without max_iter +Results using also input features for edges +Test accuracy: 0.997 +[[2749 0 0 0 0 0 0 0 1 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 99 0 0 0 0 0 1 0] + [ 0 0 0 0 99 0 1 0 0 0 0] + [ 0 0 0 1 0 98 0 1 0 0 0] + [ 0 0 0 0 1 0 98 0 1 0 0] + [ 0 0 0 0 0 1 0 99 0 0 0] + [ 0 0 0 0 0 0 0 0 100 0 0] + [ 0 0 0 1 0 0 0 1 0 98 0] + [ 0 0 0 0 1 0 0 0 0 0 99]] + +---------------------------------------------------------------- + +SHUFFLING EITHER PIXELS OR SNAKE CELLS + +Please be patient. Learning will take 5-20 minutes. +200 200 +ADDING PICTURE WIHOUT SNAKES!!! 200 elements in train +400 400 +Snakes are ok +400 400 400 +TEST len= 100 +ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test +TEST len= 200 +Results using only directional features for edges +Test accuracy: 0.858 +[[6336 2 1 6 7 11 13 72 31 11 10] + [ 87 9 0 0 2 0 0 0 0 2 0] + [ 44 0 2 1 1 1 9 31 10 1 0] + [ 49 0 0 1 0 6 5 15 18 3 3] + [ 50 0 1 0 2 2 12 16 12 2 3] + [ 52 1 0 2 0 2 11 23 4 5 0] + [ 58 0 1 0 3 1 13 14 7 2 1] + [ 57 0 1 1 1 5 1 16 10 5 3] + [ 57 1 0 1 3 3 8 8 12 3 4] + [ 57 0 0 0 1 0 1 16 8 15 2] + [ 58 0 0 0 0 3 0 9 3 3 24]] +Training time = 44.0s +Results using also input features for edges +Test accuracy: 0.864 +[[6439 1 0 4 8 5 6 7 1 10 19] + [ 98 1 0 1 0 0 0 0 0 0 0] + [ 98 0 1 1 0 0 0 0 0 0 0] + [ 98 0 0 2 0 0 0 0 0 0 0] + [ 98 0 0 0 0 0 2 0 0 0 0] + [ 95 0 0 0 0 5 0 0 0 0 0] + [ 95 0 0 0 0 0 5 0 0 0 0] + [ 95 0 0 0 0 0 0 5 0 0 0] + [ 94 0 0 0 0 0 0 0 5 0 1] + [ 94 0 0 0 0 0 0 0 0 6 0] + [ 91 0 0 0 1 0 0 0 0 0 8]] + + + -------------------------- +switch_to='ad3', + max-iter=100 + +Training time = 34.5s +Results using also input features for edges +Test accuracy: 0.870 +[[6384 2 0 0 1 13 11 6 4 20 59] + [ 92 5 1 0 1 0 0 0 0 0 1] + [ 86 0 4 1 0 3 1 0 0 2 3] + [ 80 1 1 4 2 4 2 1 3 0 2] + [ 79 0 1 3 3 3 3 2 2 4 0] + [ 74 0 1 0 2 8 2 5 3 1 4] + [ 69 0 0 2 0 4 10 1 8 4 2] + [ 66 0 0 0 2 0 2 11 3 11 5] + [ 58 0 0 0 1 2 0 3 23 2 11] + [ 57 0 0 0 0 1 1 2 0 34 5] + [ 57 0 0 0 0 0 0 1 0 0 42]] + -------------------------- +switch_to='ad3', +without max-iter + +Training time = 1346.7s +Results using also input features for edges +Test accuracy: 0.987 +[[6437 7 8 8 4 2 1 0 7 14 12] + [ 2 97 0 0 0 1 0 0 0 0 0] + [ 2 0 97 0 1 0 0 0 0 0 0] + [ 0 0 0 97 0 2 0 1 0 0 0] + [ 0 0 1 0 96 0 2 0 1 0 0] + [ 0 0 0 2 0 95 0 3 0 0 0] + [ 0 0 1 0 2 0 94 0 3 0 0] + [ 0 0 0 1 0 3 0 93 0 3 0] + [ 0 0 1 0 1 0 1 0 97 0 0] + [ 0 0 0 0 0 1 0 1 0 98 0] + [ 0 0 0 0 0 0 1 0 1 0 98]] + + +""" \ No newline at end of file From 6fa4d986471ebbf20929609d2d3352a4b5120866 Mon Sep 17 00:00:00 2001 From: meunier Date: Mon, 16 Jan 2017 10:15:14 +0100 Subject: [PATCH 014/155] usual code without the plot at the end --- examples/plot_snakes.py | 43 +++++++++++++++++------------------------ 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/examples/plot_snakes.py b/examples/plot_snakes.py index 57201fc3..c535060d 100644 --- a/examples/plot_snakes.py +++ b/examples/plot_snakes.py @@ -96,12 +96,6 @@ def prepare_data(X): snakes = load_snakes() X_train, Y_train = snakes['X_train'], snakes['Y_train'] - #JL - X_train, Y_train = X_train[:40], Y_train[:40] - print len(X_train), len(Y_train) - print X_train[0].shape - print Y_train[0].shape - X_train = [one_hot_colors(x) for x in X_train] Y_train_flat = [y_.ravel() for y_ in Y_train] @@ -125,12 +119,10 @@ def prepare_data(X): print("Test accuracy: %.3f" % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) - + # now, use more informative edge features: crf = EdgeFeatureGraphCRF(inference_method=inference) ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', - #JL - max_iter=20, n_jobs=-1) ssvm.fit(X_train_edge_features, Y_train_flat) Y_pred2 = ssvm.predict(X_test_edge_features) @@ -139,19 +131,20 @@ def prepare_data(X): % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) - # plot stuff - fig, axes = plt.subplots(2, 2) - axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') - axes[0, 0].set_title('Input') - y = Y_test[0].astype(np.int) - bg = 2 * (y != 0) # enhance contrast - axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) - axes[0, 1].set_title("Ground Truth") - axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 0].set_title("Prediction w/o edge features") - axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 1].set_title("Prediction with edge features") - for a in axes.ravel(): - a.set_xticks(()) - a.set_yticks(()) - plt.show() + if False: + # plot stuff + fig, axes = plt.subplots(2, 2) + axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') + axes[0, 0].set_title('Input') + y = Y_test[0].astype(np.int) + bg = 2 * (y != 0) # enhance contrast + axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) + axes[0, 1].set_title("Ground Truth") + axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 0].set_title("Prediction w/o edge features") + axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 1].set_title("Prediction with edge features") + for a in axes.ravel(): + a.set_xticks(()) + a.set_yticks(()) + plt.show() From a8260025a49bac56995d354b49c48876d9841e01 Mon Sep 17 00:00:00 2001 From: meunier Date: Mon, 16 Jan 2017 10:47:35 +0100 Subject: [PATCH 015/155] The snake example with the NodeTypeEdgeFeatureGraphCRF class --- examples/plot_snakes_typed.py | 96 +++++++++++++++++++++-------------- 1 file changed, 59 insertions(+), 37 deletions(-) diff --git a/examples/plot_snakes_typed.py b/examples/plot_snakes_typed.py index e2b25f38..36edd717 100644 --- a/examples/plot_snakes_typed.py +++ b/examples/plot_snakes_typed.py @@ -3,8 +3,9 @@ Conditional Interactions on the Snakes Dataset ============================================== -This is a varaint of plot_snakes.py where we use the NodeTypeEdgeFeatureGraphCRF +This is a variant of plot_snakes.py where we use the NodeTypeEdgeFeatureGraphCRF class instead of EdgeFeatureGraphCRF, despite there is only 1 type of nodes. +So this should give exact same results as plot_snakes.py This example uses the snake dataset introduced in @@ -61,24 +62,16 @@ def convertToSingleTypeX(X): snakes = load_snakes() X_train, Y_train = snakes['X_train'], snakes['Y_train'] - #JL -# X_train, Y_train = X_train[:40], Y_train[:40] -# print len(X_train), len(Y_train) -# print X_train[0].shape -# print Y_train[0].shape - X_train = [one_hot_colors(x) for x in X_train] Y_train_flat = [y_.ravel() for y_ in Y_train] - + + X_train_directions, X_train_edge_features = prepare_data(X_train) - - #CHANGE!! - #We require AD3 and NodeTypeEdgeFeatureGraphCRF - #inference = 'qpbo' + + inference = 'qpbo' # first, train on X with directions only: - #crf = NodeTypeEdgeFeatureGraphCRF(inference_method=inference) - crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[2]]) - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, + crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[2]], inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, n_jobs=1) ssvm.fit(convertToSingleTypeX(X_train_directions), Y_train_flat) @@ -93,13 +86,10 @@ def convertToSingleTypeX(X): print("Test accuracy: %.3f" % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) - + # now, use more informative edge features: - crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]]) - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, - #switch_to='ad3', - #CHANGE: AD3 by default and only 100 iterations to save time and energy... - max_iter=100, + crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]], inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', n_jobs=-1) ssvm.fit( convertToSingleTypeX(X_train_edge_features), Y_train_flat) Y_pred2 = ssvm.predict( convertToSingleTypeX(X_test_edge_features) ) @@ -108,19 +98,51 @@ def convertToSingleTypeX(X): % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) - # plot stuff - fig, axes = plt.subplots(2, 2) - axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') - axes[0, 0].set_title('Input') - y = Y_test[0].astype(np.int) - bg = 2 * (y != 0) # enhance contrast - axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) - axes[0, 1].set_title("Ground Truth") - axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 0].set_title("Prediction w/o edge features") - axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 1].set_title("Prediction with edge features") - for a in axes.ravel(): - a.set_xticks(()) - a.set_yticks(()) - plt.show() + if False: + # plot stuff + fig, axes = plt.subplots(2, 2) + axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') + axes[0, 0].set_title('Input') + y = Y_test[0].astype(np.int) + bg = 2 * (y != 0) # enhance contrast + axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) + axes[0, 1].set_title("Ground Truth") + axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 0].set_title("Prediction w/o edge features") + axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 1].set_title("Prediction with edge features") + for a in axes.ravel(): + a.set_xticks(()) + a.set_yticks(()) + plt.show() + +""" +Please be patient. Learning will take 5-20 minutes. +Results using only directional features for edges +Test accuracy: 0.847 +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 99 0 0 1 0 0 0 0 0 0] + [ 0 2 68 3 9 4 6 4 3 1 0] + [ 0 4 11 45 8 14 5 6 0 6 1] + [ 0 1 22 18 31 2 14 4 3 5 0] + [ 0 3 7 38 12 22 5 4 2 7 0] + [ 0 2 19 16 26 8 16 2 9 2 0] + [ 0 6 14 26 10 15 5 12 2 10 0] + [ 0 0 12 15 16 4 16 2 18 4 13] + [ 0 2 5 18 6 8 5 3 2 50 1] + [ 0 1 11 4 13 1 2 0 2 2 64]] +Results using also input features for edges +Test accuracy: 0.998 +[[2749 0 0 0 0 0 0 0 1 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 99 0 0 0 0 0 1 0] + [ 0 0 0 0 99 0 1 0 0 0 0] + [ 0 0 0 1 0 98 0 1 0 0 0] + [ 0 0 0 0 1 0 99 0 0 0 0] + [ 0 0 0 0 0 1 0 99 0 0 0] + [ 0 0 0 0 0 0 0 0 100 0 0] + [ 0 0 0 0 0 0 0 1 0 99 0] + [ 0 0 0 0 0 0 0 0 0 0 100]] + +""" \ No newline at end of file From e04d4e5afd945385c488c6c28c1fa34080f3da6a Mon Sep 17 00:00:00 2001 From: meunier Date: Mon, 16 Jan 2017 10:50:12 +0100 Subject: [PATCH 016/155] The snake example, with additional pictures where there is no snake, althought there are pixels os snake cell color. This is because snakes hide!! :) --- examples/plot_hidden_snakes.py | 137 ++++++++++++++++++++++++++++++--- 1 file changed, 126 insertions(+), 11 deletions(-) diff --git a/examples/plot_hidden_snakes.py b/examples/plot_hidden_snakes.py index f101c9d2..ce6f3e0f 100644 --- a/examples/plot_hidden_snakes.py +++ b/examples/plot_hidden_snakes.py @@ -118,14 +118,41 @@ def shuffleSnakeCells(a_picture, bOneHot=True): #in place!! a_picture[_ai,_aj,:] = a_picture[ai,aj,:] return a_picture +def changeOneSnakeCell(a_picture, bOneHot=True): #in place!! + """ + Change the color of 1 snake cells + """ + if bOneHot: + ai, aj = np.where(a_picture[...,3] != 1) + else: + _p = np.copy(a_picture) + _p = one_hot_colors(_p) + ai, aj = np.where(_p[...,3] != 1) + assert len(ai) == 10 + + iChange = random.randint(0,9) + + while True: + iFromCell = random.randint(0,9) + if (a_picture[ai[iChange], aj[iChange],:] != a_picture[ai[iFromCell], aj[iFromCell],:]).any(): + a_picture[ai[iChange], aj[iChange],:] = a_picture[ai[iFromCell], aj[iFromCell],:] + #so that we do not care about which color is valid... + break + + return a_picture + def shuffleSnake(a_picture, bOneHot=True): """ Shuffle either the snake's cells or the pcitures' pixels. """ - if random.randint(0,1): - shuffleSnakeCells(a_picture, bOneHot) + if True: + changeOneSnakeCell(a_picture, bOneHot) + changeOneSnakeCell(a_picture, bOneHot) else: - shufflePictureCells(a_picture) + if random.randint(0,1): + shuffleSnakeCells(a_picture, bOneHot) + else: + shufflePictureCells(a_picture) def convertToSingleTypeX(X): """ @@ -312,8 +339,9 @@ def shuffle_XY(X,Y): [ 1 0 2 2 12 0 5 0 1 0 77]] -------------------------- -switch_to='ad3', - max-iter=100 + switch_to='ad3', + max-iter=100 + Results using also input features for edges Test accuracy: 0.870 [[2750 0 0 0 0 0 0 0 0 0 0] @@ -330,8 +358,9 @@ def shuffle_XY(X,Y): -------------------------- -switch_to='ad3', -without max_iter + switch_to='ad3', + without max_iter + Results using also input features for edges Test accuracy: 0.997 [[2749 0 0 0 0 0 0 0 1 0 0] @@ -389,8 +418,8 @@ def shuffle_XY(X,Y): -------------------------- -switch_to='ad3', - max-iter=100 + switch_to='ad3', + max-iter=100 Training time = 34.5s Results using also input features for edges @@ -407,8 +436,8 @@ def shuffle_XY(X,Y): [ 57 0 0 0 0 1 1 2 0 34 5] [ 57 0 0 0 0 0 0 1 0 0 42]] -------------------------- -switch_to='ad3', -without max-iter + switch_to='ad3', + without max-iter Training time = 1346.7s Results using also input features for edges @@ -426,4 +455,90 @@ def shuffle_XY(X,Y): [ 0 0 0 0 0 0 1 0 1 0 98]] + +---------------------------------------------------------------- +CHANGING ONE CELL OF THE SNAKE + switch_to='ad3', + without max-iter + + Please be patient. Learning will take 5-20 minutes. +200 200 +ADDING PICTURE WIHOUT SNAKES!!! 200 elements in train +400 400 +Snakes are ok +400 400 400 +TEST len= 100 +ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test +TEST len= 200 +Results using only directional features for edges +Test accuracy: 0.857 +[[6355 0 0 0 4 26 0 8 1 4 102] + [ 100 0 0 0 0 0 0 0 0 0 0] + [ 91 0 0 0 0 9 0 0 0 0 0] + [ 91 0 0 0 0 0 0 0 0 0 9] + [ 99 0 0 0 0 0 0 0 0 0 1] + [ 96 0 0 0 0 1 0 1 0 0 2] + [ 97 0 0 0 1 0 0 0 1 0 1] + [ 95 0 0 0 0 4 0 1 0 0 0] + [ 86 0 0 0 2 0 0 0 1 0 11] + [ 70 0 0 0 0 13 0 3 0 7 7] + [ 34 0 0 0 0 0 0 2 0 0 64]] +Training time = 1852.6s +Results using also input features for edges +Test accuracy: 0.904 +[[6185 25 25 25 25 24 25 32 39 42 53] + [ 41 58 0 0 0 0 1 0 0 0 0] + [ 41 0 56 0 2 0 0 1 0 0 0] + [ 41 0 1 56 0 2 0 0 0 0 0] + [ 39 0 0 1 56 0 4 0 0 0 0] + [ 39 0 0 0 1 58 0 2 0 0 0] + [ 39 0 0 0 0 1 59 0 1 0 0] + [ 38 0 0 0 0 0 1 60 0 1 0] + [ 36 1 0 0 0 0 0 0 62 0 1] + [ 36 0 0 1 1 0 0 0 0 62 0] + [ 32 1 0 0 1 1 0 0 0 0 65]] + + +---------------------------------------------------------------- +CHANGING TWO CELLs OF THE SNAKE + switch_to='ad3', + without max-iter + +Please be patient. Learning will take 5-20 minutes. +200 200 +ADDING PICTURE WIHOUT SNAKES!!! 200 elements in train +400 400 +Snakes are ok +400 400 400 +TEST len= 100 +ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test +TEST len= 200 +Results using only directional features for edges +Test accuracy: 0.853 +[[6318 5 13 8 5 9 26 18 25 30 43] + [ 93 5 0 0 0 1 0 0 0 1 0] + [ 86 0 3 0 1 0 5 0 2 3 0] + [ 84 0 0 0 0 3 3 3 3 4 0] + [ 84 0 0 0 1 1 5 1 4 4 0] + [ 82 0 0 2 1 5 2 2 4 2 0] + [ 80 0 3 0 0 2 8 3 1 3 0] + [ 79 0 1 1 0 2 4 3 4 6 0] + [ 74 1 1 2 2 0 5 0 8 5 2] + [ 71 0 3 0 0 3 3 3 4 13 0] + [ 51 0 0 3 0 0 2 2 4 1 37]] +Training time = 2100.8s +Results using also input features for edges +Test accuracy: 0.941 +[[6204 26 30 29 25 26 29 23 26 35 47] + [ 11 88 0 0 0 0 1 0 0 0 0] + [ 11 0 87 0 0 1 0 1 0 0 0] + [ 10 1 1 85 0 1 1 1 0 0 0] + [ 9 0 1 1 83 1 3 0 2 0 0] + [ 9 0 0 1 1 83 1 3 0 2 0] + [ 8 0 1 0 2 2 83 0 3 0 1] + [ 8 0 0 1 0 2 2 85 0 2 0] + [ 8 0 0 0 1 0 2 1 86 0 2] + [ 8 0 0 0 0 1 0 1 1 89 0] + [ 8 0 0 0 0 0 2 0 1 1 88]] + """ \ No newline at end of file From 2fdc4092741f30048ccd887c700d17d47f42c3a8 Mon Sep 17 00:00:00 2001 From: meunier Date: Mon, 16 Jan 2017 13:33:55 +0100 Subject: [PATCH 017/155] minor --- examples/plot_hidden_snakes.py | 18 +- examples/plot_hidden_snakes_typed.py | 307 +++++++++++++++++++++++++++ 2 files changed, 317 insertions(+), 8 deletions(-) create mode 100644 examples/plot_hidden_snakes_typed.py diff --git a/examples/plot_hidden_snakes.py b/examples/plot_hidden_snakes.py index ce6f3e0f..5ff4a69b 100644 --- a/examples/plot_hidden_snakes.py +++ b/examples/plot_hidden_snakes.py @@ -166,6 +166,9 @@ def plot_snake(picture): plt.show() def augmentWithNoSnakeImages(X,Y, name, bOneHot=True): + """ + return the number of added picture (AT THE END OF INPUT LISTS) + """ print "ADDING PICTURE WIHOUT SNAKES!!! %d elements in %s"%(len(X), name) X_NoSnake = [np.copy(x) for x in X] @@ -182,13 +185,12 @@ def augmentWithNoSnakeImages(X,Y, name, bOneHot=True): Y_NoSnake.append(np.zeros(y.shape, dtype=np.int8)) X_NoSnake = newX - return X+X_NoSnake, Y+Y_NoSnake + return len(X_NoSnake), X+X_NoSnake, Y+Y_NoSnake -def shuffle_XY(X,Y): - lxy = zip(X, Y) - random.shuffle(lxy) - X, Y = zip(*lxy) - return X, Y +def shuffle_in_unison(*args): + lTuple = zip(*args) + random.shuffle(lTuple) + return zip(*lTuple) if __name__ == '__main__': print("Please be patient. Learning will take 5-20 minutes.") @@ -205,7 +207,7 @@ def shuffle_XY(X,Y): #print `X_train[0]` if bADD_HIDDEN_SNAKES: - X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False) + _, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False) print len(X_train), len(Y_train) if False: @@ -249,7 +251,7 @@ def shuffle_XY(X,Y): X_test, Y_test = snakes['X_test'], snakes['Y_test'] print "TEST len=", len(X_test) if bADD_HIDDEN_SNAKES: - X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", bOneHot=False) + _, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", bOneHot=False) print "TEST len=", len(X_test) X_test = [one_hot_colors(x) for x in X_test] diff --git a/examples/plot_hidden_snakes_typed.py b/examples/plot_hidden_snakes_typed.py new file mode 100644 index 00000000..81906fbd --- /dev/null +++ b/examples/plot_hidden_snakes_typed.py @@ -0,0 +1,307 @@ +""" +============================================== +Conditional Interactions on the Snakes Dataset +============================================== + +This is a variant of plot_snakes.py + +Snake are hidding, so another task is both to determine if a snake is in the picture, and +identify its head to tail body. + +We use the NodeTypeEdgeFeatureGraphCRF class with 2 type of nodes. + + +This example uses the snake dataset introduced in +Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 + +This dataset is specifically designed to require the pairwise interaction terms +to be conditioned on the input, in other words to use non-trival edge-features. + +The task is as following: a "snake" of length ten wandered over a grid. For +each cell, it had the option to go up, down, left or right (unless it came from +there). The input consists of these decisions, while the desired output is an +annotation of the snake from 0 (head) to 9 (tail). See the plots for an +example. + +As input features we use a 3x3 window around each pixel (and pad with background +where necessary). We code the five different input colors (for up, down, left, right, +background) using a one-hot encoding. This is a rather naive approach, not using any +information about the dataset (other than that it is a 2d grid). + +The task can not be solved using the simple DirectionalGridCRF - which can only +infer head and tail (which are also possible to infer just from the unary +features). If we add edge-features that contain the features of the nodes that are +connected by the edge, the CRF can solve the task. + +From an inference point of view, this task is very hard. QPBO move-making is +not able to solve it alone, so we use the relaxed AD3 inference for learning. + +PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). +But it does work as well as Decision Tree Fields ;) +""" +import numpy as np +import matplotlib.pyplot as plt +import random +from sklearn.preprocessing import label_binarize +from sklearn.metrics import confusion_matrix, accuracy_score +import time + +from pystruct.learners import OneSlackSSVM +from pystruct.datasets import load_snakes +from pystruct.utils import make_grid_edges, edge_list_to_features +#from pystruct.models import EdgeFeatureGraphCRF +from pystruct.models import NodeTypeEdgeFeatureGraphCRF + +from plot_snakes import one_hot_colors, neighborhood_feature, prepare_data + +def isSnakePresent(a_hot_picture): + """ + Algorithmic check, to make sure that after shuffling we do not have a snake! :-) + work on the 1-hot encoded picture + """ + try: + ai, aj = np.where(a_hot_picture[...,3] != 1) + if len(ai) != 10: return False + lij = zip(ai, aj) + for n in range(10): + _lij = shiftSnake(a_hot_picture, lij) + if len(_lij) != len(lij)-1: return False + lij = _lij + if len(_lij) != 0: return False + return True + except: + return False + +def shiftSnake(a_hot_picture, lij): + #the snake moves by one cell, head disappearing in sand + _lij = list() + for i,j in lij: + color_index = np.where(a_hot_picture[i,j,:]==1)[0][0] + dj = np.array( [ 0, 0, 1, None, -1])[color_index] + di = np.array( [-1, 1, 0, None, 0])[color_index] + i,j = i+di,j+dj + if a_hot_picture[i,j,3] != 1: #backgroun + _lij.append((i,j)) + return _lij + +def shufflePictureCells(a_picture): #in place!! + """ + Shuffle the pixels + """ + n = random.randint(1,4) + if n == 1: + map(np.random.shuffle, a_picture) + elif n == 2: + map(np.random.shuffle, np.transpose(a_picture, (1,0,2))) + else: + map(np.random.shuffle, a_picture) + map(np.random.shuffle, np.transpose(a_picture, (1,0,2))) + + return a_picture + +def shuffleSnakeCells(a_picture, bOneHot=True): #in place!! + """ + Shuffle the colors of the 10 snake cells + """ + if bOneHot: + ai, aj = np.where(a_picture[...,3] != 1) + else: + _p = np.copy(a_picture) + _p = one_hot_colors(_p) + ai, aj = np.where(_p[...,3] != 1) + assert len(ai) == 10 + + l_shuffled_aij = zip(ai,aj) + random.shuffle( l_shuffled_aij ) + _ai, _aj = zip(*l_shuffled_aij) + + a_picture[_ai,_aj,:] = a_picture[ai,aj,:] + return a_picture + +def changeOneSnakeCell(a_picture, bOneHot=True): #in place!! + """ + Change the color of 1 snake cells + """ + if bOneHot: + ai, aj = np.where(a_picture[...,3] != 1) + else: + _p = np.copy(a_picture) + _p = one_hot_colors(_p) + ai, aj = np.where(_p[...,3] != 1) + assert len(ai) == 10 + + iChange = random.randint(0,9) + + while True: + iFromCell = random.randint(0,9) + if (a_picture[ai[iChange], aj[iChange],:] != a_picture[ai[iFromCell], aj[iFromCell],:]).any(): + a_picture[ai[iChange], aj[iChange],:] = a_picture[ai[iFromCell], aj[iFromCell],:] + #so that we do not care about which color is valid... + break + + return a_picture + +def shuffleSnake(a_picture, bOneHot=True): + """ + Shuffle either the snake's cells or the pcitures' pixels. + """ + if True: + changeOneSnakeCell(a_picture, bOneHot) + changeOneSnakeCell(a_picture, bOneHot) + else: + if random.randint(0,1): + shuffleSnakeCells(a_picture, bOneHot) + else: + shufflePictureCells(a_picture) + +def convertToSingleTypeX(X): + """ + For NodeTypeEdgeFeatureGraphCRF X is structured differently. + But NodeTypeEdgeFeatureGraphCRF can handle graph with a single node type. One needs to convert X to the new structure using this method. + """ + return [([nf], [e], [ef]) for (nf,e,ef) in X] + +def plot_snake(picture): + plt.imshow(picture, interpolation='nearest') + plt.show() + +def augmentWithNoSnakeImages(X,Y, name, bOneHot=True): + print "ADDING PICTURE WIHOUT SNAKES!!! %d elements in %s"%(len(X), name) + + X_NoSnake = [np.copy(x) for x in X] + for x in X_NoSnake: shuffleSnake(x, bOneHot) + #map(shufflePictureCells, X_NoSnake) + + newX = list() + Y_NoSnake = list() + for x,y in zip(X_NoSnake, Y): + if isSnakePresent(x): + print "\t- DISCARDING a shuffled snake which is still a snake!!!!" + else: + newX.append(x) + Y_NoSnake.append(np.zeros(y.shape, dtype=np.int8)) + X_NoSnake = newX + + return X+X_NoSnake, Y+Y_NoSnake + +def shuffle_XY(X,Y): + lxy = zip(X, Y) + random.shuffle(lxy) + X, Y = zip(*lxy) + return X, Y + +if __name__ == '__main__': + print("Please be patient. Learning will take 5-20 minutes.") + snakes = load_snakes() + X_train, Y_train = snakes['X_train'], snakes['Y_train'] + + bSHUFFLE = True + + bADD_HIDDEN_SNAKES = True + #bADD_HIDDEN_SNAKES = False + #JL + #X_train, Y_train = X_train[:10], Y_train[:10] + print len(X_train), len(Y_train) + #print `X_train[0]` + + if bADD_HIDDEN_SNAKES: + X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False) + print len(X_train), len(Y_train) + + if False: + #show the faked pictures + for ix, x in enumerate(X_train): plot_snake(shufflePictureCells(x)) + + X_train_hot = [one_hot_colors(x) for x in X_train] + + if False: + for ix, x in enumerate(X_train_hot): + if not isSnakePresent(x): plot_snake(X_train[ix]) + + X_train = X_train_hot + print "Snakes are ok" + + + if bSHUFFLE: + #let's shuffle our data + X_train, Y_train = shuffle_XY(X_train, Y_train) + + # ------------------------------------------------------------------------------------- + X_train_directions, X_train_edge_features = prepare_data(X_train) + + Y_train_flat = [y_.ravel() for y_ in Y_train] + + inference = 'qpbo' + # first, train on X with directions only: + #CHANGE!! + #We require NodeTypeEdgeFeatureGraphCRF + #crf = NodeTypeEdgeFeatureGraphCRF(inference_method=inference) + crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[2]], inference_method=inference) + XX = convertToSingleTypeX(X_train_directions) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + max_iter=100, + n_jobs=1) + print len(XX), len(Y_train), len(Y_train_flat) + ssvm.fit(XX, Y_train_flat) + + # Evaluate using confusion matrix. + # Clearly the middel of the snake is the hardest part. + X_test, Y_test = snakes['X_test'], snakes['Y_test'] + print "TEST len=", len(X_test) + if bADD_HIDDEN_SNAKES: + X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", bOneHot=False) + print "TEST len=", len(X_test) + + X_test = [one_hot_colors(x) for x in X_test] + Y_test_flat = [y_.ravel() for y_ in Y_test] + X_test_directions, X_test_edge_features = prepare_data(X_test) + Y_pred = ssvm.predict( convertToSingleTypeX(X_test_directions) ) + print("Results using only directional features for edges") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) + + # now, use more informative edge features: + crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]], inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + switch_to='ad3', + #JL adds a max-iter sometimes + #max_iter=100, + n_jobs=1) + t0 = time.time() + ssvm.fit( convertToSingleTypeX(X_train_edge_features) , Y_train_flat) + print "Training time = %.1fs"%(time.time()-t0) + + Y_pred2 = ssvm.predict( convertToSingleTypeX(X_test_edge_features) ) + print("Results using also input features for edges") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + + if False: + # plot stuff + fig, axes = plt.subplots(2, 2) + axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') + axes[0, 0].set_title('Input') + y = Y_test[0].astype(np.int) + bg = 2 * (y != 0) # enhance contrast + axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) + axes[0, 1].set_title("Ground Truth") + axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 0].set_title("Prediction w/o edge features") + axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 1].set_title("Prediction with edge features") + for a in axes.ravel(): + a.set_xticks(()) + a.set_yticks(()) + plt.show() + + + + +""" + + + + +""" \ No newline at end of file From a9726a65ba582cc7caaeab4e28784a39b89006e6 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 20 Jan 2017 09:19:21 +0100 Subject: [PATCH 018/155] code ok --- examples/plot_hidden_snakes.py | 6 +- examples/plot_hidden_snakes_logit.py | 141 +++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 4 deletions(-) create mode 100644 examples/plot_hidden_snakes_logit.py diff --git a/examples/plot_hidden_snakes.py b/examples/plot_hidden_snakes.py index 5ff4a69b..582f47a5 100644 --- a/examples/plot_hidden_snakes.py +++ b/examples/plot_hidden_snakes.py @@ -182,7 +182,7 @@ def augmentWithNoSnakeImages(X,Y, name, bOneHot=True): print "\t- DISCARDING a shuffled snake which is still a snake!!!!" else: newX.append(x) - Y_NoSnake.append(np.zeros(y.shape, dtype=np.int8)) + Y_NoSnake.append(np.zeros(y.shape, dtype=np.int32)) X_NoSnake = newX return len(X_NoSnake), X+X_NoSnake, Y+Y_NoSnake @@ -221,12 +221,10 @@ def shuffle_in_unison(*args): if not isSnakePresent(x): plot_snake(X_train[ix]) X_train = X_train_hot - print "Snakes are ok" - if bSHUFFLE: #let's shuffle our data - X_train, Y_train = shuffle_XY(X_train, Y_train) + X_train, Y_train = shuffle_in_unison(X_train, Y_train) # ------------------------------------------------------------------------------------- X_train_directions, X_train_edge_features = prepare_data(X_train) diff --git a/examples/plot_hidden_snakes_logit.py b/examples/plot_hidden_snakes_logit.py new file mode 100644 index 00000000..e75c24ae --- /dev/null +++ b/examples/plot_hidden_snakes_logit.py @@ -0,0 +1,141 @@ +""" +============================================== +Conditional Interactions on the Snakes Dataset +============================================== + +This is a variant of plot_snakes.py + +Snake are hidding, so another task is both to determine if a snake is in the picture, and +identify its head to tail body. + +We use the Logit and some picture feature to categorize pictures (only this task) + + +This example uses the snake dataset introduced in +Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 + +This dataset is specifically designed to require the pairwise interaction terms +to be conditioned on the input, in other words to use non-trival edge-features. + +The task is as following: a "snake" of length ten wandered over a grid. For +each cell, it had the option to go up, down, left or right (unless it came from +there). The input consists of these decisions, while the desired output is an +annotation of the snake from 0 (head) to 9 (tail). See the plots for an +example. + +As input features we use a 3x3 window around each pixel (and pad with background +where necessary). We code the five different input colors (for up, down, left, right, +background) using a one-hot encoding. This is a rather naive approach, not using any +information about the dataset (other than that it is a 2d grid). + +The task can not be solved using the simple DirectionalGridCRF - which can only +infer head and tail (which are also possible to infer just from the unary +features). If we add edge-features that contain the features of the nodes that are +connected by the edge, the CRF can solve the task. + +From an inference point of view, this task is very hard. QPBO move-making is +not able to solve it alone, so we use the relaxed AD3 inference for learning. + +PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). +But it does work as well as Decision Tree Fields ;) +""" +import numpy as np +import matplotlib.pyplot as plt +import random +import time + +from sklearn.metrics import confusion_matrix, accuracy_score +from sklearn.linear_model import LogisticRegression +from sklearn.grid_search import GridSearchCV + +from pystruct.datasets import load_snakes + +from plot_snakes import one_hot_colors, neighborhood_feature, prepare_data + +from plot_hidden_snakes import shufflePictureCells, shuffleSnakeCells, changeOneSnakeCell, augmentWithNoSnakeImages, shuffle_in_unison +from plot_hidden_snakes_typed import prepare_picture_data + +def shuffleSnake(a_picture, bOneHot=True): + """ + Shuffle either the snake's cells or the pcitures' pixels. + """ + if True: + changeOneSnakeCell(a_picture, bOneHot) + changeOneSnakeCell(a_picture, bOneHot) + else: + if random.randint(0,1): + shuffleSnakeCells(a_picture, bOneHot) + else: + shufflePictureCells(a_picture) + +def convertToSingleTypeX(X): + """ + For NodeTypeEdgeFeatureGraphCRF X is structured differently. + But NodeTypeEdgeFeatureGraphCRF can handle graph with a single node type. One needs to convert X to the new structure using this method. + """ + return [([nf], [e], [ef]) for (nf,e,ef) in X] + +def plot_snake(picture): + plt.imshow(picture, interpolation='nearest') + plt.show() + + +if __name__ == '__main__': + print("Please be patient. Learning will take 5-20 minutes.") + snakes = load_snakes() + X_train, Y_train = snakes['X_train'], snakes['Y_train'] + + bADD_HIDDEN_SNAKES = True + #bADD_HIDDEN_SNAKES = False + #JL + #X_train, Y_train = X_train[:10], Y_train[:10] + print len(X_train), len(Y_train) + #print `X_train[0]` + + if bADD_HIDDEN_SNAKES: + nb_hidden, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False) + print len(X_train), len(Y_train) + Y_train_pict = np.array([1]*(len(X_train)-nb_hidden) + [0]*nb_hidden) + + if False: + #show the faked pictures + for ix, x in enumerate(X_train): plot_snake(shufflePictureCells(x)) + + X_train = [one_hot_colors(x) for x in X_train] + + X_train, Y_train, Y_train_pict = shuffle_in_unison(X_train, Y_train, Y_train_pict) + + X_train_pict_feat = prepare_picture_data(X_train) + X_train_pict_feat = np.vstack(X_train_pict_feat) + print "X_train_pict_feat.shape ", X_train_pict_feat.shape + lr = LogisticRegression(class_weight='balanced') + dicGS = {'C':[0.1, 0.5, 1.0, 2.0] } + dicGS = {'C':[1.0] } + mdl = GridSearchCV(lr , dicGS) + + print "-training a logistic regression model on pictures" + mdl.fit(X_train_pict_feat, Y_train_pict) + + # --- TEST + X_test, Y_test = snakes['X_test'], snakes['Y_test'] + print "TEST len=", len(X_test) + if bADD_HIDDEN_SNAKES: + nb_hidden, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", bOneHot=False) + print "TEST len=", len(X_test) + Y_test_pict = np.array([1]*(len(X_test)-nb_hidden) + [0]*nb_hidden) + + X_test = [one_hot_colors(x) for x in X_test] + X_test_pict_feat = prepare_picture_data(X_test) + X_test_pict_feat = np.vstack(X_test_pict_feat) + + Y_pred = mdl.predict( X_test_pict_feat ) + print("Results using only directional features for edges") + print("Test accuracy: %.3f" + % accuracy_score(Y_test_pict, Y_pred)) + print(confusion_matrix(Y_test_pict, Y_pred)) + + +""" + + + """ \ No newline at end of file From 6e81733c820e3980046c8307ff5329f27b00c595 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 20 Jan 2017 12:22:33 +0100 Subject: [PATCH 019/155] READ ackn --- examples/plot_snakes_constraints.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/examples/plot_snakes_constraints.py b/examples/plot_snakes_constraints.py index a15d0553..dfdc55a6 100644 --- a/examples/plot_snakes_constraints.py +++ b/examples/plot_snakes_constraints.py @@ -32,6 +32,15 @@ UPDATE: we also inject domain knowledge at inference time by telling that there is at-most or exactly one of each annotation from 1 to 10 (0 is background). + + JL Meunier - January 2017 + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943 + + Copyright Xerox + """ import time import numpy as np @@ -101,6 +110,7 @@ def prepare_data(X): print("Please be patient. Learning will take 5-20 minutes.") snakes = load_snakes() X_train, Y_train = snakes['X_train'], snakes['Y_train'] +#X_train, Y_train = X_train[:5], Y_train[:5] X_train = [one_hot_colors(x) for x in X_train] Y_train_flat = [y_.ravel() for y_ in Y_train] From d346386d3560c64054e2732618ffcb7a34bc95fc Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 20 Jan 2017 16:21:19 +0100 Subject: [PATCH 020/155] fixed a few data structure msitake (following stricter checks in lib) --- .../test_node_type_edge_feature_graph_crf.py | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py index c8389437..c0e32963 100644 --- a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py +++ b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py @@ -93,7 +93,7 @@ def debug_joint_feature(): , None ] - x = [l_node_f, l_edges, l_edge_f] + x = (l_node_f, l_edges, l_edge_f) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([ np.array([0, 1]), np.array([0, 1, 2]) @@ -155,7 +155,7 @@ def test_joint_feature(): print "---SIMPLE---------------------------------------------------------------------" g, (node_f, edges, edge_f) = get_simple_graph_structure(), get_simple_graph() - x = [node_f, edges, edge_f] + x = (node_f, edges, edge_f) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.array([1,2]) @@ -192,7 +192,7 @@ def test_joint_feature(): y = np.array([0,1]) node_f = [ np.array([[1.1,1.2,1.3], [2.1,2.2,2.3]]) ] edge_f = [ np.array([[3.1,3.2,3.3]]) ] - x = [node_f, edges, edge_f] + x = (node_f, edges, edge_f) g.initialize(x, y) jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` @@ -208,7 +208,7 @@ def test_joint_feature(): print "---SIMPLE + 2nd EDGE--------------------------------------------------------" node_f, edges, edge_f = get_simple_graph2() - x = [node_f, edges, edge_f] + x = (node_f, edges, edge_f) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.array([1,2]) print y @@ -267,7 +267,7 @@ def test_joint_feature2(): , None ] - x = [node_f, edges, edge_f] + x = (node_f, edges, edge_f) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([ np.array([0, 0]) , np.array([0, 0, 0]) @@ -311,7 +311,7 @@ def test_joint_feature2(): , None ] - x = [ node_f, edges, edge_f] + x = ( node_f, edges, edge_f) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([np.array([0, 1]), np.array([0, 1, 2])]) @@ -347,7 +347,7 @@ def test_joint_feature2(): , None ] - x = [ node_f, edges, edge_f] + x = ( node_f, edges, edge_f) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([np.array([1, 0]), np.array([2, 0, 1])]) @@ -387,7 +387,7 @@ def test_unary_potentials(): ] #an edge from 0 to 1 edge_f = [ np.array([[3,3,3]]) ] - x = [node_f, edges, edge_f] + x = (node_f, edges, edge_f) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([ np.array([1,2])]) # y = np.array([1,0]) @@ -436,7 +436,7 @@ def test_inference_util(): , None , None ] - x = [ node_f, edges, None] + x = ( node_f, edges, None) reindexed_exdges = g._index_all_edges(x) #print `reindexed_exdges` @@ -453,7 +453,7 @@ def report_model_config(crf): def test_inference(): """ - Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF + Testing with a single type of nodes. Must do as well as EdgeFeatureGraphCRF """ # Test inference with different weights in different directions @@ -486,7 +486,7 @@ def test_inference(): edge_features = edge_list_to_features(edge_list) x = ([x.reshape(-1, n_states)], [edges], [edge_features]) - y = [y.ravel()] + y = y.ravel() #for inference_method in get_installed(["lp", "ad3"]): if True: @@ -498,9 +498,9 @@ def test_inference(): y_pred = crf.inference(x, w, relaxed=True) if isinstance(y_pred, tuple): # ad3 produces an integer result if it found the exact solution - assert_array_almost_equal(res[1], y_pred[1]) - assert_array_almost_equal(res[0], y_pred[0].reshape(-1, n_states)) - assert_array_equal(y, np.argmax(y_pred[0], axis=-1)) + assert_array_almost_equal(res[1], y_pred[1], 5) + assert_array_almost_equal(res[0], y_pred[0].reshape(-1, n_states), 5) + assert_array_equal(y, np.argmax(y_pred[0], axis=-1), 5) #for inference_method in get_installed(["lp", "ad3", "qpbo"]): # again, this time discrete predictions only @@ -509,7 +509,7 @@ def test_inference(): w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) crf.initialize(x) y_pred = crf.inference(x, w, relaxed=False) - assert_array_equal(y[0], y_pred) + assert_array_equal(y, y_pred) def test_joint_feature_discrete(): """ @@ -650,7 +650,7 @@ def test_energy_discrete(): if __name__ == "__main__": - if 1: + if 0: debug_joint_feature() if 1: From f99737f2e32075fb2c32af6becada8d4310a8b3e Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 20 Jan 2017 16:26:05 +0100 Subject: [PATCH 021/155] ok for node types --- pystruct/inference/inference_methods.py | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/pystruct/inference/inference_methods.py b/pystruct/inference/inference_methods.py index 7d23be13..31c5fa61 100644 --- a/pystruct/inference/inference_methods.py +++ b/pystruct/inference/inference_methods.py @@ -4,7 +4,6 @@ from .maxprod import inference_max_product from .common import _validate_params - def get_installed(method_filter=None): if method_filter is None: method_filter = ["max-product", 'ad3', 'qpbo', 'ogm', 'lp'] @@ -312,7 +311,8 @@ def inference_lp(unary_potentials, pairwise_potentials, edges, relaxed=False, def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, verbose=0, return_energy=False, branch_and_bound=False, - constraints=None): + constraints=None, + nodetype=None): """Inference with AD3 dual decomposition subgradient solver. Parameters @@ -354,10 +354,12 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, - states is a list of unary states (class), 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. - negated is a list of boolean indicating if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list - NOTE: this hard logic constraint mechanism relies on the binarisation method described by Martins et al. in their 2011 ICML paper. - It has been developed for the EU project READ, by JL Meunier (Xerox), in November 2016. - The READ project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. + NOTE: this hard logic constraint mechanism has been developed for the EU project READ, by JL Meunier (Xerox), in November 2016. + The READ project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. + nodetype : internal use for NodeTypeEdgeFeatureGraphCRF model + NOTE: developed for the EU project READ (grant agreement No 674943), by JL Meunier (Xerox), in Q1 2017. + Returns ------- labels : nd-array @@ -367,11 +369,10 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, import ad3 n_states, pairwise_potentials = \ _validate_params(unary_potentials, pairwise_potentials, edges) - unaries = unary_potentials.reshape(-1, n_states) - if constraints: + if constraints or nodetype: res = ad3.general_constrained_graph(unaries, edges, pairwise_potentials, constraints, verbose=verbose, - n_iterations=4000, exact=branch_and_bound) + n_iterations=4000, exact=branch_and_bound, nodetype=nodetype) else: res = ad3.general_graph(unaries, edges, pairwise_potentials, verbose=verbose, n_iterations=4000, exact=branch_and_bound) @@ -382,8 +383,12 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, if solver_status in ["fractional", "unsolved"] and relaxed: unary_marginals = unary_marginals.reshape(unary_potentials.shape) y = (unary_marginals, pairwise_marginals) + #print solver_status, pairwise_marginals else: - y = np.argmax(unary_marginals, axis=-1) + if nodetype: + y = ad3.getY_from_typedmarginals(unary_marginals, nodetype) + else: + y = np.argmax(unary_marginals, axis=-1) if return_energy: return y, -energy return y From a8acef94b171e405682351a0d8ec0fec7b3b0d05 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 20 Jan 2017 16:31:24 +0100 Subject: [PATCH 022/155] ok?? --- pystruct/models/typed_crf.py | 169 ++++++++++++++++++++++++++++++----- 1 file changed, 147 insertions(+), 22 deletions(-) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index 71cac805..f9bb3b00 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -1,9 +1,34 @@ +# -*- coding: utf-8 -*- + +""" + CRF with different types of nodes + + Copyright Xerox(C) 2017 JL. Meunier + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + + Developed for the EU project READ. The READ project has received funding + from the European Union�s Horizon 2020 research and innovation programme + under grant agreement No 674943. + +""" import numpy as np from .base import StructuredModel from ..inference import inference_dispatch, get_installed from .utils import loss_augment_unaries -from numpy import dtype class TypedCRF(StructuredModel): @@ -71,8 +96,13 @@ def __init__(self assert i_start == self._n_states**2 def initialize(self, X, Y=None): - pass - + if isinstance(X, list): + map(self._check_size_x, X) + if not Y is None: map(self._check_size_xy, X, Y) + else: + self._check_size_x(X) + self._check_size_xy(X, Y) + def _set_size_joint_feature(self): """ We have: @@ -87,14 +117,12 @@ def __repr__(self): self.inference_method)) def _check_size_x(self, x): - l_nodes = self._get_node_features(x) - #node_features are [ i_in_typ -> features ] - l_features = self._get_node_features(x) - if len(l_features) != self.n_types: + l_node_features = self._get_node_features(x) + if len(l_node_features) != self.n_types: raise ValueError("Expected one node feature array per node type.") - for typ, typ_features in enumerate(l_features): + for typ, typ_features in enumerate(l_node_features): if typ_features.shape[1] != self.l_n_features[typ]: raise ValueError("Expected %d features for type %d"%(self.l_n_features[typ], typ)) @@ -114,22 +142,49 @@ def _check_size_x(self, x): #edges should point to valid node indices nodes1, nodes2 = edges[:,0], edges[:,1] if min(nodes1) < 0 or min(nodes2) < 0: - raise ValueError("At least one edge points to negative and therefore invalid node index") - if max(nodes1) >= l_nodes[typ1].shape[0] or max(nodes2) > l_nodes[typ2].shape[0]: - raise ValueError("At least one edge points to non-existing node index") + raise ValueError("At least one edge points to negative and therefore invalid node index: type %d to type %d"%(typ1,typ2)) + if max(nodes1) >= l_node_features[typ1].shape[0]: + raise ValueError("At least one edge starts from a non-existing node index: type %d to type %d"%(typ1,typ2)) + if max(nodes2) >= l_node_features[typ2].shape[0]: + raise ValueError("At least one edge points to a non-existing node index: type %d to type %d"%(typ1,typ2)) + def _check_size_xy(self, X, Y): + if Y is None: return + + #make sure Y has the proper length and acceptable labels + l_node_features = self._get_node_features(X, True) + + nb_nodes = sum(nf.shape[0] for nf in l_node_features) + if Y.shape[0] != nb_nodes: + raise ValueError("Expected 1 label for each of the %d nodes. Gopt %d labels."%(nb_nodes, Y.shape[0])) + + i_start = 0 + for typ, nf, n_states in zip(range(self.n_types), l_node_features, self.l_n_states): + nb_nodes = nf.shape[0] + Y_typ = Y[i_start:i_start+nb_nodes] + if np.min(Y_typ) < 0: + raise ValueError("Got a negative label for type %d"%typ) + if np.max(Y_typ) >= n_states: + raise ValueError("Got a label outside of [0, %d] for type %d: %s"%(n_states-1, typ, Y_typ)) + i_start = i_start + nb_nodes + + + def _get_node_features(self, x, bClean=False): if bClean: return [ np.empty((0,0)) if node_features is None or len(node_features)==0 else node_features for node_features in x[0]] else: return x[0] + def _get_node_features_by_type(self, x, typ): return x[0][typ] + def _get_edges(self, x, bClean=False): if bClean: return [ np.empty((0,0)) if edges is None or len(edges)==0 else edges for edges in x[1]] else: return x[1] + def _index_all_edges(self, x): """ return all edges as a single 2-column matrix, taking care of node indices!! @@ -203,7 +258,6 @@ def _get_unary_potentials(self, x, w): Unary weights. """ self._check_size_w(w) - self._check_size_x(x) l_node_features = self._get_node_features(x) #code for single type CRF # unary_params = w[:self.n_states * self.n_features].reshape( @@ -281,19 +335,70 @@ def loss_augmented_inference(self, x, y, w, relaxed=False, shape (n_states, n_states) of accumulated pairwise marginals. """ +# print "y.shape ", y.shape self.inference_calls += 1 self._check_size_w(w) unary_potentials = self._get_unary_potentials(x, w) pairwise_potentials = self._get_pairwise_potentials(x, w) flat_edges = self._index_all_edges(x) - flat_y = np.hstack(y) - #loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) - loss_augment_unaries(unary_potentials, flat_y, self.class_weight) + + loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) + + + l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] + nodetype_data = (l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type - return inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, +# print "pairwise_potentials ", `pairwise_potentials` +# print "pairwise_potentials.shape ", pairwise_potentials.shape +# print "flat_edges = ", `flat_edges` +# print "flat_edges.shape = ", flat_edges.shape +# print " nb non zero = ", len(np.flatnonzero(pairwise_potentials)) + +# print "loss_inference" +# print " UP ", show(unary_potentials) +# print " PP ", show(pairwise_potentials) +# print " E ", show(flat_edges) + + Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, self.inference_method, relaxed=relaxed, - return_energy=return_energy) + return_energy=return_energy, + nodetype=nodetype_data) + #print " LAI->", show(Y_pred) + +# print "=====", Y_pred.shape + + if isinstance(Y_pred, tuple): + import ad3 + unary_marginals, pairwise_marginals = Y_pred + _Y_pred = ad3.getY_from_typedmarginals(unary_marginals, nodetype_data) + else: + try: + self._check_size_xy(x, Y_pred) + except ValueError as e: + print "Y_pred is BAD, FIXING IT WITH RANDOM VALUES" + Y_pred = self.fix_Y_at_random(x, Y_pred) + if self.inference_calls % 1000 == 0: print "%d inference calls"%self.inference_calls + + #print "Y_pred ", `Y_pred` + + return Y_pred + + def fix_Y_at_random(self, x, Y_pred): + import random + l_node_features = self._get_node_features(x, True) + i_start = 0 + for nf, n_states in zip(l_node_features, self.l_n_states): + nb_nodes = nf.shape[0] + if nb_nodes: + Y_typ = Y_pred[i_start:i_start+nb_nodes] + if np.max(Y_typ) >= n_states: + for i in range(nb_nodes): + if Y_pred[i_start+i] >= n_states: Y_pred[i_start+i] = random.randint(0, n_states-1) + i_start = i_start + nb_nodes + self._check_size_xy(x, Y_pred) + return Y_pred + def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): """Inference for x using parameters w. @@ -345,12 +450,32 @@ def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): pairwise_potentials = self._get_pairwise_potentials(x, w) flat_edges = self._index_all_edges(x) + l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] + nodetype_data=(l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type + if constraints: - return inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, +# print "inference" +# print " UP ", show(unary_potentials) +# print " PP ", show(pairwise_potentials) +# print " E ", show(flat_edges) + + Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, self.inference_method, relaxed=relaxed, - return_energy=return_energy, constraints=constraints) + return_energy=return_energy, constraints=constraints, + nodetype=nodetype_data) + #print " I ->", show(Y_pred) else: - return inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, + Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, self.inference_method, relaxed=relaxed, - return_energy=return_energy) - + return_energy=return_energy, + nodetype=nodetype_data) +# print "===", Y_pred.shape +# +# try: +# self._check_size_xy(x, Y_pred) +# except ValueError as e: +# print "\tY is BAD, FIXING IT AT RANDOM" +# Y_pred = self.fix_Y_at_random(x, Y_pred) + if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) + + return Y_pred From f69b08a7d3b71bc88f00a25d018984428984aad7 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 20 Jan 2017 16:32:47 +0100 Subject: [PATCH 023/155] ok I believe, but no test show yet with nice results --- .../node_type_edge_feature_graph_crf.py | 131 ++++++++++++------ 1 file changed, 91 insertions(+), 40 deletions(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index c4340651..d427c281 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -1,3 +1,29 @@ +# -*- coding: utf-8 -*- + +""" + Pairwise CRF with features/strength associated to each edge and different types of nodes + + Copyright Xerox(C) 2017 JL. Meunier + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + + Developed for the EU project READ. The READ project has received funding + from the European Union�s Horizon 2020 research and innovation programme + under grant agreement No 674943. + +""" import numpy as np from .typed_crf import TypedCRF @@ -72,7 +98,7 @@ def __init__(self TypedCRF.__init__(self, n_types, l_n_states, l_n_features, inference_method=inference_method, l_class_weight=l_class_weight) self._get_pairwise_potentials_initialize() - + def _set_size_joint_feature(self): """ We have: @@ -99,10 +125,10 @@ def __repr__(self): def _check_size_x(self, x): l_edges = self._get_edges(x) if len(l_edges) != self.n_types**2: - raise ValueError("Expected %d edge arrays"%(self.n_types**2)) + raise ValueError("Expected %d edge arrays or None"%(self.n_types**2)) l_edge_features = self._get_edge_features(x) if len(l_edge_features) != self.n_types**2: - raise ValueError("Expected %d edge feature arrays"%(self.n_types**2)) + raise ValueError("Expected %d edge feature arrays or None"%(self.n_types**2)) TypedCRF._check_size_x(self, x) @@ -124,7 +150,7 @@ def _check_size_x(self, x): edge_features = self._get_edge_features_by_type(x, typ1, typ2) if edge_features is None: continue if edge_features.shape[1] != self.a_n_edge_features[typ1,typ2]: - raise ValueError("Types %d x %d: bad number of edge features"%(typ1,typ2)) + raise ValueError("Types %d x %d: bad number of edge features. expected %d got %d"%(typ1,typ2, self.a_n_edge_features[typ1,typ2], edge_features.shape[1])) def _get_edge_features(self, x, bClean=False): if bClean: @@ -139,22 +165,27 @@ def _get_pairwise_potentials_initialize(self): Putting in cache the params required to build the pairwise potentials given x and w """ self._cache_pairwise_potentials = list() - i_w, n_states1, n_states2, i_states1, i_states2 = 0, 0, 0, 0, 0 -# for (typ1, typ2), edge_features, edgetype_start_index in zip(self._iter_type_pairs(), l_edge_features, self._l_edgetype_start_index): - for (typ1, typ2) in self._iter_type_pairs(): - - n_features = self.a_n_edge_features[typ1, typ2] +# i_w, n_states1, n_states2, i_states1, i_states2 = 0, 0, 0, 0, 0 +# for (typ1, typ2) in self._iter_type_pairs(): + + i_w, n_states1, i_states1 = 0, 0, 0 + + for typ1 in xrange(self.n_types): n_states1 = self.l_n_states[typ1] - n_states2 = self.l_n_states[typ2] - i_w_stop = i_w + n_features * n_states1 * n_states2 i_states1_stop = i_states1 + n_states1 - i_states2_stop = i_states2 + n_states2 - - self._cache_pairwise_potentials.append( (n_features - , n_states1, n_states2, i_states1, i_states1_stop, i_states2, i_states2_stop - , i_w, i_w_stop) ) - - i_w, i_states1, i_states2 = i_w_stop, i_states1_stop, i_states2_stop + n_states2, i_states2 = 0, 0 + for typ2 in xrange(self.n_types): + n_features = self.a_n_edge_features[typ1, typ2] + n_states2 = self.l_n_states[typ2] + i_w_stop = i_w + n_features * n_states1 * n_states2 + i_states2_stop = i_states2 + n_states2 + + self._cache_pairwise_potentials.append( (n_features + , n_states1, n_states2, i_states1, i_states1_stop, i_states2, i_states2_stop + , i_w, i_w_stop) ) + + i_w, i_states2 = i_w_stop, i_states2_stop + i_states1 = i_states1_stop def _get_pairwise_potentials(self, x, w): """Computes pairwise potentials for x and w. @@ -173,12 +204,7 @@ def _get_pairwise_potentials(self, x, w): Pairwise weights. """ self._check_size_w(w) - self._check_size_x(x) - # edge_features = self._get_edge_features(x) - # pairwise = np.asarray(w[self.n_states * self.n_features:]) - # pairwise = pairwise.reshape(self.n_edge_features, -1) - # return np.dot(edge_features, pairwise).reshape( - # edge_features.shape[0], self.n_states, self.n_states) + #self._check_size_x(x) #call initialize once and only once before!! l_edge_features = self._get_edge_features(x) l_edge_nb = [0 if ef is None else ef.shape[0] for ef in l_edge_features] @@ -186,12 +212,12 @@ def _get_pairwise_potentials(self, x, w): wpw = w[self.size_unaries:] a_edges_states_states = np.zeros((n_edges_total, self._n_states, self._n_states), dtype=w.dtype) - + # i_w, i_edges, i_states1, i_states2 = 0, 0, 0, 0 # # for (typ1, typ2), edge_features, edgetype_start_index in zip(self._iter_type_pairs(), l_edge_features, self._l_edgetype_start_index): # for (typ1, typ2), edge_features in zip(self._iter_type_pairs(), l_edge_features): # if edge_features is None: continue -# +# # n_edges, n_features = edge_features.shape # n_states1 = self.l_n_states[typ1] # n_states2 = self.l_n_states[typ2] @@ -199,26 +225,29 @@ def _get_pairwise_potentials(self, x, w): # i_edges_stop = i_edges + n_edges # i_states1_stop = i_states1 + n_states1 # i_states2_stop = i_states2 + n_states2 -# +# # pw_typ_typ = wpw[i_w:i_w_stop].reshape(n_features, -1) # n_states1*n_states2 x nb_feat # pot_typ_typ = np.dot(edge_features, pw_typ_typ).reshape(n_edges, n_states1, n_states2) -# +# print "pot_typ_typ.shape ", pot_typ_typ.shape # a_edges_states_states[ i_edges:i_edges_stop, i_states1:i_states1_stop , i_states2:i_states2_stop ] = pot_typ_typ -# +# # i_w, i_edges, i_states1, i_states2 = i_w_stop, i_edges_stop, i_states1_stop, i_states2_stop i_edges = 0 + #print map(len, [self._cache_pairwise_potentials, l_edge_features, l_edge_nb]) for ((n_features, n_states1, n_states2, i_states1, i_states1_stop, i_states2, i_states2_stop, i_w, i_w_stop) , edge_features, n_edges) in zip(self._cache_pairwise_potentials, l_edge_features, l_edge_nb): - - if edge_features is None: continue + i_edges_stop = i_edges + n_edges - - pw_typ_typ = wpw[i_w:i_w_stop].reshape(n_features, -1) # n_states1*n_states2 x nb_feat - pot_typ_typ = np.dot(edge_features, pw_typ_typ).reshape(n_edges, n_states1, n_states2) - - a_edges_states_states[ i_edges:i_edges_stop, i_states1:i_states1_stop , i_states2:i_states2_stop ] = pot_typ_typ - + + if not edge_features is None: + pw_typ_typ = wpw[i_w:i_w_stop].reshape(n_features, -1) # n_states1*n_states2 x nb_feat + pot_typ_typ = np.dot(edge_features, pw_typ_typ).reshape(n_edges, n_states1, n_states2) +# print i_states1,i_states1_stop , i_states2,i_states2_stop, n_states1, n_states2 +# print "a_edges_states_states.shape ", a_edges_states_states.shape +# print "a_edges_states_states[ ].shape ", a_edges_states_states[ i_edges:i_edges_stop, i_states1:i_states1_stop , i_states2:i_states2_stop ].shape + a_edges_states_states[ i_edges:i_edges_stop, i_states1:i_states1_stop , i_states2:i_states2_stop ] = pot_typ_typ + i_edges = i_edges_stop return a_edges_states_states.reshape(n_edges_total, self._n_states, self._n_states) @@ -255,28 +284,47 @@ def joint_feature(self, x, y): Feature vector associated with state (x, y). """ - self._check_size_x(x) +# print "x=", `x` +# print "y=", `y` + self._check_size_x(x) #call initialize once! l_node_features = self._get_node_features(x) l_edges, l_edge_features = self._get_edges(x), self._get_edge_features(x) l_n_nodes = [len(o) for o in self._get_node_features(x, True)] l_n_edges = [edges.shape[0] for edges in self._get_edges(x, True)] n_nodes = sum(l_n_nodes) n_edges = sum(l_n_edges) - + if False: + print + print type(y) + print "l_n_nodes = ", l_n_nodes + for nf in l_node_features: print "nf.shape ", None if nf is None else nf.shape, + print + print "l_n_edges = ", l_n_edges + for ef in l_edge_features: print "ef.shape ", None if ef is None else ef.shape, + print if isinstance(y, tuple): + #print "y=", `y` # y is result of relaxation, tuple of unary and pairwise marginals unary_marginals, pw = y unary_marginals = unary_marginals.reshape(n_nodes, self._n_states) else: + self._check_size_xy(x, y) #make one hot encoding #each type is assigned a range of columns, each starting at self._a_state_startindex_by_typ[ ] #in the arnge column I is for state i of that type unary_marginals = np.zeros((n_nodes, self._n_states), dtype=np.int) i_start = 0 #print self.l_n_states, self._l_type_startindex, y +# print "l_node_features shapes", map(lambda x: x.shape, l_node_features) +# print "y.shape", y.shape +# print "y", y.ravel() for node_features, typ_start_index in zip(l_node_features, self._l_type_startindex): if node_features is None: continue i_stop = i_start + node_features.shape[0] +# print "typ_start_index ", typ_start_index +# print "y. ", y.shape, i_start, i_stop +# print y[i_start:i_stop].ravel() + unary_marginals[ :, typ_start_index + y[i_start:i_stop] ] unary_marginals[ np.ogrid[i_start:i_stop] , typ_start_index + y[i_start:i_stop] ] = 1 @@ -313,7 +361,6 @@ def joint_feature(self, x, y): i_start = i_stop assert i_start == n_nodes #print "--- all_node_features =\n", `all_node_features` - unaries_acc = np.dot(unary_marginals.T, all_node_features) # node_states x sum_of_features matrix #print "--- unaries_acc =\n", `unaries_acc` @@ -331,8 +378,12 @@ def joint_feature(self, x, y): i_col_start = i_col_stop i_start = i_stop #print "--- all_edge_features =\n", `all_edge_features` + + #print all_edge_features.T.shape, pw.shape pairwise_acc = np.dot(all_edge_features.T, pw) # sum_of_features x edge_states + + # print '-'*30 # print np.dot(pw.T, all_edge_features).T # print '-'*30 From d7d9a95b54dea0c95e4344924cfb7758ff246a6c Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 24 Jan 2017 17:37:34 +0100 Subject: [PATCH 024/155] ok --- examples/plot_snakes_typed.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/examples/plot_snakes_typed.py b/examples/plot_snakes_typed.py index 36edd717..4c54989c 100644 --- a/examples/plot_snakes_typed.py +++ b/examples/plot_snakes_typed.py @@ -35,6 +35,15 @@ class instead of EdgeFeatureGraphCRF, despite there is only 1 type of nodes. PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). But it does work as well as Decision Tree Fields ;) + + JL Meunier - January 2017 + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943 + + Copyright Xerox + """ import numpy as np import matplotlib.pyplot as plt @@ -90,7 +99,8 @@ def convertToSingleTypeX(X): # now, use more informative edge features: crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]], inference_method=inference) ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', - n_jobs=-1) + verbose=1, + n_jobs=8) ssvm.fit( convertToSingleTypeX(X_train_edge_features), Y_train_flat) Y_pred2 = ssvm.predict( convertToSingleTypeX(X_test_edge_features) ) print("Results using also input features for edges") From dc611eedf7b44d2943d92ae0d5344aa694c26a0c Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 30 Jan 2017 13:39:23 +0100 Subject: [PATCH 025/155] friday 27/1 ok --- examples/plot_hidden_snakes.py | 116 ++++++-- examples/plot_hidden_snakes_typed.py | 387 +++++++++++++++------------ 2 files changed, 311 insertions(+), 192 deletions(-) diff --git a/examples/plot_hidden_snakes.py b/examples/plot_hidden_snakes.py index 582f47a5..c9eef953 100644 --- a/examples/plot_hidden_snakes.py +++ b/examples/plot_hidden_snakes.py @@ -118,7 +118,30 @@ def shuffleSnakeCells(a_picture, bOneHot=True): #in place!! a_picture[_ai,_aj,:] = a_picture[ai,aj,:] return a_picture -def changeOneSnakeCell(a_picture, bOneHot=True): #in place!! +def changeOneSnakeCell(a_picture, bOneHot=True, nCell=10): #in place!! + """ + Change the color of 1 snake cells + """ + if bOneHot: + ai, aj = np.where(a_picture[...,3] != 1) + else: + _p = np.copy(a_picture) + _p = one_hot_colors(_p) + ai, aj = np.where(_p[...,3] != 1) + assert len(ai) == nCell, (len(ai), nCell) + + iChange = random.randint(0,nCell-1) + + for i in range(10): + iFromCell = random.randint(0,nCell-1) + if (a_picture[ai[iChange], aj[iChange],:] != a_picture[ai[iFromCell], aj[iFromCell],:]).any(): + a_picture[ai[iChange], aj[iChange],:] = a_picture[ai[iFromCell], aj[iFromCell],:] + #so that we do not care about which color is valid... + break + + return a_picture + +def eraseOneSnakeCell(a_picture, bOneHot=True): #in place!! """ Change the color of 1 snake cells """ @@ -132,22 +155,19 @@ def changeOneSnakeCell(a_picture, bOneHot=True): #in place!! iChange = random.randint(0,9) - while True: - iFromCell = random.randint(0,9) - if (a_picture[ai[iChange], aj[iChange],:] != a_picture[ai[iFromCell], aj[iFromCell],:]).any(): - a_picture[ai[iChange], aj[iChange],:] = a_picture[ai[iFromCell], aj[iFromCell],:] - #so that we do not care about which color is valid... - break + #a_picture[ai[iChange], aj[iChange]] = a_picture[0,0] #by construction it is background return a_picture -def shuffleSnake(a_picture, bOneHot=True): + +def shuffleSnake(a_picture, bOneHot=True, nCell=10): """ Shuffle either the snake's cells or the pcitures' pixels. """ - if True: - changeOneSnakeCell(a_picture, bOneHot) - changeOneSnakeCell(a_picture, bOneHot) + if False: + eraseOneSnakeCell(a_picture, bOneHot) + elif True: + changeOneSnakeCell(a_picture, bOneHot, nCell=nCell) else: if random.randint(0,1): shuffleSnakeCells(a_picture, bOneHot) @@ -165,14 +185,17 @@ def plot_snake(picture): plt.imshow(picture, interpolation='nearest') plt.show() -def augmentWithNoSnakeImages(X,Y, name, bOneHot=True): +def augmentWithNoSnakeImages(X,Y, name, bOneHot=True, iMult=1, nCell=10): """ return the number of added picture (AT THE END OF INPUT LISTS) """ print "ADDING PICTURE WIHOUT SNAKES!!! %d elements in %s"%(len(X), name) - X_NoSnake = [np.copy(x) for x in X] - for x in X_NoSnake: shuffleSnake(x, bOneHot) + X_NoSnake = [] + for i in range(int(iMult)): + X_NoSnake.extend([np.copy(x) for x in X]) + + for x in X_NoSnake: shuffleSnake(x, bOneHot, nCell) #map(shufflePictureCells, X_NoSnake) newX = list() @@ -184,7 +207,7 @@ def augmentWithNoSnakeImages(X,Y, name, bOneHot=True): newX.append(x) Y_NoSnake.append(np.zeros(y.shape, dtype=np.int32)) X_NoSnake = newX - + assert len(X_NoSnake)==len(Y_NoSnake) return len(X_NoSnake), X+X_NoSnake, Y+Y_NoSnake def shuffle_in_unison(*args): @@ -192,11 +215,34 @@ def shuffle_in_unison(*args): random.shuffle(lTuple) return zip(*lTuple) +def shorten_snakes(lX,lY, N): + newlX,newlY = list(), list() + for X, Y in zip(lX,lY): + assert X.shape[:2] == Y.shape, (X.shape, Y.shape) + ai, aj = np.where(Y>N) + X[ai,aj,:] = X[0,0,:] + Y[ai,aj] = 0 + #crop + ai, aj = np.where(Y!=0) + aimin,aimax = min(ai)-1, max(ai)+2 + ajmin,ajmax = min(aj)-1, max(aj)+2 + newlY.append( Y[aimin:aimax, ajmin:ajmax] ) + newlX.append( X[aimin:aimax, ajmin:ajmax,:]) + + return newlX, newlY + + if __name__ == '__main__': print("Please be patient. Learning will take 5-20 minutes.") + + NCELL = 5 + print "NCELL=", NCELL + snakes = load_snakes() X_train, Y_train = snakes['X_train'], snakes['Y_train'] + #X_train, Y_train = X_train[:10], Y_train[:10] + bSHUFFLE = True bADD_HIDDEN_SNAKES = True @@ -205,9 +251,10 @@ def shuffle_in_unison(*args): #X_train, Y_train = X_train[:10], Y_train[:10] print len(X_train), len(Y_train) #print `X_train[0]` + X_train, Y_train = shorten_snakes(X_train, Y_train, NCELL) if bADD_HIDDEN_SNAKES: - _, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False) + _, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False, nCell=NCELL) print len(X_train), len(Y_train) if False: @@ -247,9 +294,11 @@ def shuffle_in_unison(*args): # Evaluate using confusion matrix. # Clearly the middel of the snake is the hardest part. X_test, Y_test = snakes['X_test'], snakes['Y_test'] + X_test, Y_test = shorten_snakes(X_test, Y_test, NCELL) + print "TEST len=", len(X_test) if bADD_HIDDEN_SNAKES: - _, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", bOneHot=False) + _, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", bOneHot=False, nCell=NCELL) print "TEST len=", len(X_test) X_test = [one_hot_colors(x) for x in X_test] @@ -498,7 +547,38 @@ def shuffle_in_unison(*args): [ 36 0 0 1 1 0 0 0 0 62 0] [ 32 1 0 0 1 1 0 0 0 0 65]] - +TEST len= 100 +ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test +TEST len= 200 +Results using only directional features for edges +Test accuracy: 0.878 +[[3839 4 9 6 13 27] + [ 100 0 0 0 0 0] + [ 98 0 0 2 0 0] + [ 96 0 1 0 2 1] + [ 94 0 1 0 3 2] + [ 81 0 0 1 0 18]] +1000 inference calls +2000 inference calls +3000 inference calls +4000 inference calls +5000 inference calls +6000 inference calls +7000 inference calls +8000 inference calls +9000 inference calls +10000 inference calls +11000 inference calls +12000 inference calls +Training time = 310.7s +Results using also input features for edges +Test accuracy: 0.954 +[[3729 29 34 33 32 41] + [ 7 93 0 0 0 0] + [ 7 0 93 0 0 0] + [ 7 0 0 93 0 0] + [ 6 0 0 0 94 0] + [ 6 0 0 0 0 94]] ---------------------------------------------------------------- CHANGING TWO CELLs OF THE SNAKE switch_to='ad3', diff --git a/examples/plot_hidden_snakes_typed.py b/examples/plot_hidden_snakes_typed.py index 81906fbd..6534a818 100644 --- a/examples/plot_hidden_snakes_typed.py +++ b/examples/plot_hidden_snakes_typed.py @@ -38,6 +38,17 @@ PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). But it does work as well as Decision Tree Fields ;) + + + + JL Meunier - January 2017 + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943 + + Copyright Xerox + """ import numpy as np import matplotlib.pyplot as plt @@ -45,6 +56,7 @@ from sklearn.preprocessing import label_binarize from sklearn.metrics import confusion_matrix, accuracy_score import time +import sys from pystruct.learners import OneSlackSSVM from pystruct.datasets import load_snakes @@ -52,94 +64,9 @@ #from pystruct.models import EdgeFeatureGraphCRF from pystruct.models import NodeTypeEdgeFeatureGraphCRF -from plot_snakes import one_hot_colors, neighborhood_feature, prepare_data - -def isSnakePresent(a_hot_picture): - """ - Algorithmic check, to make sure that after shuffling we do not have a snake! :-) - work on the 1-hot encoded picture - """ - try: - ai, aj = np.where(a_hot_picture[...,3] != 1) - if len(ai) != 10: return False - lij = zip(ai, aj) - for n in range(10): - _lij = shiftSnake(a_hot_picture, lij) - if len(_lij) != len(lij)-1: return False - lij = _lij - if len(_lij) != 0: return False - return True - except: - return False - -def shiftSnake(a_hot_picture, lij): - #the snake moves by one cell, head disappearing in sand - _lij = list() - for i,j in lij: - color_index = np.where(a_hot_picture[i,j,:]==1)[0][0] - dj = np.array( [ 0, 0, 1, None, -1])[color_index] - di = np.array( [-1, 1, 0, None, 0])[color_index] - i,j = i+di,j+dj - if a_hot_picture[i,j,3] != 1: #backgroun - _lij.append((i,j)) - return _lij - -def shufflePictureCells(a_picture): #in place!! - """ - Shuffle the pixels - """ - n = random.randint(1,4) - if n == 1: - map(np.random.shuffle, a_picture) - elif n == 2: - map(np.random.shuffle, np.transpose(a_picture, (1,0,2))) - else: - map(np.random.shuffle, a_picture) - map(np.random.shuffle, np.transpose(a_picture, (1,0,2))) - - return a_picture - -def shuffleSnakeCells(a_picture, bOneHot=True): #in place!! - """ - Shuffle the colors of the 10 snake cells - """ - if bOneHot: - ai, aj = np.where(a_picture[...,3] != 1) - else: - _p = np.copy(a_picture) - _p = one_hot_colors(_p) - ai, aj = np.where(_p[...,3] != 1) - assert len(ai) == 10 - - l_shuffled_aij = zip(ai,aj) - random.shuffle( l_shuffled_aij ) - _ai, _aj = zip(*l_shuffled_aij) - - a_picture[_ai,_aj,:] = a_picture[ai,aj,:] - return a_picture - -def changeOneSnakeCell(a_picture, bOneHot=True): #in place!! - """ - Change the color of 1 snake cells - """ - if bOneHot: - ai, aj = np.where(a_picture[...,3] != 1) - else: - _p = np.copy(a_picture) - _p = one_hot_colors(_p) - ai, aj = np.where(_p[...,3] != 1) - assert len(ai) == 10 - - iChange = random.randint(0,9) - - while True: - iFromCell = random.randint(0,9) - if (a_picture[ai[iChange], aj[iChange],:] != a_picture[ai[iFromCell], aj[iFromCell],:]).any(): - a_picture[ai[iChange], aj[iChange],:] = a_picture[ai[iFromCell], aj[iFromCell],:] - #so that we do not care about which color is valid... - break +from plot_snakes import one_hot_colors, neighborhood_feature, prepare_data - return a_picture +from plot_hidden_snakes import shufflePictureCells, shuffleSnakeCells, changeOneSnakeCell, augmentWithNoSnakeImages, shuffle_in_unison def shuffleSnake(a_picture, bOneHot=True): """ @@ -154,129 +81,241 @@ def shuffleSnake(a_picture, bOneHot=True): else: shufflePictureCells(a_picture) -def convertToSingleTypeX(X): - """ - For NodeTypeEdgeFeatureGraphCRF X is structured differently. - But NodeTypeEdgeFeatureGraphCRF can handle graph with a single node type. One needs to convert X to the new structure using this method. - """ - return [([nf], [e], [ef]) for (nf,e,ef) in X] - def plot_snake(picture): plt.imshow(picture, interpolation='nearest') plt.show() -def augmentWithNoSnakeImages(X,Y, name, bOneHot=True): - print "ADDING PICTURE WIHOUT SNAKES!!! %d elements in %s"%(len(X), name) +def prepare_picture_data(X): + """ + compute picture features (on 1-hot encoded pictures) + """ + lPictFeat = list() + for a_hot_picture in X: + #count number of cells of each color + #feat = np.zeros((1,5), dtype=np.int8) + feat = np.zeros((1,7), dtype=np.int64) + + #Histogram of pixels from 0 to 4 + """ + Test accuracy: 0.500 + [[45 55] + [45 55]] + """ + for i in xrange(5): + ai, aj = np.where(a_hot_picture[...,i] == 1) + feat[0,i] = len(ai) + + #adding height and width of the snake + """ + Test accuracy: 0.420 Test accuracy: 0.515 Test accuracy: 0.495 + [[39 61] [[48 52] [[52 48] + [55 45]] [45 55]] [53 47]] + """ + ai, aj = np.where(a_hot_picture[...,3] != 1) + feat[0,5] = max(ai)-min(ai) #height + feat[0,6] = max(aj)-min(aj) #width + + lPictFeat.append(feat) - X_NoSnake = [np.copy(x) for x in X] - for x in X_NoSnake: shuffleSnake(x, bOneHot) - #map(shufflePictureCells, X_NoSnake) + return lPictFeat + +def convertToTwoType(X_train, #list of hot pictures + X_train_directions, # list of node_feat (2D array) , edges (_ x 2 array), edge_feat (2D array) for pixel nodes + Y_train, # list of 2D arrays + X_train_pict_feat, #a list of picture_node_features + Y_train_pict): #a list of integers [0,1] + """ + return X,Y for NodeTypeEdgeFeatureGraphCRF - newX = list() - Y_NoSnake = list() - for x,y in zip(X_NoSnake, Y): - if isSnakePresent(x): - print "\t- DISCARDING a shuffled snake which is still a snake!!!!" - else: - newX.append(x) - Y_NoSnake.append(np.zeros(y.shape, dtype=np.int8)) - X_NoSnake = newX - return X+X_NoSnake, Y+Y_NoSnake + X and Y + ------- + Node features are given as a list of n_types arrays of shape (n_type_nodes, n_type_features): + - n_type_nodes is the number of nodes of that type + - n_type_features is the number of features for this type of node + + Edges are given as a list of n_types x n_types arrays of shape (n_type_edges, 2). + Columns are resp.: node index (in corresponding node type), node index (in corresponding node type) + + Edge features are given as a list of n_types x n_types arrays of shape (n_type_type_edge, n_type_type_edge_features) + - n_type_type_edge is the number of edges of type type_type + - n_type_type_edge_features is the number of features for edge of type type_type + + An instance ``X`` is represented as a tuple ``([node_features, ..], [edges, ..], [edge_features, ..])`` + + Labels ``Y`` are given as one array of shape (n_nodes) The meaning of a label depends upon the node type. + + """ + + lX, lY = list(), list() -def shuffle_XY(X,Y): - lxy = zip(X, Y) - random.shuffle(lxy) - X, Y = zip(*lxy) - return X, Y + for (X, + (aPixelFeat, aPixelPixelEdges, aPixelPixelEdgeFeat), + aPixelLbl, + aPictFeat, + iPictLbl) in zip(X_train, X_train_directions, Y_train, X_train_pict_feat, Y_train_pict ): + + + aPixelPictEdges = np.zeros( (aPixelFeat.shape[0], 2), np.int64) + aPixelPictEdges[:,0] = np.arange(aPixelFeat.shape[0]) + features = neighborhood_feature(X) + aPixelPictEdgeFeat = features + + lNodeFeat = [aPixelFeat, aPictFeat] + lEdge = [aPixelPixelEdges, + aPixelPictEdges, #pixel to picture + None, #picture to pixel + None] #picture to picture + lEdgeFeat = [aPixelPixelEdgeFeat, + aPixelPictEdgeFeat, + None, + None] + + #Y is flat for each graph + y = np.zeros((aPixelLbl.size+1, ), dtype=np.int64) + y[:-1] = aPixelLbl.ravel() + y[-1] = int(iPictLbl)+11 + + x = (lNodeFeat, lEdge, lEdgeFeat) + + lX.append(x) + lY.append(y) + + return lX,lY + + + + if __name__ == '__main__': - print("Please be patient. Learning will take 5-20 minutes.") + + np.random.seed(1605) + random.seed(98) + + print("Please be patient...") snakes = load_snakes() X_train, Y_train = snakes['X_train'], snakes['Y_train'] - bSHUFFLE = True - bADD_HIDDEN_SNAKES = True #bADD_HIDDEN_SNAKES = False #JL - #X_train, Y_train = X_train[:10], Y_train[:10] + X_train, Y_train = X_train[:3], Y_train[:3] print len(X_train), len(Y_train) #print `X_train[0]` if bADD_HIDDEN_SNAKES: - X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False) + nb_hidden, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False) print len(X_train), len(Y_train) + Y_train_pict = np.array([1]*(len(X_train)-nb_hidden) + [0]*nb_hidden) - if False: - #show the faked pictures - for ix, x in enumerate(X_train): plot_snake(shufflePictureCells(x)) + X_train = [one_hot_colors(x) for x in X_train] - X_train_hot = [one_hot_colors(x) for x in X_train] - - if False: - for ix, x in enumerate(X_train_hot): - if not isSnakePresent(x): plot_snake(X_train[ix]) - - X_train = X_train_hot - print "Snakes are ok" - + X_train, Y_train, Y_train_pict = shuffle_in_unison(X_train, Y_train, Y_train_pict) - if bSHUFFLE: - #let's shuffle our data - X_train, Y_train = shuffle_XY(X_train, Y_train) - # ------------------------------------------------------------------------------------- + X_train_pict_feat = prepare_picture_data(X_train) + + #X_train_pixel_pict_edge, X_train_pixel_pict_edge_feat = prepare_picture_edge_data(X_train) + X_train_directions, X_train_edge_features = prepare_data(X_train) - Y_train_flat = [y_.ravel() for y_ in Y_train] - - inference = 'qpbo' + inference = 'ad3' # first, train on X with directions only: - #CHANGE!! - #We require NodeTypeEdgeFeatureGraphCRF - #crf = NodeTypeEdgeFeatureGraphCRF(inference_method=inference) - crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[2]], inference_method=inference) - XX = convertToSingleTypeX(X_train_directions) - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, - max_iter=100, - n_jobs=1) - print len(XX), len(Y_train), len(Y_train_flat) - ssvm.fit(XX, Y_train_flat) + #crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[2]], inference_method=inference) + # first, train on X with directions only: +# l_weights = [ +# [10.0/200] + [10.0/200]*10, +# [10.0/20 , 10.0/20] +# ] +# print "WEIGHTS:", l_weights + crf = NodeTypeEdgeFeatureGraphCRF(2, # 2 node types: pixels and pictures + [11, 2], # 11 states for pixel nodes, 2 states for pictures + [45, 7], # 45 features for pixels, 7 for pictures + [[180, 45], # 2 feature between pixel nodes, 1 between pixel and picture + [45 , 0]], # , nothing between picture nodes (no picture_to_picture edge anyway) + inference_method=inference +# , l_class_weight = l_weights + ) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + #max_iter=1000, + n_jobs=1 + ,verbose=1 + ) + + print "YY[0].shape", Y_train[0].shape + XX, YY = convertToTwoType(X_train, + X_train_edge_features, # list of node_feat , edges, edge_feat for pixel nodes + Y_train, + X_train_pict_feat, #a list of picture_node_features + Y_train_pict) #a list of integers [0,1] + + print np.histogram( np.hstack([y.ravel() for y in YY]), bins=range(14)) +# print np.histogram( np.hstack([y.ravel()[:-1] for y in YY]), bins=range(12)) +# print np.histogram( np.hstack([y.ravel()[-1] for y in YY]), bins=range(3)) +# yy_trn = np.hstack([y.ravel()[:-1] for y in YY]) +# print(confusion_matrix(yy_trn,yy_trn)) +# yy_trn_pic = np.hstack([y.ravel()[-1] for y in YY]) +# print(confusion_matrix(np.hstack(yy_trn_pic), np.hstack(yy_trn_pic))) + + + print "YY[0].shape", YY[0].shape + crf.initialize(XX, YY)# check if the data is properly built + sys.stdout.flush() + + t0 = time.time() + ssvm.fit(XX, YY) + print "FIT DONE IN %.1fs"%(time.time() - t0) + sys.stdout.flush() + +# import sys +# sys.exit(0) # Evaluate using confusion matrix. # Clearly the middel of the snake is the hardest part. X_test, Y_test = snakes['X_test'], snakes['Y_test'] - print "TEST len=", len(X_test) +# X_test, Y_test = X_test[:3], Y_test[:3] + if bADD_HIDDEN_SNAKES: - X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", bOneHot=False) - print "TEST len=", len(X_test) + nb_hidden, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", False) + print len(X_test), len(Y_test) + Y_test_pict = np.array([1]*(len(X_test)-nb_hidden) + [0]*nb_hidden) X_test = [one_hot_colors(x) for x in X_test] - Y_test_flat = [y_.ravel() for y_ in Y_test] + + #useless X_test, Y_test, Y_test_pict = shuffle_in_unison(X_test, Y_test, Y_test_pict) + + X_test_pict_feat = prepare_picture_data(X_test) + X_test_directions, X_test_edge_features = prepare_data(X_test) - Y_pred = ssvm.predict( convertToSingleTypeX(X_test_directions) ) - print("Results using only directional features for edges") - print("Test accuracy: %.3f" - % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) - print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) - - # now, use more informative edge features: - crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]], inference_method=inference) - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, - switch_to='ad3', - #JL adds a max-iter sometimes - #max_iter=100, - n_jobs=1) - t0 = time.time() - ssvm.fit( convertToSingleTypeX(X_train_edge_features) , Y_train_flat) - print "Training time = %.1fs"%(time.time()-t0) - Y_pred2 = ssvm.predict( convertToSingleTypeX(X_test_edge_features) ) - print("Results using also input features for edges") - print("Test accuracy: %.3f" - % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) - print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + XX_test, YY_test =convertToTwoType(X_test, + X_test_edge_features, # list of node_feat , edges, edge_feat for pixel nodes + Y_test, + X_test_pict_feat, #a list of picture_node_features + Y_test_pict) #a list of integers [0,1] + + print np.histogram( np.hstack([y.ravel() for y in YY_test]), bins=range(14)) + + YY_pred = ssvm.predict( XX_test ) + print len(XX_test), len(YY_pred) + + print confusion_matrix(np.hstack([y.ravel() for y in YY_test]), + np.hstack([y.ravel() for y in YY_pred])) + +# Y_test_flat = np.hstack([y.ravel()[:-1] for y in YY_test]) +# Y_pred_flat = np.hstack([y.ravel()[:-1] for y in YY_pred]) +# +# print("Results using only relevant features for edges") +# print("Test accuracy: %.3f" +# % accuracy_score(Y_test_flat, Y_pred_flat)) +# print(confusion_matrix(Y_test_flat, Y_pred_flat)) +# +# Y_pict_pred = [yy.ravel()[-1] for yy in YY_pred] +# print("Results AT PICTURE LEVEL using only directional features for edges") +# print("Test accuracy: %.3f" +# % accuracy_score(Y_test_pict, Y_pict_pred)) +# print(confusion_matrix(Y_test_pict, Y_pict_pred)) + if False: # plot stuff @@ -296,7 +335,7 @@ def shuffle_XY(X,Y): a.set_yticks(()) plt.show() - + print "DONE" """ From 02b656781cbceee6ae14fdebfbad329c619a5a9e Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 30 Jan 2017 13:41:01 +0100 Subject: [PATCH 026/155] test ok --- .../test_node_type_edge_feature_graph_crf.py | 144 +++++++++++++++++- 1 file changed, 140 insertions(+), 4 deletions(-) diff --git a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py index c0e32963..d154033a 100644 --- a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py +++ b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py @@ -270,7 +270,7 @@ def test_joint_feature2(): x = (node_f, edges, edge_f) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([ np.array([0, 0]) - , np.array([0, 0, 0]) + , 2+np.array([0, 0, 0]) ]) print y g.initialize(x, y) @@ -314,7 +314,7 @@ def test_joint_feature2(): x = ( node_f, edges, edge_f) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([np.array([0, 1]), - np.array([0, 1, 2])]) + 2+np.array([0, 1, 2])]) print y g.initialize(x, y) jf = g.joint_feature(x,y) @@ -350,7 +350,7 @@ def test_joint_feature2(): x = ( node_f, edges, edge_f) print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([np.array([1, 0]), - np.array([2, 0, 1])]) + 2+np.array([2, 0, 1])]) print y g.initialize(x, y) jf = g.joint_feature(x,y) @@ -368,6 +368,139 @@ def test_joint_feature2(): 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ])) +def test_joint_feature3(): + + # ------------------------------------------------------------------------------------------- + print "---MORE COMPLEX GRAPH AGAIN :) ---------------------------------------------------------------------" + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3] #how many labels per node type? + , [3, 4] #how many features per node type? + , np.array([ [0, 2] + , [2, 3]]) #how many features per node type X node type? + ) + +# nodes = np.array( [[0,0], [0,1], [1, 0], [1, 1], [1, 2]] ) + node_f = [ np.array([ [1,1,1], [2,2,2] ]) + , np.array([ [.11, .12, .13, .14], [.21, .22, .23, .24], [.31, .32, .33, .34]]) + ] + edges = [ None + , np.array( [ + [0,1] #an edge from typ0:0 to typ1:1 + ]) + , None + , np.array( [ + [0,1], #an edge from typ0:0 to typ1:1 + [1,2] #an edge from typ1:1 to typ1:2 + ]) + ] + edge_f = [ None + , np.array([[.221, .222]]) + , None + , np.array([[.01, .02, .03 ], + [.001, .002, .003]]) + ] + + x = (node_f, edges, edge_f) + print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = np.hstack([ np.array([0, 0]) + , 2+np.array([0, 0, 0]) + ]) + print y + g.initialize(x, y) + print g.size_unaries + print g.size_pairwise + jf = g.joint_feature(x,y) + print "joint_feature = \n", `jf` + print + assert_array_equal(jf, jf) + assert_array_almost_equal(jf + , np.array([ 3. , 3. , 3. , 0. , 0. , 0. , + 0.63 , 0.66 , 0.69 , 0.72 , 0. , 0., 0., 0. , 0., 0., 0. , 0., + #edges 0 to 0 2x2 states + #typ0 typ0 EMPTY + #typ0 typ1 + .221, 0., 0., 0., 0., 0., + .222, 0., 0., 0., 0., 0., + #typ1 typ0 + 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., + #typ1 typ1 + 0.011, 0., 0., 0., 0., 0., 0., 0., 0., + 0.022, 0., 0., 0., 0., 0., 0., 0., 0., + 0.033, 0., 0., 0., 0., 0., 0., 0., 0. + ]) + ) + + print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = np.hstack([ np.array([0, 1]) + , 2+np.array([1, 1, 0]) + ]) + print y + g.initialize(x, y) + jf = g.joint_feature(x,y) + print "joint_feature = \n", `jf` + print + assert_array_equal(jf, jf) + assert_array_almost_equal(jf + , np.array([ 1. , 1. , 1. , 2. , 2. , 2. , + .31, .32, .33, .34 , .32, .34, .36, .38 , 0., 0., 0. , 0., + #edges 0 to 0 2x2 states + #typ0 typ0 EMPTY + #typ0 typ1 + 0., .221, 0., 0., 0., 0., + 0., .222, 0., 0., 0., 0., + #typ1 typ0 + 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., + #typ1 typ1 + 0., 0., 0., 0.001, 0.01, 0., 0., 0., 0., + 0., 0., 0., 0.002, 0.02, 0., 0., 0., 0., + 0., 0., 0., 0.003, 0.03, 0., 0., 0., 0. + ]) + ) + + w = np.array([ 1,1,1, 2,2,2, 10,10,10,10, 20,20,20,20, 30,30,30,30 ] + +[1.0]*51, dtype=np.float64 + ) + print `w` + ret_u = g._get_unary_potentials(x, w) + print `ret_u` + assert_array_almost_equal(ret_u,np.array([ #n_nodes x n_states + [3, 6, 0,0,0], + [6, 12, 0,0,0], + [0, 0, 5, 10, 15], + [0, 0, 9, 18, 27], + [0, 0, 13, 26, 39] + ]) + ) + + assert len(w) == g.size_joint_feature + ret_pw = g._get_pairwise_potentials(x, w) + print "PW ", `ret_pw` + assert_array_almost_equal(ret_pw,np.array([ #n_edges, n_states, n_states + # 3 edges 5 states in total + [ #edge: typ0 - typ1, 2 features + [ 0, 0, 0.443, 0.443, 0.443], + [ 0, 0, 0.443, 0.443, 0.443], + [ 0, 0, 0, 0, 0], + [ 0, 0, 0, 0, 0], + [ 0, 0, 0, 0, 0] + ], + [ #edge: typ1 - typ1, 2 features + [ 0. , 0. , 0. , 0. , 0. ], + [ 0. , 0. , 0. , 0. , 0. ], + [ 0. , 0. , 0.06 , 0.06 , 0.06 ], + [ 0. , 0. , 0.06 , 0.06 , 0.06 ], + [ 0. , 0. , 0.06 , 0.06 , 0.06 ]], + [ #edge: typ1 - typ1, 2 features + [ 0. , 0. , 0. , 0. , 0. ], + [ 0. , 0. , 0. , 0. , 0. ], + [ 0. , 0. , 0.006, 0.006, 0.006], + [ 0. , 0. , 0.006, 0.006, 0.006], + [ 0. , 0. , 0.006, 0.006, 0.006]] + ])) + def test_unary_potentials(): @@ -649,7 +782,8 @@ def test_energy_discrete(): if __name__ == "__main__": - + np.set_printoptions(precision=3, linewidth=9999) + if 0: debug_joint_feature() @@ -657,6 +791,8 @@ def test_energy_discrete(): test_joint_feature() if 1: test_joint_feature2() + if 1: + test_joint_feature3() if 1: test_unary_potentials() if 1: test_inference_util() From 80a26ac333323d25c0c191b8162ca37549c11941 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 6 Feb 2017 10:40:47 +0100 Subject: [PATCH 027/155] Andreas's code with main code in a if __name__ == ... --- examples/plot_snakes.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/examples/plot_snakes.py b/examples/plot_snakes.py index c535060d..bc251899 100644 --- a/examples/plot_snakes.py +++ b/examples/plot_snakes.py @@ -104,8 +104,8 @@ def prepare_data(X): inference = 'qpbo' # first, train on X with directions only: crf = EdgeFeatureGraphCRF(inference_method=inference) - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, - n_jobs=1) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, + n_jobs=1) ssvm.fit(X_train_directions, Y_train_flat) # Evaluate using confusion matrix. @@ -118,12 +118,12 @@ def prepare_data(X): print("Results using only directional features for edges") print("Test accuracy: %.3f" % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) - print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) - - # now, use more informative edge features: - crf = EdgeFeatureGraphCRF(inference_method=inference) - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', - n_jobs=-1) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) + + # now, use more informative edge features: + crf = EdgeFeatureGraphCRF(inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', + n_jobs=-1) ssvm.fit(X_train_edge_features, Y_train_flat) Y_pred2 = ssvm.predict(X_test_edge_features) print("Results using also input features for edges") @@ -131,7 +131,7 @@ def prepare_data(X): % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) - if False: + if True: # plot stuff fig, axes = plt.subplots(2, 2) axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') From ec9ce5b7077abcf36d807742fdc13ac9c32c15a1 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 6 Feb 2017 10:51:39 +0100 Subject: [PATCH 028/155] ok --- examples/plot_snakes_typed.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/plot_snakes_typed.py b/examples/plot_snakes_typed.py index 4c54989c..8d1e0add 100644 --- a/examples/plot_snakes_typed.py +++ b/examples/plot_snakes_typed.py @@ -99,7 +99,7 @@ def convertToSingleTypeX(X): # now, use more informative edge features: crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]], inference_method=inference) ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', - verbose=1, + #verbose=1, n_jobs=8) ssvm.fit( convertToSingleTypeX(X_train_edge_features), Y_train_flat) Y_pred2 = ssvm.predict( convertToSingleTypeX(X_test_edge_features) ) From 744babd0ec5bba27fb01722d3c785d789e763fd6 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 6 Feb 2017 11:22:47 +0100 Subject: [PATCH 029/155] ok --- examples/plot_snakes_constraints.py | 260 ++++++++++++++-------------- 1 file changed, 130 insertions(+), 130 deletions(-) diff --git a/examples/plot_snakes_constraints.py b/examples/plot_snakes_constraints.py index dfdc55a6..7108e830 100644 --- a/examples/plot_snakes_constraints.py +++ b/examples/plot_snakes_constraints.py @@ -44,67 +44,24 @@ """ import time import numpy as np -bPlot = False -if bPlot: - import matplotlib.pyplot as plt -from sklearn.preprocessing import label_binarize from sklearn.metrics import confusion_matrix, accuracy_score from pystruct.learners import OneSlackSSVM from pystruct.datasets import load_snakes -from pystruct.utils import make_grid_edges, edge_list_to_features from pystruct.models import EdgeFeatureGraphCRF +from plot_snakes import one_hot_colors, prepare_data -def one_hot_colors(x): - x = x / 255 - flat = np.dot(x.reshape(-1, 3), 2 ** np.arange(3)) - one_hot = label_binarize(flat, classes=[1, 2, 3, 4, 6]) - return one_hot.reshape(x.shape[0], x.shape[1], 5) - - -def neighborhood_feature(x): - """Add a 3x3 neighborhood around each pixel as a feature.""" - # we could also use a four neighborhood, that would work even better - # but one might argue then we are using domain knowledge ;) - features = np.zeros((x.shape[0], x.shape[1], 5, 9)) - # position 3 is background. - features[:, :, 3, :] = 1 - features[1:, 1:, :, 0] = x[:-1, :-1, :] - features[:, 1:, :, 1] = x[:, :-1, :] - features[:-1, 1:, :, 2] = x[1:, :-1, :] - features[1:, :, :, 3] = x[:-1, :, :] - features[:-1, :-1, :, 4] = x[1:, 1:, :] - features[:-1, :, :, 5] = x[1:, :, :] - features[1:, :-1, :, 6] = x[:-1, 1:, :] - features[:, :-1, :, 7] = x[:, 1:, :] - features[:, :, :, 8] = x[:, :, :] - return features.reshape(x.shape[0] * x.shape[1], -1) - - -def prepare_data(X): - X_directions = [] - X_edge_features = [] - for x in X: - # get edges in grid - right, down = make_grid_edges(x, return_lists=True) - edges = np.vstack([right, down]) - # use 3x3 patch around each point - features = neighborhood_feature(x) - # simple edge feature that encodes just if an edge is horizontal or - # vertical - edge_features_directions = edge_list_to_features([right, down]) - # edge feature that contains features from the nodes that the edge connects - edge_features = np.zeros((edges.shape[0], features.shape[1], 4)) - edge_features[:len(right), :, 0] = features[right[:, 0]] - edge_features[:len(right), :, 1] = features[right[:, 1]] - edge_features[len(right):, :, 0] = features[down[:, 0]] - edge_features[len(right):, :, 1] = features[down[:, 1]] - edge_features = edge_features.reshape(edges.shape[0], -1) - X_directions.append((features, edges, edge_features_directions)) - X_edge_features.append((features, edges, edge_features)) - return X_directions, X_edge_features +def REPORT(l_Y_GT, lY_Pred, t=None): + if t: print "\t( predict DONE IN %.1fs)"%t + + _flat_GT, _flat_P = (np.hstack([y.ravel() for y in l_Y_GT]), + np.hstack([y.ravel() for y in lY_Pred])) + confmat = confusion_matrix(_flat_GT, _flat_P) + print confmat + print "\ttrace =", confmat.trace() + print "\tAccuracy= %.3f"%accuracy_score(_flat_GT, _flat_P) print("Please be patient. Learning will take 5-20 minutes.") @@ -116,7 +73,18 @@ def prepare_data(X): Y_train_flat = [y_.ravel() for y_ in Y_train] X_train_directions, X_train_edge_features = prepare_data(X_train) +print "%d picture for training"%len(X_train) + +# Evaluate using confusion matrix. +# Clearly the middel of the snake is the hardest part. +X_test, Y_test = snakes['X_test'], snakes['Y_test'] +X_test = [one_hot_colors(x) for x in X_test] +Y_test_flat = [y_.ravel() for y_ in Y_test] +X_test_directions, X_test_edge_features = prepare_data(X_test) +print "%d picture for test"%len(X_test) + +print "- TRAINING ONLY WITH DIRECTIONAL EDGE FEATURES -----" #inference = 'qpbo' #I'm interested in AD3 inference. inference = 'ad3' @@ -125,21 +93,21 @@ def prepare_data(X): crf = EdgeFeatureGraphCRF(inference_method=inference) ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, n_jobs=1) +t0 = time.time() ssvm.fit(X_train_directions, Y_train_flat) +print("Model EdgeFeatureGraphCRF fitted. %.1fs"%(time.time()-t0)) -# Evaluate using confusion matrix. -# Clearly the middel of the snake is the hardest part. -X_test, Y_test = snakes['X_test'], snakes['Y_test'] -X_test = [one_hot_colors(x) for x in X_test] -Y_test_flat = [y_.ravel() for y_ in Y_test] -X_test_directions, X_test_edge_features = prepare_data(X_test) - +Y_GT = np.hstack(Y_test_flat) +print("- Results using only directional features for edges. %.1fs"%(time.time()-t0)) t0 = time.time() Y_pred = ssvm.predict(X_test_directions) -print("Results using only directional features for edges. %.1fs"%(time.time()-t0)) -print("Test accuracy: %.3f" - % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) -print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) +REPORT(Y_GT, Y_pred, time.time()-t0) + +print "- Result with binarized graph" +t0 = time.time() +Y_pred = ssvm.predict(X_test_directions, [True]*len(X_test_directions)) +REPORT(Y_GT, Y_pred, time.time()-t0) + #Predict under constraints def buildConstraints(X, bOne=True): @@ -162,59 +130,50 @@ def buildConstraints(X, bOne=True): lConstraint.append( lConstraintPerGraph ) return lConstraint - + +print "- Results of inference under constraints" lConstraint = buildConstraints(X_test_directions) t0 = time.time() -Y_predC = ssvm.predict(X_test_directions, lConstraint) -print("Same test with hard logic constraints. %.1fs"%(time.time()-t0)) -print("Test accuracy: %.3f" - % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_predC))) -print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_predC))) +Y_pred = ssvm.predict(X_test_directions, lConstraint) +REPORT(Y_GT, Y_pred, time.time()-t0) # now, use more informative edge features: +print "- NOW TRAINING WITH BETTER EDGE FEATURES -----" +inference = 'qpbo' crf = EdgeFeatureGraphCRF(inference_method=inference) ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', - n_jobs=-1) + n_jobs=1) +t0 = time.time() ssvm.fit(X_train_edge_features, Y_train_flat) +print("Model EdgeFeatureGraphCRF fitted. %.1fs"%(time.time()-t0)) + + +print("- Results using also input features for edges. %.1fs"%(time.time()-t0)) t0 = time.time() -Y_pred2 = ssvm.predict(X_test_edge_features) -print("Results using also input features for edges. %.1fs"%(time.time()-t0)) -print("Test accuracy: %.3f" - % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) -print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) +Y_pred = ssvm.predict(X_test_edge_features) +REPORT(Y_GT, Y_pred, time.time()-t0) + +print "- Result with binarized graph" +t0 = time.time() +Y_pred = ssvm.predict(X_test_edge_features, [True]*len(X_test_edge_features)) +REPORT(Y_GT, Y_pred, time.time()-t0) #Predict under constraints +print "- Results of inference under constraints" lConstraint = buildConstraints(X_test_edge_features) t0 = time.time() -Y_pred2C = ssvm.predict(X_test_edge_features, lConstraint) -print("Same test with hard logic constraints. %.1fs"%(time.time()-t0)) -print("Test accuracy: %.3f" - % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2C))) -print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2C))) - -if bPlot: - # plot stuff - fig, axes = plt.subplots(2, 2) - axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') - axes[0, 0].set_title('Input') - y = Y_test[0].astype(np.int) - bg = 2 * (y != 0) # enhance contrast - axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) - axes[0, 1].set_title("Ground Truth") - axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 0].set_title("Prediction w/o edge features") - axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 1].set_title("Prediction with edge features") - for a in axes.ravel(): - a.set_xticks(()) - a.set_yticks(()) - plt.show() +Y_pred = ssvm.predict(X_test_edge_features, lConstraint) +REPORT(Y_GT, Y_pred, time.time()-t0) + """ -> python plot_snakes_constraints_DEVTEST.py Please be patient. Learning will take 5-20 minutes. -Results using only directional features for edges. 1.0s -Test accuracy: 0.854 +200 picture for training +100 picture for test +- TRAINING ONLY WITH DIRECTIONAL EDGE FEATURES ----- +Model EdgeFeatureGraphCRF fitted. 115.9s +- Results using only directional features for edges. 115.9s + ( predict DONE IN 0.7s) [[2750 0 0 0 0 0 0 0 0 0 0] [ 0 100 0 0 0 0 0 0 0 0 0] [ 0 0 59 0 22 4 6 1 7 1 0] @@ -226,44 +185,85 @@ def buildConstraints(X, bOne=True): [ 0 0 7 2 14 10 16 4 25 0 22] [ 0 0 0 3 7 14 4 12 2 58 0] [ 0 0 5 3 11 3 7 0 5 0 66]] -Same test with hard logic constraints. 89.1s -Test accuracy: 0.871 + trace = 3201 + Accuracy= 0.854 +- Result with binarized graph + ( predict DONE IN 0.7s) [[2750 0 0 0 0 0 0 0 0 0 0] [ 0 100 0 0 0 0 0 0 0 0 0] - [ 1 0 65 1 19 2 2 2 7 0 1] - [ 0 0 2 41 4 20 1 20 5 6 1] - [ 0 0 15 3 32 5 24 3 11 3 4] - [ 0 0 1 24 3 32 8 20 4 6 2] - [ 0 0 9 2 19 9 29 6 20 5 1] - [ 0 0 2 14 5 19 11 33 2 11 3] - [ 0 0 3 4 8 5 18 5 43 3 11] - [ 0 0 0 1 4 9 3 15 0 66 2] - [ 0 0 6 2 2 0 4 0 10 2 74]] -Results using also input features for edges. 2.2s -Test accuracy: 0.998 + [ 0 0 59 0 22 4 6 1 7 1 0] + [ 0 3 1 29 5 31 8 18 1 3 1] + [ 0 1 13 2 30 11 25 1 13 3 1] + [ 0 1 1 9 4 46 11 15 3 9 1] + [ 0 1 7 2 24 10 21 7 23 2 3] + [ 0 0 1 6 7 35 10 17 3 21 0] + [ 0 0 7 2 14 10 16 4 25 0 22] + [ 0 0 0 3 7 14 4 12 2 58 0] + [ 0 0 5 3 11 3 7 0 5 0 66]] + trace = 3201 + Accuracy= 0.854 +- Results of inference under constraints + ( predict DONE IN 0.7s) [[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 59 0 22 4 6 1 7 1 0] + [ 0 3 1 29 5 31 8 18 1 3 1] + [ 0 1 13 2 30 11 25 1 13 3 1] + [ 0 1 1 9 4 46 11 15 3 9 1] + [ 0 1 7 2 24 10 21 7 23 2 3] + [ 0 0 1 6 7 35 10 17 3 21 0] + [ 0 0 7 2 14 10 16 4 25 0 22] + [ 0 0 0 3 7 14 4 12 2 58 0] + [ 0 0 5 3 11 3 7 0 5 0 66]] + trace = 3201 + Accuracy= 0.854 +- NOW TRAINING WITH BETTER EDGE FEATURES ----- +Model EdgeFeatureGraphCRF fitted. 679.6s +- Results using also input features for edges. 679.6s + ( predict DONE IN 0.9s) +[[2749 0 0 0 0 0 0 0 1 0 0] [ 0 100 0 0 0 0 0 0 0 0 0] [ 0 0 100 0 0 0 0 0 0 0 0] [ 0 0 0 100 0 0 0 0 0 0 0] [ 0 0 0 0 98 0 1 0 1 0 0] [ 0 0 0 2 0 98 0 0 0 0 0] [ 0 0 0 0 2 0 98 0 0 0 0] - [ 0 0 0 0 0 2 0 98 0 0 0] - [ 0 0 0 0 0 0 1 0 99 0 0] - [ 0 0 0 0 0 0 0 0 0 100 0] - [ 0 0 0 0 0 0 0 0 0 0 100]] -Same test with hard logic constraints. 5.8s -Test accuracy: 0.998 -[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 1 0 0 0 2 0 97 0 0 0] + [ 0 0 1 0 0 0 1 0 98 0 0] + [ 0 0 0 1 0 0 0 0 0 99 0] + [ 0 0 0 0 1 0 0 0 0 0 99]] + trace = 3736 + Accuracy= 0.996 +- Result with binarized graph + ( predict DONE IN 0.9s) +[[2749 0 0 0 0 0 0 0 1 0 0] [ 0 100 0 0 0 0 0 0 0 0 0] [ 0 0 100 0 0 0 0 0 0 0 0] - [ 0 0 0 99 0 0 0 0 0 1 0] - [ 0 0 0 0 99 0 1 0 0 0 0] - [ 0 0 0 1 0 99 0 0 0 0 0] - [ 0 0 0 0 1 0 99 0 0 0 0] - [ 0 0 0 0 0 1 0 99 0 0 0] - [ 0 0 0 0 0 0 1 0 99 0 0] - [ 0 0 0 0 0 0 0 1 0 99 0] - [ 0 0 0 0 0 0 0 0 0 0 100]] + [ 0 0 0 100 0 0 0 0 0 0 0] + [ 0 0 0 0 98 0 1 0 1 0 0] + [ 0 0 0 2 0 98 0 0 0 0 0] + [ 0 0 0 0 2 0 98 0 0 0 0] + [ 0 1 0 0 0 2 0 97 0 0 0] + [ 0 0 1 0 0 0 1 0 98 0 0] + [ 0 0 0 1 0 0 0 0 0 99 0] + [ 0 0 0 0 1 0 0 0 0 0 99]] + trace = 3736 + Accuracy= 0.996 +- Results of inference under constraints + ( predict DONE IN 0.9s) +[[2749 0 0 0 0 0 0 0 1 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 100 0 0 0 0 0 0 0] + [ 0 0 0 0 98 0 1 0 1 0 0] + [ 0 0 0 2 0 98 0 0 0 0 0] + [ 0 0 0 0 2 0 98 0 0 0 0] + [ 0 1 0 0 0 2 0 97 0 0 0] + [ 0 0 1 0 0 0 1 0 98 0 0] + [ 0 0 0 1 0 0 0 0 0 99 0] + [ 0 0 0 0 1 0 0 0 0 0 99]] + trace = 3736 + Accuracy= 0.996 + """ \ No newline at end of file From e6cd24c16a10f6ab34c1484944d96f9b76ae4ec0 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 6 Feb 2017 12:01:21 +0100 Subject: [PATCH 030/155] Logs of snakes examples --- examples/logs/plot_hidden_snakes.log | 58 + examples/logs/plot_snakes.log | 27 + examples/logs/plot_snakes_constraints.log | 97 ++ examples/logs/plot_snakes_typed.log | 1476 +++++++++++++++++++++ 4 files changed, 1658 insertions(+) create mode 100644 examples/logs/plot_hidden_snakes.log create mode 100644 examples/logs/plot_snakes.log create mode 100644 examples/logs/plot_snakes_constraints.log create mode 100644 examples/logs/plot_snakes_typed.log diff --git a/examples/logs/plot_hidden_snakes.log b/examples/logs/plot_hidden_snakes.log new file mode 100644 index 00000000..4a9eb1e0 --- /dev/null +++ b/examples/logs/plot_hidden_snakes.log @@ -0,0 +1,58 @@ +Please be patient. Learning will take 5-20 minutes. +NCELL= 10 +ADDING PICTURE WIHOUT SNAKES!!! 200 elements in train + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! +376 picture for training +ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! +187 picture for test +EdgeFeatureGraphCRF +Training time = 605.9s +Results using input features for edges +Test accuracy: 0.920 +[[5633 37 37 39 37 38 32 29 37 47 49] + [ 14 85 1 0 0 0 0 0 0 0 0] + [ 13 0 85 1 0 0 0 0 0 1 0] + [ 12 0 0 82 1 3 1 1 0 0 0] + [ 12 0 0 0 79 1 7 1 0 0 0] + [ 11 2 0 2 1 77 0 6 1 0 0] + [ 9 0 3 1 2 1 79 0 5 0 0] + [ 9 0 0 3 1 2 1 81 0 3 0] + [ 8 0 0 0 3 1 2 1 84 0 1] + [ 9 0 0 0 0 3 1 2 1 84 0] + [ 7 0 0 0 0 0 3 1 1 1 87]] diff --git a/examples/logs/plot_snakes.log b/examples/logs/plot_snakes.log new file mode 100644 index 00000000..ab590b97 --- /dev/null +++ b/examples/logs/plot_snakes.log @@ -0,0 +1,27 @@ +Please be patient. Learning will take 5-20 minutes. +Results using only directional features for edges +Test accuracy: 0.829 +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 98 0 0 1 0 0 0 1 0 0] + [ 0 6 38 3 34 8 1 2 5 1 2] + [ 0 9 8 10 8 41 1 12 3 7 1] + [ 0 1 14 2 37 8 1 9 21 5 2] + [ 0 4 2 9 16 29 2 19 11 7 1] + [ 0 2 13 3 30 16 2 7 20 5 2] + [ 0 7 5 8 15 29 3 14 8 11 0] + [ 0 3 10 3 29 10 1 6 20 3 15] + [ 0 9 3 2 10 8 0 15 4 46 3] + [ 0 2 7 3 9 1 1 3 7 3 64]] +Results using also input features for edges +Test accuracy: 0.996 +[[2749 0 0 0 0 0 0 0 1 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 100 0 0 0 0 0 0 0] + [ 0 0 0 0 98 0 1 0 1 0 0] + [ 0 0 0 2 0 98 0 0 0 0 0] + [ 0 0 0 0 2 0 98 0 0 0 0] + [ 0 1 0 0 0 2 0 97 0 0 0] + [ 0 0 1 0 0 0 1 0 98 0 0] + [ 0 0 0 1 0 0 0 0 0 99 0] + [ 0 0 0 0 1 0 0 0 0 0 99]] diff --git a/examples/logs/plot_snakes_constraints.log b/examples/logs/plot_snakes_constraints.log new file mode 100644 index 00000000..3e4e144d --- /dev/null +++ b/examples/logs/plot_snakes_constraints.log @@ -0,0 +1,97 @@ +Please be patient. Learning will take 5-20 minutes. +200 picture for training +100 picture for test +- TRAINING ONLY WITH DIRECTIONAL EDGE FEATURES ----- +Model EdgeFeatureGraphCRF fitted. 131.3s +- Results using only directional features for edges. 131.3s + ( predict DONE IN 0.8s) +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 59 0 22 4 6 1 7 1 0] + [ 0 3 1 29 5 31 8 18 1 3 1] + [ 0 1 13 2 30 11 25 1 13 3 1] + [ 0 1 1 9 4 46 11 15 3 9 1] + [ 0 1 7 2 24 10 21 7 23 2 3] + [ 0 0 1 6 7 35 10 17 3 21 0] + [ 0 0 7 2 14 10 16 4 25 0 22] + [ 0 0 0 3 7 14 4 12 2 58 0] + [ 0 0 5 3 11 3 7 0 5 0 66]] + trace = 3201 + Accuracy= 0.854 +- Result with binarized graph + ( predict DONE IN 0.8s) +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 59 0 22 4 6 1 7 1 0] + [ 0 3 1 29 5 31 8 18 1 3 1] + [ 0 1 13 2 30 11 25 1 13 3 1] + [ 0 1 1 9 4 46 11 15 3 9 1] + [ 0 1 7 2 24 10 21 7 23 2 3] + [ 0 0 1 6 7 35 10 17 3 21 0] + [ 0 0 7 2 14 10 16 4 25 0 22] + [ 0 0 0 3 7 14 4 12 2 58 0] + [ 0 0 5 3 11 3 7 0 5 0 66]] + trace = 3201 + Accuracy= 0.854 +- Results of inference under constraints + ( predict DONE IN 0.8s) +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 59 0 22 4 6 1 7 1 0] + [ 0 3 1 29 5 31 8 18 1 3 1] + [ 0 1 13 2 30 11 25 1 13 3 1] + [ 0 1 1 9 4 46 11 15 3 9 1] + [ 0 1 7 2 24 10 21 7 23 2 3] + [ 0 0 1 6 7 35 10 17 3 21 0] + [ 0 0 7 2 14 10 16 4 25 0 22] + [ 0 0 0 3 7 14 4 12 2 58 0] + [ 0 0 5 3 11 3 7 0 5 0 66]] + trace = 3201 + Accuracy= 0.854 +- NOW TRAINING WITH BETTER EDGE FEATURES ----- +Model EdgeFeatureGraphCRF fitted. 740.4s +- Results using also input features for edges. 740.4s + ( predict DONE IN 1.0s) +[[2749 0 0 0 0 0 0 0 1 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 100 0 0 0 0 0 0 0] + [ 0 0 0 0 98 0 1 0 1 0 0] + [ 0 0 0 2 0 98 0 0 0 0 0] + [ 0 0 0 0 2 0 98 0 0 0 0] + [ 0 1 0 0 0 2 0 97 0 0 0] + [ 0 0 1 0 0 0 1 0 98 0 0] + [ 0 0 0 1 0 0 0 0 0 99 0] + [ 0 0 0 0 1 0 0 0 0 0 99]] + trace = 3736 + Accuracy= 0.996 +- Result with binarized graph + ( predict DONE IN 1.0s) +[[2749 0 0 0 0 0 0 0 1 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 100 0 0 0 0 0 0 0] + [ 0 0 0 0 98 0 1 0 1 0 0] + [ 0 0 0 2 0 98 0 0 0 0 0] + [ 0 0 0 0 2 0 98 0 0 0 0] + [ 0 1 0 0 0 2 0 97 0 0 0] + [ 0 0 1 0 0 0 1 0 98 0 0] + [ 0 0 0 1 0 0 0 0 0 99 0] + [ 0 0 0 0 1 0 0 0 0 0 99]] + trace = 3736 + Accuracy= 0.996 +- Results of inference under constraints + ( predict DONE IN 1.0s) +[[2749 0 0 0 0 0 0 0 1 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 100 0 0 0 0 0 0 0] + [ 0 0 0 0 98 0 1 0 1 0 0] + [ 0 0 0 2 0 98 0 0 0 0 0] + [ 0 0 0 0 2 0 98 0 0 0 0] + [ 0 1 0 0 0 2 0 97 0 0 0] + [ 0 0 1 0 0 0 1 0 98 0 0] + [ 0 0 0 1 0 0 0 0 0 99 0] + [ 0 0 0 0 1 0 0 0 0 0 99]] + trace = 3736 + Accuracy= 0.996 diff --git a/examples/logs/plot_snakes_typed.log b/examples/logs/plot_snakes_typed.log new file mode 100644 index 00000000..0a4e7a3f --- /dev/null +++ b/examples/logs/plot_snakes_typed.log @@ -0,0 +1,1476 @@ +Please be patient. Learning will take 5-20 minutes. +1000 inference calls +2000 inference calls +3000 inference calls +4000 inference calls +5000 inference calls +6000 inference calls +Results using only directional features for edges +Test accuracy: 0.829 +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 98 0 0 1 0 0 0 1 0 0] + [ 0 6 38 3 34 8 1 2 5 1 2] + [ 0 9 8 10 8 41 1 12 3 7 1] + [ 0 1 14 2 37 8 1 9 21 5 2] + [ 0 4 2 9 16 29 2 19 11 7 1] + [ 0 2 13 3 30 16 2 7 20 5 2] + [ 0 7 5 8 15 29 3 14 8 11 0] + [ 0 3 10 3 29 10 1 6 20 3 15] + [ 0 9 3 2 10 8 0 15 4 46 3] + [ 0 2 7 3 9 1 1 3 7 3 64]] +Training 1-slack dual structural SVM +iteration 0 +cutting plane objective: 0.019872, primal objective 756.600000 +iteration 1 +new constraint too weak. +cutting plane objective: 0.038904, primal objective 462.213801 +iteration 2 +cutting plane objective: 0.039553, primal objective 15.695517 +iteration 3 +cutting plane objective: 0.135721, primal objective 499.742843 +iteration 4 +cutting plane objective: 0.141298, primal objective 18.615756 +iteration 5 +cutting plane objective: 0.180218, primal objective 517.912014 +iteration 6 +cutting plane objective: 0.200170, primal objective 51.516560 +iteration 7 +cutting plane objective: 0.217854, primal objective 336.931437 +iteration 8 +cutting plane objective: 0.233433, primal objective 46.977896 +iteration 9 +cutting plane objective: 0.265987, primal objective 281.416928 +iteration 10 +cutting plane objective: 0.293149, primal objective 33.545220 +iteration 11 +cutting plane objective: 0.310093, primal objective 308.614278 +iteration 12 +cutting plane objective: 0.331982, primal objective 47.636283 +iteration 13 +cutting plane objective: 0.396049, primal objective 286.505546 +iteration 14 +cutting plane objective: 0.421507, primal objective 32.833105 +iteration 15 +cutting plane objective: 0.447097, primal objective 325.530203 +iteration 16 +cutting plane objective: 0.471307, primal objective 61.175845 +iteration 17 +cutting plane objective: 0.538959, primal objective 286.387701 +iteration 18 +cutting plane objective: 0.553061, primal objective 54.961277 +iteration 19 +cutting plane objective: 0.732316, primal objective 276.671828 +iteration 20 +cutting plane objective: 0.765760, primal objective 83.412089 +iteration 21 +cutting plane objective: 0.850887, primal objective 77.632448 +iteration 22 +cutting plane objective: 0.905878, primal objective 59.206131 +iteration 23 +cutting plane objective: 1.042260, primal objective 278.294152 +iteration 24 +cutting plane objective: 1.070590, primal objective 76.604480 +iteration 25 +cutting plane objective: 1.123092, primal objective 49.977941 +iteration 26 +cutting plane objective: 1.271715, primal objective 331.240125 +iteration 27 +cutting plane objective: 1.286027, primal objective 53.541896 +iteration 28 +cutting plane objective: 1.617411, primal objective 377.967855 +iteration 29 +cutting plane objective: 1.798357, primal objective 79.846862 +iteration 30 +cutting plane objective: 2.082935, primal objective 304.828385 +iteration 31 +cutting plane objective: 2.675264, primal objective 117.951119 +iteration 32 +cutting plane objective: 2.844978, primal objective 64.758097 +iteration 33 +cutting plane objective: 3.287955, primal objective 342.055089 +iteration 34 +cutting plane objective: 3.388039, primal objective 88.711681 +iteration 35 +cutting plane objective: 3.721702, primal objective 74.197913 +iteration 36 +cutting plane objective: 4.063515, primal objective 408.218394 +iteration 37 +cutting plane objective: 4.404916, primal objective 96.404884 +iteration 38 +cutting plane objective: 4.493112, primal objective 388.749621 +iteration 39 +cutting plane objective: 4.629265, primal objective 80.523698 +iteration 40 +cutting plane objective: 4.908023, primal objective 180.172472 +iteration 41 +cutting plane objective: 5.047723, primal objective 69.013924 +iteration 42 +cutting plane objective: 5.314418, primal objective 74.058355 +iteration 43 +cutting plane objective: 5.548530, primal objective 67.863726 +iteration 44 +cutting plane objective: 5.701956, primal objective 53.170459 +iteration 45 +cutting plane objective: 5.857337, primal objective 50.467279 +iteration 46 +cutting plane objective: 5.971032, primal objective 57.336636 +iteration 47 +cutting plane objective: 6.049148, primal objective 46.686498 +iteration 48 +cutting plane objective: 6.310814, primal objective 193.970238 +iteration 49 +cutting plane objective: 6.594890, primal objective 53.553441 +iteration 50 +cutting plane objective: 6.817985, primal objective 61.540080 +iteration 51 +cutting plane objective: 6.905080, primal objective 53.958899 +iteration 52 +cutting plane objective: 6.996705, primal objective 50.189089 +iteration 53 +cutting plane objective: 7.238325, primal objective 134.945180 +iteration 54 +cutting plane objective: 7.359412, primal objective 57.380775 +iteration 55 +cutting plane objective: 7.533335, primal objective 52.485116 +iteration 56 +cutting plane objective: 7.671114, primal objective 50.081620 +iteration 57 +cutting plane objective: 7.764426, primal objective 55.497301 +iteration 58 +cutting plane objective: 7.879441, primal objective 50.653875 +iteration 59 +cutting plane objective: 7.948227, primal objective 45.092745 +iteration 60 +cutting plane objective: 8.022129, primal objective 43.754028 +iteration 61 +cutting plane objective: 8.086457, primal objective 39.429920 +iteration 62 +cutting plane objective: 8.143238, primal objective 117.167563 +iteration 63 +cutting plane objective: 8.311361, primal objective 51.726534 +iteration 64 +cutting plane objective: 8.382285, primal objective 45.834890 +iteration 65 +cutting plane objective: 8.445380, primal objective 40.064655 +iteration 66 +cutting plane objective: 8.515011, primal objective 37.831118 +iteration 67 +cutting plane objective: 8.617629, primal objective 36.393356 +iteration 68 +cutting plane objective: 8.681467, primal objective 34.840377 +iteration 69 +cutting plane objective: 8.976755, primal objective 110.674298 +iteration 70 +cutting plane objective: 9.246389, primal objective 61.375676 +iteration 71 +cutting plane objective: 9.668646, primal objective 59.305100 +iteration 72 +cutting plane objective: 9.875519, primal objective 57.280319 +iteration 73 +cutting plane objective: 10.027298, primal objective 56.104111 +iteration 74 +cutting plane objective: 10.214066, primal objective 49.943404 +iteration 75 +cutting plane objective: 10.348591, primal objective 42.373991 +iteration 76 +cutting plane objective: 10.360995, primal objective 46.056028 +iteration 77 +cutting plane objective: 10.490433, primal objective 35.739535 +iteration 78 +cutting plane objective: 10.660000, primal objective 92.701122 +iteration 79 +cutting plane objective: 10.897688, primal objective 54.777889 +iteration 80 +cutting plane objective: 11.086600, primal objective 53.689534 +iteration 81 +cutting plane objective: 11.141144, primal objective 54.034713 +iteration 82 +cutting plane objective: 11.284600, primal objective 42.644617 +iteration 83 +cutting plane objective: 11.380347, primal objective 48.407249 +iteration 84 +cutting plane objective: 11.416572, primal objective 44.132411 +iteration 85 +cutting plane objective: 11.571412, primal objective 34.961918 +iteration 86 +cutting plane objective: 11.704028, primal objective 38.640979 +iteration 87 +cutting plane objective: 11.784767, primal objective 38.241169 +iteration 88 +cutting plane objective: 11.830782, primal objective 41.310102 +iteration 89 +cutting plane objective: 11.872251, primal objective 35.710610 +iteration 90 +cutting plane objective: 11.970451, primal objective 29.776013 +iteration 91 +cutting plane objective: 12.042980, primal objective 70.255281 +iteration 92 +cutting plane objective: 12.321428, primal objective 47.621574 +iteration 93 +cutting plane objective: 12.434090, primal objective 54.820456 +iteration 94 +cutting plane objective: 12.545058, primal objective 44.277521 +iteration 95 +cutting plane objective: 12.579911, primal objective 50.366843 +iteration 96 +cutting plane objective: 12.703294, primal objective 42.584152 +iteration 97 +cutting plane objective: 12.814386, primal objective 44.675268 +iteration 98 +cutting plane objective: 12.877223, primal objective 41.281536 +iteration 99 +cutting plane objective: 12.921012, primal objective 37.439323 +iteration 100 +cutting plane objective: 12.998230, primal objective 35.289201 +iteration 101 +cutting plane objective: 13.071419, primal objective 36.749097 +iteration 102 +cutting plane objective: 13.140595, primal objective 31.122268 +iteration 103 +cutting plane objective: 13.238240, primal objective 31.039180 +iteration 104 +cutting plane objective: 13.274355, primal objective 32.384291 +iteration 105 +cutting plane objective: 13.342754, primal objective 27.726460 +iteration 106 +cutting plane objective: 13.378876, primal objective 56.737089 +iteration 107 +cutting plane objective: 13.513287, primal objective 45.070374 +iteration 108 +cutting plane objective: 13.668893, primal objective 45.242897 +iteration 109 +cutting plane objective: 13.772756, primal objective 42.252533 +iteration 110 +cutting plane objective: 13.848949, primal objective 38.421927 +iteration 111 +cutting plane objective: 13.918798, primal objective 32.979882 +iteration 112 +cutting plane objective: 14.014080, primal objective 35.216789 +iteration 113 +cutting plane objective: 14.062768, primal objective 41.931717 +iteration 114 +cutting plane objective: 14.129279, primal objective 30.476606 +iteration 115 +cutting plane objective: 14.199358, primal objective 32.496563 +iteration 116 +cutting plane objective: 14.255371, primal objective 31.287407 +iteration 117 +cutting plane objective: 14.313073, primal objective 31.771053 +iteration 118 +cutting plane objective: 14.332574, primal objective 30.729696 +iteration 119 +cutting plane objective: 14.366705, primal objective 26.617029 +iteration 120 +cutting plane objective: 14.403335, primal objective 27.628803 +iteration 121 +cutting plane objective: 14.429644, primal objective 28.567795 +iteration 122 +cutting plane objective: 14.469745, primal objective 27.639099 +iteration 123 +cutting plane objective: 14.490355, primal objective 25.586656 +iteration 124 +cutting plane objective: 14.504424, primal objective 24.510179 +iteration 125 +cutting plane objective: 14.516832, primal objective 38.118386 +iteration 126 +cutting plane objective: 14.742530, primal objective 39.861384 +iteration 127 +cutting plane objective: 14.906810, primal objective 39.531021 +iteration 128 +cutting plane objective: 14.964538, primal objective 39.741604 +iteration 129 +cutting plane objective: 15.066200, primal objective 33.027552 +iteration 130 +cutting plane objective: 15.173573, primal objective 36.010357 +iteration 131 +cutting plane objective: 15.244508, primal objective 32.454034 +iteration 132 +cutting plane objective: 15.307902, primal objective 32.142314 +iteration 133 +cutting plane objective: 15.370147, primal objective 33.227497 +iteration 134 +cutting plane objective: 15.435844, primal objective 29.290471 +iteration 135 +cutting plane objective: 15.455029, primal objective 29.740110 +iteration 136 +cutting plane objective: 15.487805, primal objective 26.241301 +iteration 137 +cutting plane objective: 15.530650, primal objective 26.389384 +iteration 138 +cutting plane objective: 15.559001, primal objective 29.019526 +iteration 139 +cutting plane objective: 15.578269, primal objective 27.657838 +iteration 140 +cutting plane objective: 15.591534, primal objective 25.981607 +iteration 141 +cutting plane objective: 15.605012, primal objective 27.118902 +iteration 142 +cutting plane objective: 15.626955, primal objective 25.609108 +iteration 143 +cutting plane objective: 15.676807, primal objective 25.950261 +iteration 144 +cutting plane objective: 15.704026, primal objective 24.426672 +iteration 145 +cutting plane objective: 15.729378, primal objective 24.653150 +iteration 146 +cutting plane objective: 15.759814, primal objective 24.408942 +iteration 147 +cutting plane objective: 15.783420, primal objective 23.747515 +iteration 148 +cutting plane objective: 15.796411, primal objective 23.745447 +iteration 149 +cutting plane objective: 15.813970, primal objective 22.341130 +iteration 150 +cutting plane objective: 15.827383, primal objective 21.512536 +iteration 151 +cutting plane objective: 15.857623, primal objective 40.008093 +iteration 152 +cutting plane objective: 16.112699, primal objective 41.946535 +iteration 153 +cutting plane objective: 16.240748, primal objective 42.477879 +iteration 154 +cutting plane objective: 16.415461, primal objective 36.934896 +iteration 155 +cutting plane objective: 16.529820, primal objective 34.629216 +iteration 156 +cutting plane objective: 16.589955, primal objective 36.567574 +iteration 157 +cutting plane objective: 16.693600, primal objective 31.592590 +iteration 158 +cutting plane objective: 16.791745, primal objective 31.562259 +iteration 159 +cutting plane objective: 16.844531, primal objective 30.922127 +iteration 160 +cutting plane objective: 16.882273, primal objective 32.110430 +iteration 161 +cutting plane objective: 16.926870, primal objective 27.542302 +iteration 162 +cutting plane objective: 16.972016, primal objective 29.909823 +iteration 163 +cutting plane objective: 16.992850, primal objective 31.024998 +iteration 164 +cutting plane objective: 17.023246, primal objective 28.302176 +iteration 165 +cutting plane objective: 17.068547, primal objective 27.389193 +iteration 166 +cutting plane objective: 17.098948, primal objective 26.376054 +iteration 167 +cutting plane objective: 17.123413, primal objective 25.140992 +iteration 168 +cutting plane objective: 17.145637, primal objective 25.293771 +iteration 169 +cutting plane objective: 17.160597, primal objective 24.891791 +iteration 170 +cutting plane objective: 17.182297, primal objective 24.854375 +iteration 171 +cutting plane objective: 17.206514, primal objective 24.229423 +iteration 172 +cutting plane objective: 17.227862, primal objective 24.138926 +iteration 173 +cutting plane objective: 17.239502, primal objective 23.948760 +iteration 174 +cutting plane objective: 17.256542, primal objective 23.679435 +iteration 175 +cutting plane objective: 17.269835, primal objective 24.211192 +iteration 176 +cutting plane objective: 17.288319, primal objective 22.446479 +iteration 177 +cutting plane objective: 17.311084, primal objective 35.034461 +iteration 178 +cutting plane objective: 17.584768, primal objective 41.303077 +iteration 179 +cutting plane objective: 17.730201, primal objective 45.557020 +iteration 180 +cutting plane objective: 17.857572, primal objective 40.515854 +iteration 181 +cutting plane objective: 17.931328, primal objective 37.035197 +iteration 182 +cutting plane objective: 18.020099, primal objective 33.692262 +iteration 183 +cutting plane objective: 18.094606, primal objective 34.565970 +iteration 184 +cutting plane objective: 18.157064, primal objective 33.558166 +iteration 185 +cutting plane objective: 18.223848, primal objective 32.875251 +iteration 186 +cutting plane objective: 18.274319, primal objective 30.253177 +iteration 187 +cutting plane objective: 18.321115, primal objective 30.265179 +iteration 188 +cutting plane objective: 18.361318, primal objective 29.046013 +iteration 189 +cutting plane objective: 18.392455, primal objective 27.982337 +iteration 190 +cutting plane objective: 18.423358, primal objective 29.604863 +iteration 191 +cutting plane objective: 18.457755, primal objective 27.372942 +iteration 192 +cutting plane objective: 18.488021, primal objective 26.884197 +iteration 193 +cutting plane objective: 18.509007, primal objective 28.104562 +iteration 194 +cutting plane objective: 18.530443, primal objective 25.625755 +iteration 195 +cutting plane objective: 18.550246, primal objective 28.297988 +iteration 196 +cutting plane objective: 18.579698, primal objective 25.486664 +iteration 197 +cutting plane objective: 18.600024, primal objective 25.889710 +iteration 198 +cutting plane objective: 18.611331, primal objective 26.601719 +iteration 199 +cutting plane objective: 18.631269, primal objective 24.391966 +iteration 200 +cutting plane objective: 18.651220, primal objective 24.362099 +iteration 201 +cutting plane objective: 18.662568, primal objective 24.995704 +iteration 202 +cutting plane objective: 18.674863, primal objective 24.783030 +iteration 203 +cutting plane objective: 18.689842, primal objective 24.238198 +iteration 204 +cutting plane objective: 18.703041, primal objective 23.189288 +iteration 205 +cutting plane objective: 18.715830, primal objective 23.246123 +iteration 206 +cutting plane objective: 18.723583, primal objective 23.362962 +iteration 207 +cutting plane objective: 18.734480, primal objective 22.584175 +iteration 208 +cutting plane objective: 18.743365, primal objective 27.858498 +iteration 209 +cutting plane objective: 18.905044, primal objective 36.345570 +iteration 210 +cutting plane objective: 19.015666, primal objective 36.723502 +iteration 211 +cutting plane objective: 19.083564, primal objective 33.532242 +iteration 212 +cutting plane objective: 19.154390, primal objective 32.651228 +iteration 213 +cutting plane objective: 19.208529, primal objective 31.088988 +iteration 214 +cutting plane objective: 19.262657, primal objective 29.947074 +iteration 215 +cutting plane objective: 19.292811, primal objective 30.141265 +iteration 216 +cutting plane objective: 19.336226, primal objective 27.883462 +iteration 217 +cutting plane objective: 19.368576, primal objective 28.155540 +iteration 218 +cutting plane objective: 19.396752, primal objective 28.576452 +iteration 219 +cutting plane objective: 19.430494, primal objective 27.383806 +iteration 220 +cutting plane objective: 19.451701, primal objective 27.277672 +iteration 221 +cutting plane objective: 19.481313, primal objective 27.606754 +iteration 222 +cutting plane objective: 19.507760, primal objective 26.099495 +iteration 223 +cutting plane objective: 19.527715, primal objective 27.356829 +iteration 224 +cutting plane objective: 19.538091, primal objective 26.129442 +iteration 225 +cutting plane objective: 19.558567, primal objective 25.426673 +iteration 226 +cutting plane objective: 19.572461, primal objective 25.768954 +iteration 227 +cutting plane objective: 19.590646, primal objective 24.653763 +iteration 228 +cutting plane objective: 19.612164, primal objective 25.222956 +iteration 229 +cutting plane objective: 19.624748, primal objective 25.107009 +iteration 230 +cutting plane objective: 19.636567, primal objective 24.838748 +iteration 231 +cutting plane objective: 19.645769, primal objective 23.729175 +iteration 232 +cutting plane objective: 19.653630, primal objective 24.007738 +iteration 233 +cutting plane objective: 19.663241, primal objective 23.591188 +iteration 234 +cutting plane objective: 19.672471, primal objective 23.541146 +iteration 235 +cutting plane objective: 19.678394, primal objective 23.703990 +iteration 236 +cutting plane objective: 19.688930, primal objective 23.197163 +iteration 237 +cutting plane objective: 19.696072, primal objective 23.777556 +iteration 238 +cutting plane objective: 19.701599, primal objective 23.344421 +iteration 239 +cutting plane objective: 19.709086, primal objective 22.861171 +iteration 240 +cutting plane objective: 19.715964, primal objective 22.718072 +iteration 241 +cutting plane objective: 19.720704, primal objective 22.759357 +iteration 242 +cutting plane objective: 19.724719, primal objective 22.488610 +iteration 243 +cutting plane objective: 19.728284, primal objective 22.090405 +iteration 244 +cutting plane objective: 19.731785, primal objective 21.893303 +iteration 245 +new constraint too weak. +no additional constraints +Switching to ad3 inference +iteration 246 +cutting plane objective: 19.740518, primal objective 277.543643 +iteration 247 +cutting plane objective: 19.747216, primal objective 54.938903 +iteration 248 +cutting plane objective: 20.361410, primal objective 121.478774 +iteration 249 +cutting plane objective: 21.038496, primal objective 69.490816 +iteration 250 +cutting plane objective: 21.444008, primal objective 62.711182 +iteration 251 +cutting plane objective: 21.712583, primal objective 54.027282 +iteration 252 +cutting plane objective: 21.891889, primal objective 52.079547 +iteration 253 +cutting plane objective: 22.150648, primal objective 45.136568 +iteration 254 +cutting plane objective: 22.376458, primal objective 116.187744 +iteration 255 +cutting plane objective: 22.987750, primal objective 72.400185 +iteration 256 +cutting plane objective: 23.107620, primal objective 65.940528 +iteration 257 +cutting plane objective: 23.435505, primal objective 56.813426 +iteration 258 +cutting plane objective: 23.502455, primal objective 58.833499 +iteration 259 +cutting plane objective: 23.821033, primal objective 51.532771 +iteration 260 +cutting plane objective: 23.997264, primal objective 62.338774 +iteration 261 +cutting plane objective: 24.148997, primal objective 52.287887 +iteration 262 +cutting plane objective: 24.284673, primal objective 48.569832 +iteration 263 +cutting plane objective: 24.394759, primal objective 48.546630 +iteration 264 +cutting plane objective: 24.504855, primal objective 51.349970 +iteration 265 +cutting plane objective: 24.603537, primal objective 46.453357 +iteration 266 +cutting plane objective: 24.843374, primal objective 105.572554 +iteration 267 +cutting plane objective: 25.082067, primal objective 62.851719 +iteration 268 +cutting plane objective: 25.273329, primal objective 64.987973 +iteration 269 +cutting plane objective: 25.466227, primal objective 54.095038 +iteration 270 +cutting plane objective: 25.628534, primal objective 53.507269 +iteration 271 +cutting plane objective: 25.822553, primal objective 57.581414 +iteration 272 +cutting plane objective: 26.013074, primal objective 52.709686 +iteration 273 +cutting plane objective: 26.148908, primal objective 51.965542 +iteration 274 +cutting plane objective: 26.242762, primal objective 50.423732 +iteration 275 +cutting plane objective: 26.362973, primal objective 48.855360 +iteration 276 +cutting plane objective: 26.519640, primal objective 54.322950 +iteration 277 +cutting plane objective: 26.602421, primal objective 53.348782 +iteration 278 +cutting plane objective: 26.703987, primal objective 45.786819 +iteration 279 +cutting plane objective: 26.731452, primal objective 93.121500 +iteration 280 +cutting plane objective: 27.098968, primal objective 71.463749 +iteration 281 +cutting plane objective: 27.399831, primal objective 62.448015 +iteration 282 +cutting plane objective: 27.682632, primal objective 61.016739 +iteration 283 +cutting plane objective: 27.816397, primal objective 59.495245 +iteration 284 +cutting plane objective: 28.012931, primal objective 54.918061 +iteration 285 +cutting plane objective: 28.155126, primal objective 57.650078 +iteration 286 +cutting plane objective: 28.392132, primal objective 50.850739 +iteration 287 +cutting plane objective: 28.520658, primal objective 55.083307 +iteration 288 +cutting plane objective: 28.652725, primal objective 49.877599 +iteration 289 +cutting plane objective: 28.744848, primal objective 49.640668 +iteration 290 +cutting plane objective: 28.829915, primal objective 49.068535 +iteration 291 +cutting plane objective: 28.918603, primal objective 47.072560 +iteration 292 +cutting plane objective: 28.989226, primal objective 46.695790 +iteration 293 +cutting plane objective: 29.079261, primal objective 44.057642 +iteration 294 +cutting plane objective: 29.291114, primal objective 89.243532 +iteration 295 +cutting plane objective: 29.647958, primal objective 61.806888 +iteration 296 +cutting plane objective: 29.806036, primal objective 64.504411 +iteration 297 +cutting plane objective: 30.056655, primal objective 59.201594 +iteration 298 +cutting plane objective: 30.247216, primal objective 58.934001 +iteration 299 +cutting plane objective: 30.426310, primal objective 55.889184 +iteration 300 +cutting plane objective: 30.458525, primal objective 57.865813 +iteration 301 +cutting plane objective: 30.676319, primal objective 52.853986 +iteration 302 +cutting plane objective: 30.843012, primal objective 54.264329 +iteration 303 +cutting plane objective: 30.937745, primal objective 52.415248 +iteration 304 +cutting plane objective: 31.029548, primal objective 48.875741 +iteration 305 +cutting plane objective: 31.126341, primal objective 49.935645 +iteration 306 +cutting plane objective: 31.240662, primal objective 49.935390 +iteration 307 +cutting plane objective: 31.343540, primal objective 47.717134 +iteration 308 +cutting plane objective: 31.384021, primal objective 51.343821 +iteration 309 +cutting plane objective: 31.473540, primal objective 45.930987 +iteration 310 +cutting plane objective: 31.487228, primal objective 86.132179 +iteration 311 +cutting plane objective: 31.656760, primal objective 61.487181 +iteration 312 +cutting plane objective: 31.719132, primal objective 58.682933 +iteration 313 +cutting plane objective: 31.881288, primal objective 53.707593 +iteration 314 +cutting plane objective: 31.996094, primal objective 57.868450 +iteration 315 +cutting plane objective: 32.119040, primal objective 52.627828 +iteration 316 +cutting plane objective: 32.243279, primal objective 50.777363 +iteration 317 +cutting plane objective: 32.329802, primal objective 50.779353 +iteration 318 +cutting plane objective: 32.428452, primal objective 51.325226 +iteration 319 +cutting plane objective: 32.511702, primal objective 49.883232 +iteration 320 +cutting plane objective: 32.579997, primal objective 47.836306 +iteration 321 +cutting plane objective: 32.667324, primal objective 48.235687 +iteration 322 +cutting plane objective: 32.741056, primal objective 46.481267 +iteration 323 +cutting plane objective: 32.826191, primal objective 46.180131 +iteration 324 +cutting plane objective: 33.034644, primal objective 73.766742 +iteration 325 +cutting plane objective: 33.209126, primal objective 59.665062 +iteration 326 +cutting plane objective: 33.434830, primal objective 56.831227 +iteration 327 +cutting plane objective: 33.621972, primal objective 57.451114 +iteration 328 +cutting plane objective: 33.804584, primal objective 55.363451 +iteration 329 +cutting plane objective: 33.966614, primal objective 55.333321 +iteration 330 +cutting plane objective: 34.131394, primal objective 51.171930 +iteration 331 +cutting plane objective: 34.269898, primal objective 57.708789 +iteration 332 +cutting plane objective: 34.369885, primal objective 53.707698 +iteration 333 +cutting plane objective: 34.458461, primal objective 52.377899 +iteration 334 +cutting plane objective: 34.552755, primal objective 48.512908 +iteration 335 +cutting plane objective: 34.580638, primal objective 50.377465 +iteration 336 +cutting plane objective: 34.669584, primal objective 48.070365 +iteration 337 +cutting plane objective: 34.755923, primal objective 50.421221 +iteration 338 +cutting plane objective: 34.831442, primal objective 49.169683 +iteration 339 +cutting plane objective: 34.876186, primal objective 49.632812 +iteration 340 +cutting plane objective: 34.925525, primal objective 47.777317 +iteration 341 +cutting plane objective: 34.998525, primal objective 48.162106 +iteration 342 +cutting plane objective: 35.045553, primal objective 48.133287 +iteration 343 +cutting plane objective: 35.109015, primal objective 46.819500 +iteration 344 +cutting plane objective: 35.155711, primal objective 47.051436 +iteration 345 +cutting plane objective: 35.196735, primal objective 46.700018 +iteration 346 +cutting plane objective: 35.237797, primal objective 46.838492 +iteration 347 +cutting plane objective: 35.283779, primal objective 45.326752 +iteration 348 +cutting plane objective: 35.521891, primal objective 66.524296 +iteration 349 +cutting plane objective: 35.703803, primal objective 57.333080 +iteration 350 +cutting plane objective: 35.906799, primal objective 57.657687 +iteration 351 +cutting plane objective: 36.053958, primal objective 56.031346 +iteration 352 +cutting plane objective: 36.234934, primal objective 53.636153 +iteration 353 +cutting plane objective: 36.341414, primal objective 56.332082 +iteration 354 +cutting plane objective: 36.444964, primal objective 57.935026 +iteration 355 +cutting plane objective: 36.576880, primal objective 54.762486 +iteration 356 +cutting plane objective: 36.688919, primal objective 53.735584 +iteration 357 +cutting plane objective: 36.791099, primal objective 52.126281 +iteration 358 +cutting plane objective: 36.876112, primal objective 52.289686 +iteration 359 +cutting plane objective: 36.963208, primal objective 51.147145 +iteration 360 +cutting plane objective: 37.069543, primal objective 51.356811 +iteration 361 +cutting plane objective: 37.151586, primal objective 50.997177 +iteration 362 +cutting plane objective: 37.225636, primal objective 51.757264 +iteration 363 +cutting plane objective: 37.291856, primal objective 49.725274 +iteration 364 +cutting plane objective: 37.365054, primal objective 49.165327 +iteration 365 +cutting plane objective: 37.421455, primal objective 49.549253 +iteration 366 +cutting plane objective: 37.469833, primal objective 49.931493 +iteration 367 +cutting plane objective: 37.521295, primal objective 48.917906 +iteration 368 +cutting plane objective: 37.567162, primal objective 48.168400 +iteration 369 +cutting plane objective: 37.609989, primal objective 48.139434 +iteration 370 +cutting plane objective: 37.645404, primal objective 48.323373 +iteration 371 +cutting plane objective: 37.685027, primal objective 47.586412 +iteration 372 +cutting plane objective: 37.717919, primal objective 46.849012 +iteration 373 +cutting plane objective: 37.746205, primal objective 47.012826 +iteration 374 +cutting plane objective: 37.777056, primal objective 45.795802 +iteration 375 +cutting plane objective: 37.808104, primal objective 46.826427 +iteration 376 +cutting plane objective: 37.842631, primal objective 45.563177 +iteration 377 +cutting plane objective: 37.997031, primal objective 61.741652 +iteration 378 +cutting plane objective: 38.137114, primal objective 55.231201 +iteration 379 +cutting plane objective: 38.264639, primal objective 55.323326 +iteration 380 +cutting plane objective: 38.351852, primal objective 54.159588 +iteration 381 +cutting plane objective: 38.453961, primal objective 51.830719 +iteration 382 +cutting plane objective: 38.526402, primal objective 51.557095 +iteration 383 +cutting plane objective: 38.610734, primal objective 50.903091 +iteration 384 +cutting plane objective: 38.694956, primal objective 50.175441 +iteration 385 +cutting plane objective: 38.750461, primal objective 50.390575 +iteration 386 +cutting plane objective: 38.816428, primal objective 51.087793 +iteration 387 +cutting plane objective: 38.824463, primal objective 51.954340 +iteration 388 +cutting plane objective: 38.889279, primal objective 49.381607 +iteration 389 +cutting plane objective: 38.967133, primal objective 49.591135 +iteration 390 +cutting plane objective: 39.043220, primal objective 49.431823 +iteration 391 +cutting plane objective: 39.090282, primal objective 50.580487 +iteration 392 +cutting plane objective: 39.135705, primal objective 48.619329 +iteration 393 +cutting plane objective: 39.187507, primal objective 48.549039 +iteration 394 +cutting plane objective: 39.237645, primal objective 48.028908 +iteration 395 +cutting plane objective: 39.284517, primal objective 47.051863 +iteration 396 +cutting plane objective: 39.330745, primal objective 47.560238 +iteration 397 +cutting plane objective: 39.370100, primal objective 47.788802 +iteration 398 +cutting plane objective: 39.413633, primal objective 48.595372 +iteration 399 +cutting plane objective: 39.451676, primal objective 47.401479 +iteration 400 +cutting plane objective: 39.478350, primal objective 47.452649 +iteration 401 +cutting plane objective: 39.508271, primal objective 46.320363 +iteration 402 +cutting plane objective: 39.524614, primal objective 46.207101 +iteration 403 +cutting plane objective: 39.548567, primal objective 45.610274 +iteration 404 +cutting plane objective: 39.567947, primal objective 45.565967 +iteration 405 +cutting plane objective: 39.587765, primal objective 45.167604 +iteration 406 +cutting plane objective: 39.621460, primal objective 61.499869 +iteration 407 +cutting plane objective: 39.735177, primal objective 54.311566 +iteration 408 +cutting plane objective: 39.818411, primal objective 54.185205 +iteration 409 +cutting plane objective: 39.893787, primal objective 52.326498 +iteration 410 +cutting plane objective: 39.966651, primal objective 51.457569 +iteration 411 +cutting plane objective: 40.025227, primal objective 50.526348 +iteration 412 +cutting plane objective: 40.085008, primal objective 50.640769 +iteration 413 +cutting plane objective: 40.138749, primal objective 49.923707 +iteration 414 +cutting plane objective: 40.172139, primal objective 49.880886 +iteration 415 +cutting plane objective: 40.207032, primal objective 49.401324 +iteration 416 +cutting plane objective: 40.248986, primal objective 49.255515 +iteration 417 +cutting plane objective: 40.274022, primal objective 48.799770 +iteration 418 +cutting plane objective: 40.317236, primal objective 48.471938 +iteration 419 +cutting plane objective: 40.362521, primal objective 48.426364 +iteration 420 +cutting plane objective: 40.408769, primal objective 49.336856 +iteration 421 +cutting plane objective: 40.444401, primal objective 48.638279 +iteration 422 +cutting plane objective: 40.478940, primal objective 47.433494 +iteration 423 +cutting plane objective: 40.511180, primal objective 48.186916 +iteration 424 +cutting plane objective: 40.546595, primal objective 47.210720 +iteration 425 +cutting plane objective: 40.572901, primal objective 48.165288 +iteration 426 +cutting plane objective: 40.611206, primal objective 47.359289 +iteration 427 +cutting plane objective: 40.638771, primal objective 47.727217 +iteration 428 +cutting plane objective: 40.670389, primal objective 46.671290 +iteration 429 +cutting plane objective: 40.696643, primal objective 47.097754 +iteration 430 +cutting plane objective: 40.717111, primal objective 46.605956 +iteration 431 +cutting plane objective: 40.745395, primal objective 46.562990 +iteration 432 +cutting plane objective: 40.765295, primal objective 46.562799 +iteration 433 +cutting plane objective: 40.787529, primal objective 45.675705 +iteration 434 +cutting plane objective: 40.896790, primal objective 57.064382 +iteration 435 +cutting plane objective: 40.984176, primal objective 53.717002 +iteration 436 +cutting plane objective: 41.055439, primal objective 51.564877 +iteration 437 +cutting plane objective: 41.121984, primal objective 50.882540 +iteration 438 +cutting plane objective: 41.182713, primal objective 52.106853 +iteration 439 +cutting plane objective: 41.240129, primal objective 51.884299 +iteration 440 +cutting plane objective: 41.314679, primal objective 52.423110 +iteration 441 +cutting plane objective: 41.366143, primal objective 51.175604 +iteration 442 +cutting plane objective: 41.415077, primal objective 51.068580 +iteration 443 +cutting plane objective: 41.453352, primal objective 50.806076 +iteration 444 +cutting plane objective: 41.511131, primal objective 50.004755 +iteration 445 +cutting plane objective: 41.557386, primal objective 50.560701 +iteration 446 +cutting plane objective: 41.605809, primal objective 49.436283 +iteration 447 +cutting plane objective: 41.648209, primal objective 49.520643 +iteration 448 +cutting plane objective: 41.676554, primal objective 50.325978 +iteration 449 +cutting plane objective: 41.718070, primal objective 48.442864 +iteration 450 +cutting plane objective: 41.744915, primal objective 49.775659 +iteration 451 +cutting plane objective: 41.767760, primal objective 48.555874 +iteration 452 +cutting plane objective: 41.800355, primal objective 48.567181 +iteration 453 +cutting plane objective: 41.830157, primal objective 48.108429 +iteration 454 +cutting plane objective: 41.860966, primal objective 47.891200 +iteration 455 +cutting plane objective: 41.881486, primal objective 48.410518 +iteration 456 +cutting plane objective: 41.903566, primal objective 48.465374 +iteration 457 +cutting plane objective: 41.927494, primal objective 47.537310 +iteration 458 +cutting plane objective: 41.952757, primal objective 47.963777 +iteration 459 +cutting plane objective: 41.980442, primal objective 48.113021 +iteration 460 +cutting plane objective: 41.996905, primal objective 48.025304 +iteration 461 +cutting plane objective: 42.025225, primal objective 47.569929 +iteration 462 +cutting plane objective: 42.044505, primal objective 47.512155 +iteration 463 +cutting plane objective: 42.064035, primal objective 47.448036 +iteration 464 +cutting plane objective: 42.084959, primal objective 46.845952 +iteration 465 +cutting plane objective: 42.100841, primal objective 47.224497 +iteration 466 +cutting plane objective: 42.116083, primal objective 47.052681 +iteration 467 +cutting plane objective: 42.132631, primal objective 46.514931 +iteration 468 +cutting plane objective: 42.145579, primal objective 46.840112 +iteration 469 +cutting plane objective: 42.163848, primal objective 46.682447 +iteration 470 +cutting plane objective: 42.179220, primal objective 46.583182 +iteration 471 +cutting plane objective: 42.192965, primal objective 46.752422 +iteration 472 +cutting plane objective: 42.205050, primal objective 46.690550 +iteration 473 +cutting plane objective: 42.217534, primal objective 46.582640 +iteration 474 +cutting plane objective: 42.227564, primal objective 46.342950 +iteration 475 +cutting plane objective: 42.241381, primal objective 46.026060 +iteration 476 +cutting plane objective: 42.312613, primal objective 55.306993 +iteration 477 +cutting plane objective: 42.361664, primal objective 51.641100 +iteration 478 +cutting plane objective: 42.425387, primal objective 49.840399 +iteration 479 +cutting plane objective: 42.470515, primal objective 49.693245 +iteration 480 +cutting plane objective: 42.513243, primal objective 50.136865 +iteration 481 +cutting plane objective: 42.555074, primal objective 50.914155 +iteration 482 +cutting plane objective: 42.592809, primal objective 49.228776 +iteration 483 +cutting plane objective: 42.631904, primal objective 49.165645 +iteration 484 +cutting plane objective: 42.670521, primal objective 48.968778 +iteration 485 +cutting plane objective: 42.698786, primal objective 49.238600 +iteration 486 +cutting plane objective: 42.721514, primal objective 48.725163 +iteration 487 +cutting plane objective: 42.745387, primal objective 48.035692 +iteration 488 +cutting plane objective: 42.775211, primal objective 48.432481 +iteration 489 +cutting plane objective: 42.801522, primal objective 48.370978 +iteration 490 +cutting plane objective: 42.824307, primal objective 48.124140 +iteration 491 +cutting plane objective: 42.844942, primal objective 48.363060 +iteration 492 +cutting plane objective: 42.863712, primal objective 47.864942 +iteration 493 +cutting plane objective: 42.887789, primal objective 47.647711 +iteration 494 +cutting plane objective: 42.910830, primal objective 47.773211 +iteration 495 +cutting plane objective: 42.931775, primal objective 47.918808 +iteration 496 +cutting plane objective: 42.951648, primal objective 47.806290 +iteration 497 +cutting plane objective: 42.972117, primal objective 47.514832 +iteration 498 +cutting plane objective: 42.992297, primal objective 47.612411 +iteration 499 +cutting plane objective: 43.010329, primal objective 47.234518 +iteration 500 +cutting plane objective: 43.025491, primal objective 47.310092 +iteration 501 +cutting plane objective: 43.037983, primal objective 47.098889 +iteration 502 +cutting plane objective: 43.049242, primal objective 47.304889 +iteration 503 +cutting plane objective: 43.061689, primal objective 46.723948 +iteration 504 +cutting plane objective: 43.075889, primal objective 47.050410 +iteration 505 +cutting plane objective: 43.089906, primal objective 47.480244 +iteration 506 +cutting plane objective: 43.100336, primal objective 46.807853 +iteration 507 +cutting plane objective: 43.108938, primal objective 46.767303 +iteration 508 +cutting plane objective: 43.121109, primal objective 46.369990 +iteration 509 +cutting plane objective: 43.130531, primal objective 46.530540 +iteration 510 +cutting plane objective: 43.141865, primal objective 46.419028 +iteration 511 +cutting plane objective: 43.154182, primal objective 46.617030 +iteration 512 +cutting plane objective: 43.164501, primal objective 46.558451 +iteration 513 +cutting plane objective: 43.174198, primal objective 46.807876 +iteration 514 +cutting plane objective: 43.183043, primal objective 46.260739 +iteration 515 +cutting plane objective: 43.223603, primal objective 52.834861 +iteration 516 +cutting plane objective: 43.273979, primal objective 50.375055 +iteration 517 +cutting plane objective: 43.311721, primal objective 50.707909 +iteration 518 +cutting plane objective: 43.352673, primal objective 49.640318 +iteration 519 +cutting plane objective: 43.384107, primal objective 49.918813 +iteration 520 +cutting plane objective: 43.416465, primal objective 49.274893 +iteration 521 +cutting plane objective: 43.452441, primal objective 49.272775 +iteration 522 +cutting plane objective: 43.481801, primal objective 49.240485 +iteration 523 +cutting plane objective: 43.505703, primal objective 49.058759 +iteration 524 +cutting plane objective: 43.530733, primal objective 48.450409 +iteration 525 +cutting plane objective: 43.547577, primal objective 49.038355 +iteration 526 +cutting plane objective: 43.575319, primal objective 48.581374 +iteration 527 +cutting plane objective: 43.595171, primal objective 48.054213 +iteration 528 +cutting plane objective: 43.607938, primal objective 47.912996 +iteration 529 +cutting plane objective: 43.626134, primal objective 47.450004 +iteration 530 +cutting plane objective: 43.646514, primal objective 47.995381 +iteration 531 +cutting plane objective: 43.667569, primal objective 48.085065 +iteration 532 +cutting plane objective: 43.686676, primal objective 48.007830 +iteration 533 +cutting plane objective: 43.712646, primal objective 48.249849 +iteration 534 +cutting plane objective: 43.730066, primal objective 48.326927 +iteration 535 +cutting plane objective: 43.745561, primal objective 47.714256 +iteration 536 +cutting plane objective: 43.758292, primal objective 47.529434 +iteration 537 +cutting plane objective: 43.771064, primal objective 47.570419 +iteration 538 +cutting plane objective: 43.785719, primal objective 47.435847 +iteration 539 +cutting plane objective: 43.798947, primal objective 47.243962 +iteration 540 +cutting plane objective: 43.810558, primal objective 47.571412 +iteration 541 +cutting plane objective: 43.823964, primal objective 47.598628 +iteration 542 +cutting plane objective: 43.834684, primal objective 47.086703 +iteration 543 +cutting plane objective: 43.847696, primal objective 47.442380 +iteration 544 +cutting plane objective: 43.857997, primal objective 46.727770 +iteration 545 +cutting plane objective: 43.865595, primal objective 46.705302 +iteration 546 +cutting plane objective: 43.872454, primal objective 47.118972 +iteration 547 +cutting plane objective: 43.880550, primal objective 46.706461 +iteration 548 +cutting plane objective: 43.884495, primal objective 46.795411 +iteration 549 +cutting plane objective: 43.893036, primal objective 46.387726 +iteration 550 +cutting plane objective: 43.901140, primal objective 46.835442 +iteration 551 +cutting plane objective: 43.909026, primal objective 46.766550 +iteration 552 +cutting plane objective: 43.917524, primal objective 46.662896 +iteration 553 +cutting plane objective: 43.927945, primal objective 46.469632 +iteration 554 +cutting plane objective: 43.936893, primal objective 46.422914 +iteration 555 +cutting plane objective: 43.944849, primal objective 46.635197 +iteration 556 +cutting plane objective: 43.951799, primal objective 46.530667 +iteration 557 +cutting plane objective: 43.960817, primal objective 46.385541 +iteration 558 +cutting plane objective: 43.968528, primal objective 46.625885 +iteration 559 +cutting plane objective: 43.973768, primal objective 46.288062 +iteration 560 +cutting plane objective: 43.993339, primal objective 52.113207 +iteration 561 +cutting plane objective: 44.025552, primal objective 49.554422 +iteration 562 +cutting plane objective: 44.051588, primal objective 49.119559 +iteration 563 +cutting plane objective: 44.077695, primal objective 49.130734 +iteration 564 +cutting plane objective: 44.102586, primal objective 48.926756 +iteration 565 +cutting plane objective: 44.115489, primal objective 48.387668 +iteration 566 +cutting plane objective: 44.128857, primal objective 48.022978 +iteration 567 +cutting plane objective: 44.142789, primal objective 47.998367 +iteration 568 +cutting plane objective: 44.157361, primal objective 47.559019 +iteration 569 +cutting plane objective: 44.172283, primal objective 48.233456 +iteration 570 +cutting plane objective: 44.184643, primal objective 48.208925 +iteration 571 +cutting plane objective: 44.196357, primal objective 47.906139 +iteration 572 +cutting plane objective: 44.212569, primal objective 48.087980 +iteration 573 +cutting plane objective: 44.223039, primal objective 47.721440 +iteration 574 +cutting plane objective: 44.233750, primal objective 47.686926 +iteration 575 +cutting plane objective: 44.248568, primal objective 47.455357 +iteration 576 +cutting plane objective: 44.261516, primal objective 47.728046 +iteration 577 +cutting plane objective: 44.272153, primal objective 47.088333 +iteration 578 +cutting plane objective: 44.283592, primal objective 47.423833 +iteration 579 +cutting plane objective: 44.294738, primal objective 47.352999 +iteration 580 +cutting plane objective: 44.304950, primal objective 47.232698 +iteration 581 +cutting plane objective: 44.313504, primal objective 47.240919 +iteration 582 +cutting plane objective: 44.323404, primal objective 47.267722 +iteration 583 +cutting plane objective: 44.332864, primal objective 47.208191 +iteration 584 +cutting plane objective: 44.341748, primal objective 47.153929 +iteration 585 +cutting plane objective: 44.348483, primal objective 46.898137 +iteration 586 +cutting plane objective: 44.354968, primal objective 47.082592 +iteration 587 +cutting plane objective: 44.360294, primal objective 46.801816 +iteration 588 +cutting plane objective: 44.366586, primal objective 46.988810 +iteration 589 +cutting plane objective: 44.372775, primal objective 46.582295 +iteration 590 +cutting plane objective: 44.378990, primal objective 46.541389 +iteration 591 +cutting plane objective: 44.383805, primal objective 46.531858 +iteration 592 +cutting plane objective: 44.389199, primal objective 46.523805 +iteration 593 +cutting plane objective: 44.394177, primal objective 46.528430 +iteration 594 +cutting plane objective: 44.400049, primal objective 46.440173 +iteration 595 +cutting plane objective: 44.404562, primal objective 46.548270 +iteration 596 +cutting plane objective: 44.408784, primal objective 46.470540 +iteration 597 +new constraint too weak. +cutting plane objective: 44.439824, primal objective 49.378301 +iteration 598 +cutting plane objective: 44.465954, primal objective 48.777049 +iteration 599 +cutting plane objective: 44.485542, primal objective 48.678252 +iteration 600 +cutting plane objective: 44.504180, primal objective 48.610474 +iteration 601 +cutting plane objective: 44.524295, primal objective 48.249795 +iteration 602 +cutting plane objective: 44.542621, primal objective 48.091666 +iteration 603 +cutting plane objective: 44.557350, primal objective 47.969619 +iteration 604 +cutting plane objective: 44.568825, primal objective 48.322974 +iteration 605 +cutting plane objective: 44.583878, primal objective 47.837242 +iteration 606 +cutting plane objective: 44.598342, primal objective 47.607253 +iteration 607 +cutting plane objective: 44.605554, primal objective 48.060459 +iteration 608 +cutting plane objective: 44.617795, primal objective 47.753131 +iteration 609 +cutting plane objective: 44.625449, primal objective 47.354934 +iteration 610 +cutting plane objective: 44.632955, primal objective 47.320574 +iteration 611 +cutting plane objective: 44.640633, primal objective 47.440613 +iteration 612 +cutting plane objective: 44.649716, primal objective 47.495059 +iteration 613 +cutting plane objective: 44.659672, primal objective 47.470130 +iteration 614 +cutting plane objective: 44.666983, primal objective 47.241963 +iteration 615 +cutting plane objective: 44.676545, primal objective 47.058892 +iteration 616 +cutting plane objective: 44.685557, primal objective 47.285583 +iteration 617 +cutting plane objective: 44.693247, primal objective 47.287941 +iteration 618 +cutting plane objective: 44.701508, primal objective 47.030915 +iteration 619 +cutting plane objective: 44.707170, primal objective 47.163261 +iteration 620 +cutting plane objective: 44.713266, primal objective 46.969104 +iteration 621 +cutting plane objective: 44.719528, primal objective 46.832278 +iteration 622 +cutting plane objective: 44.725387, primal objective 46.922858 +iteration 623 +cutting plane objective: 44.730540, primal objective 46.786663 +iteration 624 +cutting plane objective: 44.736461, primal objective 46.825526 +iteration 625 +new constraint too weak. +cutting plane objective: 44.752083, primal objective 48.774799 +iteration 626 +cutting plane objective: 44.769423, primal objective 47.997275 +iteration 627 +cutting plane objective: 44.781747, primal objective 48.072543 +iteration 628 +cutting plane objective: 44.792405, primal objective 48.082034 +iteration 629 +cutting plane objective: 44.800988, primal objective 47.803370 +iteration 630 +cutting plane objective: 44.809933, primal objective 47.634412 +iteration 631 +cutting plane objective: 44.818328, primal objective 47.418097 +iteration 632 +cutting plane objective: 44.828383, primal objective 47.606751 +iteration 633 +cutting plane objective: 44.836258, primal objective 47.652823 +iteration 634 +cutting plane objective: 44.844533, primal objective 47.365089 +iteration 635 +cutting plane objective: 44.853619, primal objective 47.478129 +iteration 636 +cutting plane objective: 44.861697, primal objective 47.460959 +iteration 637 +cutting plane objective: 44.868637, primal objective 47.316038 +iteration 638 +cutting plane objective: 44.874854, primal objective 47.381950 +iteration 639 +cutting plane objective: 44.880335, primal objective 47.204120 +iteration 640 +cutting plane objective: 44.885732, primal objective 47.162493 +iteration 641 +cutting plane objective: 44.891993, primal objective 47.156626 +iteration 642 +cutting plane objective: 44.899067, primal objective 47.096594 +iteration 643 +cutting plane objective: 44.903889, primal objective 47.100602 +iteration 644 +cutting plane objective: 44.909042, primal objective 47.210688 +iteration 645 +cutting plane objective: 44.915139, primal objective 46.956284 +iteration 646 +new constraint too weak. +cutting plane objective: 44.926472, primal objective 48.027930 +iteration 647 +cutting plane objective: 44.936515, primal objective 47.775455 +iteration 648 +cutting plane objective: 44.946557, primal objective 47.596100 +iteration 649 +cutting plane objective: 44.952651, primal objective 47.689936 +iteration 650 +cutting plane objective: 44.961395, primal objective 47.532969 +iteration 651 +cutting plane objective: 44.968138, primal objective 47.631642 +iteration 652 +cutting plane objective: 44.975903, primal objective 47.541158 +iteration 653 +cutting plane objective: 44.982206, primal objective 47.445009 +iteration 654 +cutting plane objective: 44.990649, primal objective 47.330042 +iteration 655 +cutting plane objective: 44.998674, primal objective 47.453943 +iteration 656 +cutting plane objective: 45.003591, primal objective 47.411593 +iteration 657 +cutting plane objective: 45.010570, primal objective 47.479892 +iteration 658 +cutting plane objective: 45.016379, primal objective 47.154594 +iteration 659 +cutting plane objective: 45.021874, primal objective 47.108300 +iteration 660 +cutting plane objective: 45.027322, primal objective 47.188755 +iteration 661 +new constraint too weak. +cutting plane objective: 45.036116, primal objective 47.617069 +iteration 662 +cutting plane objective: 45.043593, primal objective 47.304272 +iteration 663 +cutting plane objective: 45.051923, primal objective 47.455887 +iteration 664 +cutting plane objective: 45.059136, primal objective 47.647937 +iteration 665 +cutting plane objective: 45.065383, primal objective 47.422196 +iteration 666 +cutting plane objective: 45.071971, primal objective 47.212878 +iteration 667 +cutting plane objective: 45.077455, primal objective 47.131600 +iteration 668 +cutting plane objective: 45.084012, primal objective 47.224766 +iteration 669 +cutting plane objective: 45.089605, primal objective 47.136758 +iteration 670 +cutting plane objective: 45.095178, primal objective 47.146985 +iteration 671 +cutting plane objective: 45.100633, primal objective 47.098961 +iteration 672 +new constraint too weak. +cutting plane objective: 45.107283, primal objective 47.520703 +iteration 673 +cutting plane objective: 45.114744, primal objective 47.407076 +iteration 674 +cutting plane objective: 45.121579, primal objective 47.343884 +iteration 675 +cutting plane objective: 45.128382, primal objective 47.341440 +iteration 676 +cutting plane objective: 45.132699, primal objective 47.271365 +iteration 677 +new constraint too weak. +cutting plane objective: 45.140261, primal objective 47.569480 +iteration 678 +cutting plane objective: 45.147898, primal objective 47.665761 +iteration 679 +cutting plane objective: 45.157485, primal objective 47.479075 +iteration 680 +cutting plane objective: 45.165177, primal objective 47.632770 +iteration 681 +cutting plane objective: 45.172476, primal objective 47.618447 +iteration 682 +cutting plane objective: 45.180181, primal objective 47.720736 +iteration 683 +cutting plane objective: 45.188574, primal objective 47.561174 +iteration 684 +cutting plane objective: 45.197416, primal objective 47.773228 +iteration 685 +cutting plane objective: 45.205932, primal objective 47.471479 +iteration 686 +cutting plane objective: 45.213801, primal objective 47.935943 +iteration 687 +cutting plane objective: 45.222835, primal objective 47.769860 +iteration 688 +cutting plane objective: 45.230366, primal objective 47.583348 +iteration 689 +cutting plane objective: 45.237364, primal objective 47.766477 +iteration 690 +cutting plane objective: 45.244965, primal objective 47.582993 +iteration 691 +cutting plane objective: 45.251357, primal objective 47.698541 +iteration 692 +cutting plane objective: 45.258899, primal objective 47.520509 +iteration 693 +cutting plane objective: 45.267206, primal objective 47.326435 +iteration 694 +cutting plane objective: 45.274819, primal objective 47.748319 +iteration 695 +cutting plane objective: 45.282694, primal objective 47.733576 +iteration 696 +cutting plane objective: 45.288299, primal objective 47.558968 +iteration 697 +cutting plane objective: 45.295173, primal objective 47.373888 +iteration 698 +new constraint too weak. +cutting plane objective: 45.301986, primal objective 47.565159 +iteration 699 +cutting plane objective: 45.308397, primal objective 47.657055 +iteration 700 +cutting plane objective: 45.316628, primal objective 47.775878 +iteration 701 +cutting plane objective: 45.326118, primal objective 47.540368 +iteration 702 +cutting plane objective: 45.331291, primal objective 47.741623 +iteration 703 +cutting plane objective: 45.338424, primal objective 47.530808 +iteration 704 +cutting plane objective: 45.343557, primal objective 47.662534 +iteration 705 +cutting plane objective: 45.349114, primal objective 47.360803 +iteration 706 +cutting plane objective: 45.355668, primal objective 47.373585 +iteration 707 +cutting plane objective: 45.361184, primal objective 47.398588 +iteration 708 +cutting plane objective: 45.367670, primal objective 47.382663 +iteration 709 +cutting plane objective: 45.374293, primal objective 47.371971 +iteration 710 +cutting plane objective: 45.379615, primal objective 47.520312 +iteration 711 +cutting plane objective: 45.384749, primal objective 47.428997 +iteration 712 +new constraint too weak. +cutting plane objective: 45.389687, primal objective 47.520781 +iteration 713 +new constraint too weak. +new constraint too weak. +no additional constraints +final primal objective: 47.218747 gap: 1.829060 +Results using also input features for edges +Test accuracy: 0.996 +[[2749 0 0 0 0 0 0 0 1 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 100 0 0 0 0 0 0 0] + [ 0 0 0 0 98 0 1 0 1 0 0] + [ 0 0 0 2 0 98 0 0 0 0 0] + [ 0 0 0 0 2 0 98 0 0 0 0] + [ 0 1 0 0 0 2 0 97 0 0 0] + [ 0 0 1 0 0 0 1 0 98 0 0] + [ 0 0 0 1 0 0 0 0 0 99 0] + [ 0 0 0 0 1 0 0 0 0 0 99]] From e18e0f1ad698d436eaabb2beeea1a0bb0bf94cb2 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 6 Feb 2017 12:14:10 +0100 Subject: [PATCH 031/155] no change, why is this file tagged as changed?? --- examples/plot_hidden_snakes.py | 624 +++++++++------------------------ 1 file changed, 161 insertions(+), 463 deletions(-) diff --git a/examples/plot_hidden_snakes.py b/examples/plot_hidden_snakes.py index c9eef953..ea1b05c5 100644 --- a/examples/plot_hidden_snakes.py +++ b/examples/plot_hidden_snakes.py @@ -5,11 +5,15 @@ This is a variant of plot_snakes.py -Snake are hidding, so another task is both to determine if a snake is in the picture, and -identify its head to tail body. - -We use the NodeTypeEdgeFeatureGraphCRF class with 2 type of nodes. +Snake are hiding!! Therefore, some picture have colored pixels despite they do not contain any snake. + JL Meunier - January 2017 + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943 + + Copyright Xerox This example uses the snake dataset introduced in Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 @@ -48,79 +52,55 @@ from pystruct.learners import OneSlackSSVM from pystruct.datasets import load_snakes -from pystruct.utils import make_grid_edges, edge_list_to_features -#from pystruct.models import EdgeFeatureGraphCRF +from pystruct.models import EdgeFeatureGraphCRF from pystruct.models import NodeTypeEdgeFeatureGraphCRF -from plot_snakes import one_hot_colors, neighborhood_feature, prepare_data +from plot_snakes import one_hot_colors, prepare_data -def isSnakePresent(a_hot_picture): - """ - Algorithmic check, to make sure that after shuffling we do not have a snake! :-) - work on the 1-hot encoded picture - """ - try: - ai, aj = np.where(a_hot_picture[...,3] != 1) - if len(ai) != 10: return False - lij = zip(ai, aj) - for n in range(10): - _lij = shiftSnake(a_hot_picture, lij) - if len(_lij) != len(lij)-1: return False - lij = _lij - if len(_lij) != 0: return False - return True - except: - return False - -def shiftSnake(a_hot_picture, lij): - #the snake moves by one cell, head disappearing in sand - _lij = list() - for i,j in lij: - color_index = np.where(a_hot_picture[i,j,:]==1)[0][0] - dj = np.array( [ 0, 0, 1, None, -1])[color_index] - di = np.array( [-1, 1, 0, None, 0])[color_index] - i,j = i+di,j+dj - if a_hot_picture[i,j,3] != 1: #backgroun - _lij.append((i,j)) - return _lij -def shufflePictureCells(a_picture): #in place!! - """ - Shuffle the pixels - """ - n = random.randint(1,4) - if n == 1: - map(np.random.shuffle, a_picture) - elif n == 2: - map(np.random.shuffle, np.transpose(a_picture, (1,0,2))) - else: - map(np.random.shuffle, a_picture) - map(np.random.shuffle, np.transpose(a_picture, (1,0,2))) - - return a_picture +if True: + np.random.seed(1605) + random.seed(98) -def shuffleSnakeCells(a_picture, bOneHot=True): #in place!! +def isSnakePresent(a_hot_picture, nCell=10): """ - Shuffle the colors of the 10 snake cells + Algorithmic check, to make sure that after tempering with the snake we do not have a snake! :-) + Works on the 1-hot encoded picture """ - if bOneHot: - ai, aj = np.where(a_picture[...,3] != 1) - else: - _p = np.copy(a_picture) - _p = one_hot_colors(_p) - ai, aj = np.where(_p[...,3] != 1) - assert len(ai) == 10 + ai, aj = np.where(a_hot_picture[...,3] != 1) - l_shuffled_aij = zip(ai,aj) - random.shuffle( l_shuffled_aij ) - _ai, _aj = zip(*l_shuffled_aij) + #let's start from each cell until we can walk thru an entire snake + #yeah, brute force, but otherwise it is tricky to check!! + bSnake = False + for i0,j0 in zip(ai,aj): + + lij = walkThruSnake(a_hot_picture, (i0, j0), nCell) + if len(lij) == nCell-1: + bSnake = True + break + return bSnake + +def walkThruSnake(a_hot_picture, (i,j), nCell=10): + """ + Walk thru the snake from I,J + Return the list of visited cells (excluding start cell) + """ + lij = list() + color_index = np.where(a_hot_picture[i,j,:]==1)[0][0] + while len(lij) < nCell -1: + dj = np.array( [ 0, 0, 1, None, -1])[color_index] + di = np.array( [-1, 1, 0, None, 0])[color_index] + i += di + j += dj + color_index = np.where(a_hot_picture[i,j,:]==1)[0][0] + if color_index == 3: break #background + if (i,j) in lij: break #crossing itself, or looping + lij.append((i,j)) + return lij - a_picture[_ai,_aj,:] = a_picture[ai,aj,:] - return a_picture - def changeOneSnakeCell(a_picture, bOneHot=True, nCell=10): #in place!! """ - Change the color of 1 snake cells + Change the color of 1 snake cells into another snake cell color """ if bOneHot: ai, aj = np.where(a_picture[...,3] != 1) @@ -141,74 +121,69 @@ def changeOneSnakeCell(a_picture, bOneHot=True, nCell=10): #in place!! return a_picture -def eraseOneSnakeCell(a_picture, bOneHot=True): #in place!! +def distortSnake(a_picture, bOneHot=True, nCell=10): """ - Change the color of 1 snake cells + Shuffle either the snake's cells or the pcitures' pixels. """ - if bOneHot: - ai, aj = np.where(a_picture[...,3] != 1) - else: - _p = np.copy(a_picture) - _p = one_hot_colors(_p) - ai, aj = np.where(_p[...,3] != 1) - assert len(ai) == 10 + bDOCUMENT = False #to show the change on screen - iChange = random.randint(0,9) + if bDOCUMENT: + pict_mem = np.copy(a_picture) - #a_picture[ai[iChange], aj[iChange]] = a_picture[0,0] #by construction it is background - - return a_picture - - -def shuffleSnake(a_picture, bOneHot=True, nCell=10): - """ - Shuffle either the snake's cells or the pcitures' pixels. - """ - if False: - eraseOneSnakeCell(a_picture, bOneHot) - elif True: - changeOneSnakeCell(a_picture, bOneHot, nCell=nCell) - else: - if random.randint(0,1): - shuffleSnakeCells(a_picture, bOneHot) + changeOneSnakeCell(a_picture, bOneHot, nCell=nCell) + + if bDOCUMENT: + if bOneHot: + zz = a_picture else: - shufflePictureCells(a_picture) + zz = one_hot_colors(a_picture) + if not isSnakePresent(zz, nCell): + plot_snake(pict_mem) + plot_snake(a_picture) def convertToSingleTypeX(X): """ For NodeTypeEdgeFeatureGraphCRF X is structured differently. - But NodeTypeEdgeFeatureGraphCRF can handle graph with a single node type. One needs to convert X to the new structure using this method. + But NodeTypeEdgeFeatureGraphCRF can handle graphs with a single node type. One simply needs to convert X to the new structure using this method. """ return [([nf], [e], [ef]) for (nf,e,ef) in X] + def plot_snake(picture): plt.imshow(picture, interpolation='nearest') plt.show() + def augmentWithNoSnakeImages(X,Y, name, bOneHot=True, iMult=1, nCell=10): """ - return the number of added picture (AT THE END OF INPUT LISTS) + return the number of added picture (ADDED AT THE END OF INPUT LISTS) """ print "ADDING PICTURE WIHOUT SNAKES!!! %d elements in %s"%(len(X), name) X_NoSnake = [] + Y_NoSnake = [] for i in range(int(iMult)): X_NoSnake.extend([np.copy(x) for x in X]) + Y_NoSnake.extend([np.copy(y) for y in Y]) #shorten_sakes does modify Y... - for x in X_NoSnake: shuffleSnake(x, bOneHot, nCell) - #map(shufflePictureCells, X_NoSnake) + if True: + #best method for our experiment + for x in X_NoSnake: distortSnake(x, bOneHot, nCell) + else: + shorten_snakes(X_NoSnake, Y_NoSnake, nCell-1) newX = list() - Y_NoSnake = list() - for x,y in zip(X_NoSnake, Y): - if isSnakePresent(x): + newY = list() + for x,y in zip(X_NoSnake, Y_NoSnake): + _x = x if bOneHot else one_hot_colors(x) + if isSnakePresent(_x): print "\t- DISCARDING a shuffled snake which is still a snake!!!!" +# if True and not bOneHot: plot_snake(x) else: newX.append(x) - Y_NoSnake.append(np.zeros(y.shape, dtype=np.int32)) - X_NoSnake = newX - assert len(X_NoSnake)==len(Y_NoSnake) - return len(X_NoSnake), X+X_NoSnake, Y+Y_NoSnake + newY.append(np.zeros(y.shape, dtype=np.int32)) + assert len(newX)==len(newY) + return len(newX), X+newX, Y+newY def shuffle_in_unison(*args): lTuple = zip(*args) @@ -216,6 +191,9 @@ def shuffle_in_unison(*args): return zip(*lTuple) def shorten_snakes(lX,lY, N): + """ + It is faster to work on shorter snakes, but easier as well for the models + """ newlX,newlY = list(), list() for X, Y in zip(lX,lY): assert X.shape[:2] == Y.shape, (X.shape, Y.shape) @@ -231,394 +209,114 @@ def shorten_snakes(lX,lY, N): return newlX, newlY - +#===================================================================================================== if __name__ == '__main__': print("Please be patient. Learning will take 5-20 minutes.") - NCELL = 5 + #if you want to shorten all the snakes + #NCELL = 3 + NCELL = 10 print "NCELL=", NCELL - snakes = load_snakes() - X_train, Y_train = snakes['X_train'], snakes['Y_train'] - - #X_train, Y_train = X_train[:10], Y_train[:10] - bSHUFFLE = True - - bADD_HIDDEN_SNAKES = True - #bADD_HIDDEN_SNAKES = False - #JL - #X_train, Y_train = X_train[:10], Y_train[:10] - print len(X_train), len(Y_train) - #print `X_train[0]` - X_train, Y_train = shorten_snakes(X_train, Y_train, NCELL) - - if bADD_HIDDEN_SNAKES: - _, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False, nCell=NCELL) - print len(X_train), len(Y_train) - - if False: - #show the faked pictures - for ix, x in enumerate(X_train): plot_snake(shufflePictureCells(x)) - - X_train_hot = [one_hot_colors(x) for x in X_train] - - if False: - for ix, x in enumerate(X_train_hot): - if not isSnakePresent(x): plot_snake(X_train[ix]) - - X_train = X_train_hot + snakes = load_snakes() - if bSHUFFLE: - #let's shuffle our data - X_train, Y_train = shuffle_in_unison(X_train, Y_train) + # --- TRAIN + X_train, Y_train = snakes['X_train'], snakes['Y_train'] + #X_train, Y_train = X_train[:10], Y_train[:10] #if you want to debug... + if NCELL < 10: X_train, Y_train = shorten_snakes(X_train, Y_train, NCELL) - # ------------------------------------------------------------------------------------- + nbNoSnake, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", bOneHot=False, nCell=NCELL) + X_train = [one_hot_colors(x) for x in X_train] + X_train, Y_train = shuffle_in_unison(X_train, Y_train) X_train_directions, X_train_edge_features = prepare_data(X_train) - Y_train_flat = [y_.ravel() for y_ in Y_train] - inference = 'qpbo' - # first, train on X with directions only: - #CHANGE!! - #We require NodeTypeEdgeFeatureGraphCRF - #crf = NodeTypeEdgeFeatureGraphCRF(inference_method=inference) - crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[2]], inference_method=inference) - XX = convertToSingleTypeX(X_train_directions) - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, - max_iter=100, - n_jobs=1) - print len(XX), len(Y_train), len(Y_train_flat) - ssvm.fit(XX, Y_train_flat) - - # Evaluate using confusion matrix. - # Clearly the middel of the snake is the hardest part. + print "%d picture for training"%len(X_train) + + # --- TEST X_test, Y_test = snakes['X_test'], snakes['Y_test'] - X_test, Y_test = shorten_snakes(X_test, Y_test, NCELL) - - print "TEST len=", len(X_test) - if bADD_HIDDEN_SNAKES: - _, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", bOneHot=False, nCell=NCELL) - print "TEST len=", len(X_test) + if NCELL < 10: X_test, Y_test = shorten_snakes(X_test, Y_test, NCELL) + _, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", bOneHot=False, nCell=NCELL) X_test = [one_hot_colors(x) for x in X_test] - Y_test_flat = [y_.ravel() for y_ in Y_test] X_test_directions, X_test_edge_features = prepare_data(X_test) - Y_pred = ssvm.predict( convertToSingleTypeX(X_test_directions) ) - print("Results using only directional features for edges") - print("Test accuracy: %.3f" - % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) - print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) - + Y_test_flat = [y_.ravel() for y_ in Y_test] + + print "%d picture for test"%len(X_test) + + # ------------------------------------------------------------------------------------- + + inference = 'qpbo' + bClassic = True #True => use the old good EdgeFeatureGraphCRF + # now, use more informative edge features: - crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]], inference_method=inference) - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + t0 = time.time() + if bClassic: + print "EdgeFeatureGraphCRF" + crf = EdgeFeatureGraphCRF(inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + #WHY THIS??? max_iter=100, + #why not this switch_to=ad3??? + switch_to='ad3', + #verbose=1, + n_jobs=2, + ) + ssvm.fit( X_train_edge_features , Y_train_flat) + else: + print "NodeTypeEdgeFeatureGraphCRF" + crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]], inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', #JL adds a max-iter sometimes #max_iter=100, n_jobs=1) - t0 = time.time() - ssvm.fit( convertToSingleTypeX(X_train_edge_features) , Y_train_flat) + ssvm.fit( convertToSingleTypeX(X_train_edge_features) , Y_train_flat) print "Training time = %.1fs"%(time.time()-t0) - Y_pred2 = ssvm.predict( convertToSingleTypeX(X_test_edge_features) ) - print("Results using also input features for edges") + if bClassic: + Y_pred2 = ssvm.predict( X_test_edge_features ) + else: + Y_pred2 = ssvm.predict( convertToSingleTypeX(X_test_edge_features) ) + print("Results using input features for edges") print("Test accuracy: %.3f" % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) - if False: - # plot stuff - fig, axes = plt.subplots(2, 2) - axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') - axes[0, 0].set_title('Input') - y = Y_test[0].astype(np.int) - bg = 2 * (y != 0) # enhance contrast - axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) - axes[0, 1].set_title("Ground Truth") - axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 0].set_title("Prediction w/o edge features") - axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 1].set_title("Prediction with edge features") - for a in axes.ravel(): - a.set_xticks(()) - a.set_yticks(()) - plt.show() - + #------------------------------------------------------------------------------------------------------------------------ + #Predict under constraints + if True and not bClassic: + def buildConstraintsFromSingleTyped(X, bOne=True): + """ + We iterate over each graph, and make sure that for each, we constrain to have a single instances of classes 1 to 9 + (or atmost one) + + The constraints must be a list of tuples like ( , , , ) + where: + - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - unaries is a list of the index of the unaries involved in this constraint + - states is a list of unary states, 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. + - negated is a list of boolean indicated if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list + """ + sLogicOp = "XOR" if bOne else "ATMOSTONE" + lConstraint = [] + for ([nf], [e], [ef]) in X: + n_nodes = nf.shape[0] + lConstraintPerGraph = [ (sLogicOp, range(n_nodes), i, False) for i in range(1,NCELL+1) ] #only one + lConstraint.append( lConstraintPerGraph ) + return lConstraint + + X_3 = convertToSingleTypeX(X_test_edge_features) + lC = buildConstraintsFromSingleTyped(X_3, False) + Y_pred2 = ssvm.predict( X_3, lC ) + print("Results using also input features for edges") + print "Inference with an ATMOST constraint per snake label" + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) """ ----------------------------------------------------------------- -ALWAYS SHUFFLING!! - -WITHOUT HIDDEN SNAKES - -Please be patient. Learning will take 5-20 minutes. -200 200 -Snakes are ok -200 200 200 -TEST len= 100 -Results using only directional features for edges -Test accuracy: 0.847 -[[2750 0 0 0 0 0 0 0 0 0 0] - [ 0 99 0 0 1 0 0 0 0 0 0] - [ 0 2 68 3 9 4 6 4 3 1 0] - [ 0 4 11 45 8 14 5 6 0 6 1] - [ 0 1 22 18 31 2 14 4 3 5 0] - [ 0 3 7 38 12 22 5 4 2 7 0] - [ 0 2 19 16 26 8 16 2 9 2 0] - [ 0 6 14 26 10 15 5 12 2 10 0] - [ 0 0 12 15 16 4 16 2 18 4 13] - [ 0 2 5 18 6 8 5 3 2 50 1] - [ 0 1 11 4 13 1 2 0 2 2 64]] -Training time = 37.5s -Results using also input features for edges -Test accuracy: 0.907 -[[2749 0 0 0 0 0 0 0 1 0 0] - [ 0 99 0 1 0 0 0 0 0 0 0] - [ 0 0 98 0 1 0 0 1 0 0 0] - [ 0 9 2 79 1 6 0 2 1 0 0] - [ 0 1 38 4 38 0 15 2 2 0 0] - [ 1 5 3 41 2 30 1 13 1 3 0] - [ 1 0 17 7 12 1 44 1 15 0 2] - [ 1 3 1 19 5 7 2 52 2 8 0] - [ 0 2 10 1 9 2 4 2 63 1 6] - [ 2 0 2 14 0 5 0 3 2 71 1] - [ 1 0 2 2 12 0 5 0 1 0 77]] - - -------------------------- - switch_to='ad3', - max-iter=100 - - Results using also input features for edges -Test accuracy: 0.870 -[[2750 0 0 0 0 0 0 0 0 0 0] - [ 1 94 2 1 0 0 1 0 0 1 0] - [ 0 7 88 0 0 0 2 0 2 0 1] - [ 0 30 11 41 0 7 0 9 0 2 0] - [ 4 6 38 11 17 3 7 0 13 0 1] - [ 2 9 10 25 4 24 3 13 2 8 0] - [ 0 9 18 9 8 6 23 1 19 1 6] - [ 2 9 9 12 6 10 4 34 2 11 1] - [ 0 8 13 3 4 3 4 1 54 2 8] - [ 10 8 6 6 1 3 1 4 2 57 2] - [ 1 3 3 4 4 0 0 0 6 0 79]] - - --------------------------- - switch_to='ad3', - without max_iter - -Results using also input features for edges -Test accuracy: 0.997 -[[2749 0 0 0 0 0 0 0 1 0 0] - [ 0 100 0 0 0 0 0 0 0 0 0] - [ 0 0 100 0 0 0 0 0 0 0 0] - [ 0 0 0 99 0 0 0 0 0 1 0] - [ 0 0 0 0 99 0 1 0 0 0 0] - [ 0 0 0 1 0 98 0 1 0 0 0] - [ 0 0 0 0 1 0 98 0 1 0 0] - [ 0 0 0 0 0 1 0 99 0 0 0] - [ 0 0 0 0 0 0 0 0 100 0 0] - [ 0 0 0 1 0 0 0 1 0 98 0] - [ 0 0 0 0 1 0 0 0 0 0 99]] - ----------------------------------------------------------------- - -SHUFFLING EITHER PIXELS OR SNAKE CELLS - -Please be patient. Learning will take 5-20 minutes. -200 200 -ADDING PICTURE WIHOUT SNAKES!!! 200 elements in train -400 400 -Snakes are ok -400 400 400 -TEST len= 100 -ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test -TEST len= 200 -Results using only directional features for edges -Test accuracy: 0.858 -[[6336 2 1 6 7 11 13 72 31 11 10] - [ 87 9 0 0 2 0 0 0 0 2 0] - [ 44 0 2 1 1 1 9 31 10 1 0] - [ 49 0 0 1 0 6 5 15 18 3 3] - [ 50 0 1 0 2 2 12 16 12 2 3] - [ 52 1 0 2 0 2 11 23 4 5 0] - [ 58 0 1 0 3 1 13 14 7 2 1] - [ 57 0 1 1 1 5 1 16 10 5 3] - [ 57 1 0 1 3 3 8 8 12 3 4] - [ 57 0 0 0 1 0 1 16 8 15 2] - [ 58 0 0 0 0 3 0 9 3 3 24]] -Training time = 44.0s -Results using also input features for edges -Test accuracy: 0.864 -[[6439 1 0 4 8 5 6 7 1 10 19] - [ 98 1 0 1 0 0 0 0 0 0 0] - [ 98 0 1 1 0 0 0 0 0 0 0] - [ 98 0 0 2 0 0 0 0 0 0 0] - [ 98 0 0 0 0 0 2 0 0 0 0] - [ 95 0 0 0 0 5 0 0 0 0 0] - [ 95 0 0 0 0 0 5 0 0 0 0] - [ 95 0 0 0 0 0 0 5 0 0 0] - [ 94 0 0 0 0 0 0 0 5 0 1] - [ 94 0 0 0 0 0 0 0 0 6 0] - [ 91 0 0 0 1 0 0 0 0 0 8]] - - - -------------------------- - switch_to='ad3', - max-iter=100 - -Training time = 34.5s -Results using also input features for edges -Test accuracy: 0.870 -[[6384 2 0 0 1 13 11 6 4 20 59] - [ 92 5 1 0 1 0 0 0 0 0 1] - [ 86 0 4 1 0 3 1 0 0 2 3] - [ 80 1 1 4 2 4 2 1 3 0 2] - [ 79 0 1 3 3 3 3 2 2 4 0] - [ 74 0 1 0 2 8 2 5 3 1 4] - [ 69 0 0 2 0 4 10 1 8 4 2] - [ 66 0 0 0 2 0 2 11 3 11 5] - [ 58 0 0 0 1 2 0 3 23 2 11] - [ 57 0 0 0 0 1 1 2 0 34 5] - [ 57 0 0 0 0 0 0 1 0 0 42]] - -------------------------- - switch_to='ad3', - without max-iter - -Training time = 1346.7s -Results using also input features for edges -Test accuracy: 0.987 -[[6437 7 8 8 4 2 1 0 7 14 12] - [ 2 97 0 0 0 1 0 0 0 0 0] - [ 2 0 97 0 1 0 0 0 0 0 0] - [ 0 0 0 97 0 2 0 1 0 0 0] - [ 0 0 1 0 96 0 2 0 1 0 0] - [ 0 0 0 2 0 95 0 3 0 0 0] - [ 0 0 1 0 2 0 94 0 3 0 0] - [ 0 0 0 1 0 3 0 93 0 3 0] - [ 0 0 1 0 1 0 1 0 97 0 0] - [ 0 0 0 0 0 1 0 1 0 98 0] - [ 0 0 0 0 0 0 1 0 1 0 98]] - - - ----------------------------------------------------------------- -CHANGING ONE CELL OF THE SNAKE - switch_to='ad3', - without max-iter - - Please be patient. Learning will take 5-20 minutes. -200 200 -ADDING PICTURE WIHOUT SNAKES!!! 200 elements in train -400 400 -Snakes are ok -400 400 400 -TEST len= 100 -ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test -TEST len= 200 -Results using only directional features for edges -Test accuracy: 0.857 -[[6355 0 0 0 4 26 0 8 1 4 102] - [ 100 0 0 0 0 0 0 0 0 0 0] - [ 91 0 0 0 0 9 0 0 0 0 0] - [ 91 0 0 0 0 0 0 0 0 0 9] - [ 99 0 0 0 0 0 0 0 0 0 1] - [ 96 0 0 0 0 1 0 1 0 0 2] - [ 97 0 0 0 1 0 0 0 1 0 1] - [ 95 0 0 0 0 4 0 1 0 0 0] - [ 86 0 0 0 2 0 0 0 1 0 11] - [ 70 0 0 0 0 13 0 3 0 7 7] - [ 34 0 0 0 0 0 0 2 0 0 64]] -Training time = 1852.6s -Results using also input features for edges -Test accuracy: 0.904 -[[6185 25 25 25 25 24 25 32 39 42 53] - [ 41 58 0 0 0 0 1 0 0 0 0] - [ 41 0 56 0 2 0 0 1 0 0 0] - [ 41 0 1 56 0 2 0 0 0 0 0] - [ 39 0 0 1 56 0 4 0 0 0 0] - [ 39 0 0 0 1 58 0 2 0 0 0] - [ 39 0 0 0 0 1 59 0 1 0 0] - [ 38 0 0 0 0 0 1 60 0 1 0] - [ 36 1 0 0 0 0 0 0 62 0 1] - [ 36 0 0 1 1 0 0 0 0 62 0] - [ 32 1 0 0 1 1 0 0 0 0 65]] - -TEST len= 100 -ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test -TEST len= 200 -Results using only directional features for edges -Test accuracy: 0.878 -[[3839 4 9 6 13 27] - [ 100 0 0 0 0 0] - [ 98 0 0 2 0 0] - [ 96 0 1 0 2 1] - [ 94 0 1 0 3 2] - [ 81 0 0 1 0 18]] -1000 inference calls -2000 inference calls -3000 inference calls -4000 inference calls -5000 inference calls -6000 inference calls -7000 inference calls -8000 inference calls -9000 inference calls -10000 inference calls -11000 inference calls -12000 inference calls -Training time = 310.7s -Results using also input features for edges -Test accuracy: 0.954 -[[3729 29 34 33 32 41] - [ 7 93 0 0 0 0] - [ 7 0 93 0 0 0] - [ 7 0 0 93 0 0] - [ 6 0 0 0 94 0] - [ 6 0 0 0 0 94]] ----------------------------------------------------------------- -CHANGING TWO CELLs OF THE SNAKE - switch_to='ad3', - without max-iter - -Please be patient. Learning will take 5-20 minutes. -200 200 -ADDING PICTURE WIHOUT SNAKES!!! 200 elements in train -400 400 -Snakes are ok -400 400 400 -TEST len= 100 -ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test -TEST len= 200 -Results using only directional features for edges -Test accuracy: 0.853 -[[6318 5 13 8 5 9 26 18 25 30 43] - [ 93 5 0 0 0 1 0 0 0 1 0] - [ 86 0 3 0 1 0 5 0 2 3 0] - [ 84 0 0 0 0 3 3 3 3 4 0] - [ 84 0 0 0 1 1 5 1 4 4 0] - [ 82 0 0 2 1 5 2 2 4 2 0] - [ 80 0 3 0 0 2 8 3 1 3 0] - [ 79 0 1 1 0 2 4 3 4 6 0] - [ 74 1 1 2 2 0 5 0 8 5 2] - [ 71 0 3 0 0 3 3 3 4 13 0] - [ 51 0 0 3 0 0 2 2 4 1 37]] -Training time = 2100.8s -Results using also input features for edges -Test accuracy: 0.941 -[[6204 26 30 29 25 26 29 23 26 35 47] - [ 11 88 0 0 0 0 1 0 0 0 0] - [ 11 0 87 0 0 1 0 1 0 0 0] - [ 10 1 1 85 0 1 1 1 0 0 0] - [ 9 0 1 1 83 1 3 0 2 0 0] - [ 9 0 0 1 1 83 1 3 0 2 0] - [ 8 0 1 0 2 2 83 0 3 0 1] - [ 8 0 0 1 0 2 2 85 0 2 0] - [ 8 0 0 0 1 0 2 1 86 0 2] - [ 8 0 0 0 0 1 0 1 1 89 0] - [ 8 0 0 0 0 0 2 0 1 1 88]] """ \ No newline at end of file From f11217997a44db550f8c41ad396f52944d24f217 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 6 Feb 2017 12:31:50 +0100 Subject: [PATCH 032/155] ok --- examples/plot_hidden_short_snakes_typed.py | 548 +++++++++++++++++++++ 1 file changed, 548 insertions(+) create mode 100644 examples/plot_hidden_short_snakes_typed.py diff --git a/examples/plot_hidden_short_snakes_typed.py b/examples/plot_hidden_short_snakes_typed.py new file mode 100644 index 00000000..f231c651 --- /dev/null +++ b/examples/plot_hidden_short_snakes_typed.py @@ -0,0 +1,548 @@ +""" +============================================== +Conditional Interactions on the Snakes Dataset +============================================== + +This is a variant of plot_snakes.py + +Snake are hidding, so we have 2 tasks: +- determining if a snake is in the picture, +- identifying its head to tail body. + +We use the NodeTypeEdgeFeatureGraphCRF class with 2 type of nodes. + + +This example uses the snake dataset introduced in +Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 + +This dataset is specifically designed to require the pairwise interaction terms +to be conditioned on the input, in other words to use non-trival edge-features. + +The task is as following: a "snake" of length ten wandered over a grid. For +each cell, it had the option to go up, down, left or right (unless it came from +there). The input consists of these decisions, while the desired output is an +annotation of the snake from 0 (head) to 9 (tail). See the plots for an +example. + +As input features we use a 3x3 window around each pixel (and pad with background +where necessary). We code the five different input colors (for up, down, left, right, +background) using a one-hot encoding. This is a rather naive approach, not using any +information about the dataset (other than that it is a 2d grid). + +The task can not be solved using the simple DirectionalGridCRF - which can only +infer head and tail (which are also possible to infer just from the unary +features). If we add edge-features that contain the features of the nodes that are +connected by the edge, the CRF can solve the task. + +From an inference point of view, this task is very hard. QPBO move-making is +not able to solve it alone, so we use the relaxed AD3 inference for learning. + +PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). +But it does work as well as Decision Tree Fields ;) + + + + JL Meunier - January 2017 + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943 + + Copyright Xerox + +""" + +import sys, os, time +import random, cPickle + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.metrics import confusion_matrix, accuracy_score +from sklearn.linear_model import LogisticRegression +from sklearn.grid_search import GridSearchCV + +from pystruct.learners import OneSlackSSVM +from pystruct.datasets import load_snakes +from pystruct.models import NodeTypeEdgeFeatureGraphCRF + +from plot_snakes import one_hot_colors, neighborhood_feature, prepare_data + +from plot_hidden_snakes import augmentWithNoSnakeImages, shuffle_in_unison, shorten_snakes + + + +#============================================================================================== + +bFIXED_RANDOM_SEED = True + +NCELL=10 + +nbSWAP_Pixel_Pict_TYPES = 0 #0,1,2 are useful (this was for DEBUG) + +bMAKE_PICT_EASY = False #DEBUG: we had a feature on the picture that tells directly if a snake is present or not + +#INFERENCE="qpbo" +INFERENCE="ad3+" +N_JOBS=8 + +MAXITER=750 + +sMODELFILE = None +sMODELFILE = "model.pkl" #we save the model in a file and do not re-trian if the file exists + +#============================================================================================== + +def printConfig(): + print "== NCELL=", NCELL + print "== FIXED_SEED=", bFIXED_RANDOM_SEED + print "== INFERENCE =", INFERENCE + print "== N_JOBS =", N_JOBS + print "== SWAP=", nbSWAP_Pixel_Pict_TYPES + print "== EASY=", bMAKE_PICT_EASY + print "== MAX_ITER=", MAXITER + print "== MODEL FILE=", sMODELFILE + +if __name__ == '__main__': printConfig() + + +if bFIXED_RANDOM_SEED: + np.random.seed(1605) + random.seed(98) +else: + np.random.seed() + random.seed() + +def plot_snake(picture): + plt.imshow(picture, interpolation='nearest') + plt.show() + +def prepare_picture_data(X): + """ + compute picture features (on 1-hot encoded pictures) + """ + lPictFeat = list() + for a_hot_picture in X: + #count number of cells of each color + #feat = np.zeros((1,5), dtype=np.int8) + feat = np.zeros((1,7), dtype=np.int64) + + #Histogram of pixels from 0 to 4 + """ + Test accuracy: 0.500 + [[45 55] + [45 55]] + """ + for i in xrange(5): + ai, aj = np.where(a_hot_picture[...,i] == 1) + feat[0,i] = len(ai) + + #adding height and width of the snake + """ + Test accuracy: 0.420 Test accuracy: 0.515 Test accuracy: 0.495 + [[39 61] [[48 52] [[52 48] + [55 45]] [45 55]] [53 47]] + """ + ai, aj = np.where(a_hot_picture[...,3] != 1) + feat[0,5] = max(ai)-min(ai) #height + feat[0,6] = max(aj)-min(aj) #width + + lPictFeat.append(feat) + + return lPictFeat + +def convertToTwoType(X_train, #list of hot pictures + X_train_directions, # list of node_feat (2D array) , edges (_ x 2 array), edge_feat (2D array) for pixel nodes + Y_train, # list of 2D arrays + X_train_pict_feat, #a list of picture_node_features + Y_train_pict, #a list of integers [0,1] + nCell=10): + """ + return X,Y for NodeTypeEdgeFeatureGraphCRF + + + X and Y + ------- + Node features are given as a list of n_types arrays of shape (n_type_nodes, n_type_features): + - n_type_nodes is the number of nodes of that type + - n_type_features is the number of features for this type of node + + Edges are given as a list of n_types x n_types arrays of shape (n_type_edges, 2). + Columns are resp.: node index (in corresponding node type), node index (in corresponding node type) + + Edge features are given as a list of n_types x n_types arrays of shape (n_type_type_edge, n_type_type_edge_features) + - n_type_type_edge is the number of edges of type type_type + - n_type_type_edge_features is the number of features for edge of type type_type + + An instance ``X`` is represented as a tuple ``([node_features, ..], [edges, ..], [edge_features, ..])`` + + Labels ``Y`` are given as one array of shape (n_nodes) The meaning of a label depends upon the node type. + + """ + + lX, lY = list(), list() + + for (X, + (aPixelFeat, aPixelPixelEdges, aPixelPixelEdgeFeat), + aPixelLbl, + aPictFeat, + iPictLbl) in zip(X_train, X_train_directions, Y_train, X_train_pict_feat, Y_train_pict ): + + + aPixelPictEdges = np.zeros( (aPixelFeat.shape[0], 2), np.int64) + aPixelPictEdges[:,0] = np.arange(aPixelFeat.shape[0]) + features = neighborhood_feature(X) + aPixelPictEdgeFeat = features + + lNodeFeat = [aPixelFeat, aPictFeat] + lEdge = [aPixelPixelEdges, + aPixelPictEdges, #pixel to picture + None, #picture to pixel + None] #picture to picture + lEdgeFeat = [aPixelPixelEdgeFeat, + aPixelPictEdgeFeat, + None, + None] + + #Y is flat for each graph + y = np.zeros((aPixelLbl.size+1, ), dtype=np.int64) + y[:-1] = aPixelLbl.ravel() + y[-1] = int(iPictLbl)+nCell+1 + + x = (lNodeFeat, lEdge, lEdgeFeat) + + lX.append(x) + lY.append(y) + + return lX,lY + +def swap_node_types(l_perm, l_n_state, lX, lY, constraints=None): + """ + lX and lY have been produced for a CRF configured with l_n_state + + We permute this as indicated by the permutation (typically for the snake: l_perm=[1, 0] ) + + """ + _lX, _lY = [], [] + _constraints = None + + n_types = len(l_n_state) + a_perm = np.asarray(l_perm) #e.g. 3 for l_n_state = [2, 3, 4] + a_cumsum_n_state = np.asarray([sum(l_n_state[:i]) for i in range(len(l_n_state))]) # [0, 2, 5] + a_delta_y_by_y = np.asarray([item for i,n in enumerate(l_n_state) for item in n*(a_cumsum_n_state[i:i+1]).tolist()]) # [0, 0, 2, 2, 2, 5, 5, 5, 5] + a_typ_by_y = np.asarray([item for i,n in enumerate(l_n_state) for item in n*[i]]) # [0, 0, 1, 1, 1, 2, 2, 2, 2] + + _l_n_state = [l_n_state[i] for i in l_perm] + _a_cumsum_n_state = np.asarray([sum(_l_n_state[:i]) for i in range(len(_l_n_state))]) + + for (lNF, lE, lEF), Y in zip(lX, lY): + + _lNF = [lNF[i] for i in l_perm] + + _Y = np.zeros(Y.shape, dtype=Y.dtype) + #we need to re-arrange the Ys accordingly + l_n_nodes = [nf.shape[0] for nf in lNF] + _l_n_nodes = [nf.shape[0] for nf in _lNF] + cumsum_n_nodes = [0] + [sum( l_n_nodes[:i+1]) for i in range(len( l_n_nodes))] + _cumsum_n_nodes = [0] + [sum(_l_n_nodes[:i+1]) for i in range(len(_l_n_nodes))] + for i in range(len(lNF)): + j = l_perm[i] + _Y[_cumsum_n_nodes[j]:_cumsum_n_nodes[j+1]] = Y[cumsum_n_nodes[i]:cumsum_n_nodes[i+1]] + + _Y = _Y - a_delta_y_by_y[_Y] + _a_cumsum_n_state[a_perm[a_typ_by_y[_Y]]] + + _lE = [lE[i*n_types+j] for i in l_perm for j in l_perm] + _lEF = [lEF[i*n_types+j] for i in l_perm for j in l_perm] + + _lX.append( (_lNF, _lE, _lEF) ) + _lY.append(_Y) + + if constraints: + print "WARNING: some constraints are not properly swapped because the node order has a meaning." + _constraints = list() + for _lConstraints in constraints: + for (op, l_l_unary, l_l_state, l_lnegated) in _lConstraints: + #keep the op but permute by types + _l_l_unary = [l_l_unary [i] for i in l_perm] + _l_l_state = [l_l_state [i] for i in l_perm] + _l_lnegated = [l_lnegated[i] for i in l_perm] + _lConstraints.append( (op, _l_l_unary, _l_l_state, _l_lnegated)) + _constraints.append(_lConstraints) + + return _lX, _lY, _constraints + +def listConstraints(lX): + """ + produce the list of constraints for this list of multi-type graphs + """ + lConstraints = list() + for _lNF, _lE, _lEF in lX: + nf_pixel, nf_pict = _lNF + nb_pixels = len(nf_pixel) + l_l_unary = [ range(nb_pixels), [0]] + l_l_states = [ 0, 0 ] #we pass a scalar for each type instead of a list since the values are the same across each type + l_l_negated = [ False, False ] #same + + lConstraint_for_X = [("ANDOUT", l_l_unary, l_l_states, l_l_negated)] #we have a list of constraints per X + + for _state in range(1, NCELL+1): + lConstraint_for_X.append( ("XOROUT" , l_l_unary + , [ _state, 1 ] #exactly one cell in state _state with picture label being snake + , l_l_negated) + ) #we have a list of constraints per X + + lConstraints.append( lConstraint_for_X ) + return lConstraints + + +def makeItEasy(lX_pict_feat, lY_pict): + """ + add the picture label in a feature... + """ + for X,y in zip(lX_pict_feat, lY_pict): + X[0] = y + + +def REPORT(l_Y_GT, lY_Pred, t=None): + if t: print "\t( predict DONE IN %.1fs)"%t + + _flat_GT, _flat_P = (np.hstack([y.ravel() for y in l_Y_GT]), + np.hstack([y.ravel() for y in lY_Pred])) + confmat = confusion_matrix(_flat_GT, _flat_P) + print confmat + print "\ttrace =", confmat.trace() + print "\tAccuracy= %.3f"%accuracy_score(_flat_GT, _flat_P) + + +if __name__ == '__main__': + + print("Please be patient...") + snakes = load_snakes() + + #-------------------------------------------------------------------------------------------------- + X_train, Y_train = snakes['X_train'], snakes['Y_train'] + #X_train, Y_train = X_train[:3], Y_train[:3] + print "TRAIN SET ", len(X_train), len(Y_train) + + if NCELL <10: X_train, Y_train = shorten_snakes(X_train, Y_train, NCELL) + + nb_hidden, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False, nCell=NCELL) + print "TRAIN SET ",len(X_train), len(Y_train) + Y_train_pict = np.array([1]*(len(X_train)-nb_hidden) + [0]*nb_hidden) + + X_train = [one_hot_colors(x) for x in X_train] + + X_train, Y_train, Y_train_pict = shuffle_in_unison(X_train, Y_train, Y_train_pict) + + + X_train_pict_feat = prepare_picture_data(X_train) + if bMAKE_PICT_EASY: + print "Making the train picture task easy" + makeItEasy(X_train_pict_feat, Y_train_pict) + + X_train_directions, X_train_edge_features = prepare_data(X_train) + #-------------------------------------------------------------------------------------------------- + X_test, Y_test = snakes['X_test'], snakes['Y_test'] + + if NCELL <10: X_test, Y_test = shorten_snakes(X_test, Y_test, NCELL) + + nb_hidden, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", False, nCell=NCELL) + Y_test_pict = np.array([1]*(len(X_test)-nb_hidden) + [0]*nb_hidden) + print "TEST SET ", len(X_test), len(Y_test) + + X_test = [one_hot_colors(x) for x in X_test] + + #useless X_test, Y_test, Y_test_pict = shuffle_in_unison(X_test, Y_test, Y_test_pict) + + X_test_pict_feat = prepare_picture_data(X_test) + if bMAKE_PICT_EASY: + print "Making the test picture task easy" + makeItEasy(X_test_pict_feat, Y_test_pict) + + X_test_directions, X_test_edge_features = prepare_data(X_test) + + #-------------------------------------------------------------------------------------------------- + print "======================================================================================================" + if True: + from pystruct.models.edge_feature_graph_crf import EdgeFeatureGraphCRF + print "ONE TYPE TRAINING AND TESTING: PIXELS" + +# inference = 'ad3+' +# inference = 'qpbo' + inference=INFERENCE + inference = "qpbo" + crf = EdgeFeatureGraphCRF(inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + max_iter=MAXITER, + n_jobs=N_JOBS + #,verbose=1 + , switch_to='ad3' + ) + + Y_train_flat = [y_.ravel() for y_ in Y_train] + print "\ttrain label histogram : ", np.histogram(np.hstack(Y_train_flat), bins=range(NCELL+2)) + + t0 = time.time() + ssvm.fit(X_train_edge_features, Y_train_flat) + print "FIT DONE IN %.1fs"%(time.time() - t0) + sys.stdout.flush() + + t0 = time.time() + _Y_pred = ssvm.predict( X_test_edge_features ) + REPORT(Y_test, _Y_pred, time.time() - t0) + + #-------------------------------------------------------------------------------------------------- + if True: + print "_"*50 + print "ONE TYPE TRAINING AND TESTING: PICTURES" + + print "\ttrain label histogram : ", np.histogram(Y_train_pict, bins=range(3)) + + lr = LogisticRegression(class_weight='balanced') + + mdl = GridSearchCV(lr , {'C':[0.1, 0.5, 1.0, 2.0] }) + + XX = np.vstack(X_train_pict_feat) + + t0 = time.time() + mdl.fit(XX, Y_train_pict) + print "FIT DONE IN %.1fs"%(time.time() - t0) + + t0 = time.time() + _Y_pred = mdl.predict( np.vstack(X_test_pict_feat) ) + REPORT([Y_test_pict], _Y_pred, time.time() - t0) + + #-------------------------------------------------------------------------------------------------- + print "======================================================================================================" + + + # first, train on X with directions only: + #crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[2]], inference_method=inference) + # first, train on X with directions only: +# l_weights = [ +# [10.0/200] + [10.0/200]*10, +# [10.0/20 , 10.0/20] +# ] +# print "WEIGHTS:", l_weights + if nbSWAP_Pixel_Pict_TYPES %2 == 0: + l_n_states = [NCELL+1, 2] # 11 states for pixel nodes, 2 states for pictures + l_n_feat = [45, 7] # 45 features for pixels, 7 for pictures + ll_n_feat = [[180, 45], # 2 feature between pixel nodes, 1 between pixel and picture + [45 , 0]] # , nothing between picture nodes (no picture_to_picture edge anyway) + else: + l_n_states = [2, NCELL+1] + l_n_feat = [7, 45] + ll_n_feat = [[0, 45], [45 , 180]] + + if not sMODELFILE or not os.path.exists(sMODELFILE): + print " TRAINING MULTI-TYPE MODEL " + #TRAINING + crf = NodeTypeEdgeFeatureGraphCRF(2, # How many node types? + l_n_states, # How many states per type? + l_n_feat, # How many node features per type? + ll_n_feat, # How many edge features per type x type? + inference_method=INFERENCE + # , l_class_weight = l_weights + ) + print crf + + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=0, + max_iter=MAXITER, + n_jobs=N_JOBS + #,verbose=1 + #, switch_to='ad3' + ) + + print "======================================================================================================" + print "YY[0].shape", Y_train[0].shape + XX, YY = convertToTwoType(X_train, + X_train_edge_features, # list of node_feat , edges, edge_feat for pixel nodes + Y_train, + X_train_pict_feat, #a list of picture_node_features + Y_train_pict, #a list of integers [0,1] + nCell=NCELL) + + if nbSWAP_Pixel_Pict_TYPES: + if nbSWAP_Pixel_Pict_TYPES % 2 == 0: + XX, YY = swap_node_types([1,0], [NCELL+1, 2], XX, YY) + XX, YY = swap_node_types([1,0], [2 , NCELL+1], XX, YY) + else: + XX, YY = swap_node_types([1,0], [NCELL+1, 2], XX, YY) + + + print "\tlabel histogram : ", np.histogram( np.hstack([y.ravel() for y in YY]), bins=range(14)) + + + print "YY[0].shape", YY[0].shape + crf.initialize(XX, YY)# check if the data is properly built + sys.stdout.flush() + + t0 = time.time() + ssvm.fit(XX, YY) + print "FIT DONE IN %.1fs"%(time.time() - t0) + sys.stdout.flush() + + ssvm.alphas = None + ssvm.constraints_ = None + ssvm.inference_cache_ = None + if sMODELFILE: + print "Saving model in: ", sMODELFILE + with open(sMODELFILE, "wb") as fd: + cPickle.dump(ssvm, fd) + else: + #REUSE PREVIOUSLY TRAINED MODEL + print " RUSING PREVIOULSLY TRAINED MULTI-TYPE MODEL: ", sMODELFILE + + with open(sMODELFILE, "rb") as fd: + ssvm = cPickle.load(fd) + + + print "INFERENCE WITH ", INFERENCE + XX_test, YY_test =convertToTwoType(X_test, + X_test_edge_features, # list of node_feat , edges, edge_feat for pixel nodes + Y_test, + X_test_pict_feat, #a list of picture_node_features + Y_test_pict, #a list of integers [0,1] + nCell=NCELL) + print "\tlabel histogram (PIXELs and PICTUREs): ", np.histogram( np.hstack([y.ravel() for y in YY_test]), bins=range(14)) + + + l_constraints = listConstraints(XX_test) + + if nbSWAP_Pixel_Pict_TYPES %2 == 1: + XX_test, YY_test, l_constraints = swap_node_types([1,0], [NCELL+1, 2], XX_test, YY_test, l_constraints) + + print "\t- results without constraints" + t0 = time.time() + YY_pred = ssvm.predict( XX_test ) + REPORT(YY_test, YY_pred, time.time() - t0) + + print "_"*50 + print "\t- results exploiting constraints" + t0 = time.time() + YY_pred = ssvm.predict( XX_test, l_constraints ) + REPORT(YY_test, YY_pred, time.time() - t0) + + + print "_"*50 + + if INFERENCE == "ad3": + ssvm.model.inference_method = "ad3+" + else: + ssvm.model.inference_method = "ad3" + print "INFERENCE WITH ", ssvm.model.inference_method + t0 = time.time() + YY_pred = ssvm.predict( XX_test ) + REPORT(YY_test, YY_pred, time.time() - t0) + + print "DONE" + + printConfig() + + +""" + + + + +""" \ No newline at end of file From bf994f30354e3eab9848716dc6500c42a79e22e3 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 6 Feb 2017 13:28:09 +0100 Subject: [PATCH 033/155] ok --- .../logs/plot_hidden_short_snakes_typed.log | 158 ++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 examples/logs/plot_hidden_short_snakes_typed.log diff --git a/examples/logs/plot_hidden_short_snakes_typed.log b/examples/logs/plot_hidden_short_snakes_typed.log new file mode 100644 index 00000000..89b36227 --- /dev/null +++ b/examples/logs/plot_hidden_short_snakes_typed.log @@ -0,0 +1,158 @@ +== NCELL= 10 +== FIXED_SEED= True +== INFERENCE = ad3+ +== N_JOBS = 8 +== SWAP= 0 +== EASY= False +== MAX_ITER= 750 +== MODEL FILE= model.pkl +Please be patient... +TRAIN SET 200 200 +ADDING PICTURE WIHOUT SNAKES!!! 200 elements in train + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! +TRAIN SET 376 376 +ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! +TEST SET 187 187 +====================================================================================================== +ONE TYPE TRAINING AND TESTING: PIXELS + train label histogram : (array([12198, 200, 200, 200, 200, 200, 200, 200, 200, + 200, 200]), array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])) +FIT DONE IN 312.4s + ( predict DONE IN 1.4s) +[[5633 37 37 39 37 38 32 29 37 47 49] + [ 14 85 1 0 0 0 0 0 0 0 0] + [ 13 0 85 1 0 0 0 0 0 1 0] + [ 12 0 0 82 1 3 1 1 0 0 0] + [ 12 0 0 0 79 1 7 1 0 0 0] + [ 11 2 0 2 1 77 0 6 1 0 0] + [ 9 0 3 1 2 1 79 0 5 0 0] + [ 9 0 0 3 1 2 1 81 0 3 0] + [ 8 0 0 0 3 1 2 1 84 0 1] + [ 9 0 0 0 0 3 1 2 1 84 0] + [ 7 0 0 0 0 0 3 1 1 1 87]] + trace = 6456 + Accuracy= 0.920 +__________________________________________________ +ONE TYPE TRAINING AND TESTING: PICTURES + train label histogram : (array([176, 200]), array([0, 1, 2])) +FIT DONE IN 0.0s + ( predict DONE IN 0.0s) +[[30 57] + [47 53]] + trace = 83 + Accuracy= 0.444 +====================================================================================================== + TRAINING MULTI-TYPE MODEL +NodeTypeEdgeFeatureGraphCRF(n_states: [11, 2], inference_method: ad3+, n_features: [45, 7], n_edge_features: [[180 45] + [ 45 0]]) +====================================================================================================== +YY[0].shape (6, 6) + label histogram : (array([12198, 200, 200, 200, 200, 200, 200, 200, 200, + 200, 200, 176, 200]), array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])) +YY[0].shape (37,) +FIT DONE IN 1344.1s +Saving model in: model.pkl +INFERENCE WITH ad3+ + label histogram (PIXELs and PICTUREs): (array([6015, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, + 87, 100]), array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])) + - results without constraints + ( predict DONE IN 9.8s) +[[5739 30 33 32 24 23 23 20 28 31 32 0 0] + [ 5 93 2 0 0 0 0 0 0 0 0 0 0] + [ 3 0 91 2 0 0 2 0 1 1 0 0 0] + [ 4 0 0 89 2 0 0 3 1 1 0 0 0] + [ 4 0 2 0 86 3 3 0 2 0 0 0 0] + [ 4 2 0 3 0 82 2 5 1 1 0 0 0] + [ 4 0 4 1 3 0 82 2 3 0 1 0 0] + [ 4 0 0 4 1 3 1 84 1 2 0 0 0] + [ 3 0 0 0 4 1 2 1 88 1 0 0 0] + [ 3 0 0 0 0 4 1 4 1 86 1 0 0] + [ 3 0 0 1 0 0 5 1 1 1 88 0 0] + [ 0 0 0 0 0 0 0 0 0 0 0 60 27] + [ 0 0 0 0 0 0 0 0 0 0 0 3 97]] + trace = 6765 + Accuracy= 0.939 +__________________________________________________ + - results exploiting constraints + ( predict DONE IN 13.7s) +[[5735 29 30 30 27 29 28 26 24 29 28 0 0] + [ 9 91 0 0 0 0 0 0 0 0 0 0 0] + [ 9 0 91 0 0 0 0 0 0 0 0 0 0] + [ 9 0 0 91 0 0 0 0 0 0 0 0 0] + [ 9 0 0 0 91 0 0 0 0 0 0 0 0] + [ 9 0 0 0 0 91 0 0 0 0 0 0 0] + [ 9 0 0 0 0 0 91 0 0 0 0 0 0] + [ 9 0 0 0 0 0 0 91 0 0 0 0 0] + [ 9 0 0 0 0 0 0 0 91 0 0 0 0] + [ 9 0 0 0 0 0 0 0 0 91 0 0 0] + [ 9 0 0 0 0 0 0 0 0 0 91 0 0] + [ 0 0 0 0 0 0 0 0 0 0 0 57 30] + [ 0 0 0 0 0 0 0 0 0 0 0 9 91]] + trace = 6793 + Accuracy= 0.943 +__________________________________________________ +INFERENCE WITH ad3 + Y is BAD, FIXING IT AT RANDOM +array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11]) + ( predict DONE IN 3.1s) +[[5743 25 30 30 26 26 24 22 29 30 30 0 0] + [ 6 92 2 0 0 0 0 0 0 0 0 0 0] + [ 4 0 91 2 0 0 1 0 1 1 0 0 0] + [ 5 0 0 89 2 0 0 2 1 1 0 0 0] + [ 5 0 2 0 84 3 3 0 3 0 0 0 0] + [ 5 2 0 3 0 80 3 5 0 2 0 0 0] + [ 5 0 4 1 3 0 80 2 3 0 2 0 0] + [ 5 0 0 4 1 3 1 83 1 2 0 0 0] + [ 5 0 0 0 4 1 2 1 86 1 0 0 0] + [ 5 0 0 0 0 4 1 4 1 84 1 0 0] + [ 5 0 0 1 0 0 5 1 1 1 86 0 0] + [ 0 0 0 0 0 0 0 0 0 0 0 61 26] + [ 0 0 0 0 0 0 0 0 0 0 0 5 95]] + trace = 6754 + Accuracy= 0.938 +DONE +== NCELL= 10 +== FIXED_SEED= True +== INFERENCE = ad3+ +== N_JOBS = 8 +== SWAP= 0 +== EASY= False +== MAX_ITER= 750 +== MODEL FILE= model.pkl From 34d5f5d4d805bd87102a43ecb077d46784d628d7 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 6 Feb 2017 13:36:55 +0100 Subject: [PATCH 034/155] ok!! :) --- examples/plot_hidden_snakes_logit.py | 141 ------- examples/plot_hidden_snakes_typed.py | 346 ------------------ pystruct/inference/__init__.py | 6 +- pystruct/inference/inference_methods.py | 46 ++- .../node_type_edge_feature_graph_crf.py | 120 ++---- pystruct/models/typed_crf.py | 152 +++----- 6 files changed, 133 insertions(+), 678 deletions(-) delete mode 100644 examples/plot_hidden_snakes_logit.py delete mode 100644 examples/plot_hidden_snakes_typed.py diff --git a/examples/plot_hidden_snakes_logit.py b/examples/plot_hidden_snakes_logit.py deleted file mode 100644 index e75c24ae..00000000 --- a/examples/plot_hidden_snakes_logit.py +++ /dev/null @@ -1,141 +0,0 @@ -""" -============================================== -Conditional Interactions on the Snakes Dataset -============================================== - -This is a variant of plot_snakes.py - -Snake are hidding, so another task is both to determine if a snake is in the picture, and -identify its head to tail body. - -We use the Logit and some picture feature to categorize pictures (only this task) - - -This example uses the snake dataset introduced in -Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 - -This dataset is specifically designed to require the pairwise interaction terms -to be conditioned on the input, in other words to use non-trival edge-features. - -The task is as following: a "snake" of length ten wandered over a grid. For -each cell, it had the option to go up, down, left or right (unless it came from -there). The input consists of these decisions, while the desired output is an -annotation of the snake from 0 (head) to 9 (tail). See the plots for an -example. - -As input features we use a 3x3 window around each pixel (and pad with background -where necessary). We code the five different input colors (for up, down, left, right, -background) using a one-hot encoding. This is a rather naive approach, not using any -information about the dataset (other than that it is a 2d grid). - -The task can not be solved using the simple DirectionalGridCRF - which can only -infer head and tail (which are also possible to infer just from the unary -features). If we add edge-features that contain the features of the nodes that are -connected by the edge, the CRF can solve the task. - -From an inference point of view, this task is very hard. QPBO move-making is -not able to solve it alone, so we use the relaxed AD3 inference for learning. - -PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). -But it does work as well as Decision Tree Fields ;) -""" -import numpy as np -import matplotlib.pyplot as plt -import random -import time - -from sklearn.metrics import confusion_matrix, accuracy_score -from sklearn.linear_model import LogisticRegression -from sklearn.grid_search import GridSearchCV - -from pystruct.datasets import load_snakes - -from plot_snakes import one_hot_colors, neighborhood_feature, prepare_data - -from plot_hidden_snakes import shufflePictureCells, shuffleSnakeCells, changeOneSnakeCell, augmentWithNoSnakeImages, shuffle_in_unison -from plot_hidden_snakes_typed import prepare_picture_data - -def shuffleSnake(a_picture, bOneHot=True): - """ - Shuffle either the snake's cells or the pcitures' pixels. - """ - if True: - changeOneSnakeCell(a_picture, bOneHot) - changeOneSnakeCell(a_picture, bOneHot) - else: - if random.randint(0,1): - shuffleSnakeCells(a_picture, bOneHot) - else: - shufflePictureCells(a_picture) - -def convertToSingleTypeX(X): - """ - For NodeTypeEdgeFeatureGraphCRF X is structured differently. - But NodeTypeEdgeFeatureGraphCRF can handle graph with a single node type. One needs to convert X to the new structure using this method. - """ - return [([nf], [e], [ef]) for (nf,e,ef) in X] - -def plot_snake(picture): - plt.imshow(picture, interpolation='nearest') - plt.show() - - -if __name__ == '__main__': - print("Please be patient. Learning will take 5-20 minutes.") - snakes = load_snakes() - X_train, Y_train = snakes['X_train'], snakes['Y_train'] - - bADD_HIDDEN_SNAKES = True - #bADD_HIDDEN_SNAKES = False - #JL - #X_train, Y_train = X_train[:10], Y_train[:10] - print len(X_train), len(Y_train) - #print `X_train[0]` - - if bADD_HIDDEN_SNAKES: - nb_hidden, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False) - print len(X_train), len(Y_train) - Y_train_pict = np.array([1]*(len(X_train)-nb_hidden) + [0]*nb_hidden) - - if False: - #show the faked pictures - for ix, x in enumerate(X_train): plot_snake(shufflePictureCells(x)) - - X_train = [one_hot_colors(x) for x in X_train] - - X_train, Y_train, Y_train_pict = shuffle_in_unison(X_train, Y_train, Y_train_pict) - - X_train_pict_feat = prepare_picture_data(X_train) - X_train_pict_feat = np.vstack(X_train_pict_feat) - print "X_train_pict_feat.shape ", X_train_pict_feat.shape - lr = LogisticRegression(class_weight='balanced') - dicGS = {'C':[0.1, 0.5, 1.0, 2.0] } - dicGS = {'C':[1.0] } - mdl = GridSearchCV(lr , dicGS) - - print "-training a logistic regression model on pictures" - mdl.fit(X_train_pict_feat, Y_train_pict) - - # --- TEST - X_test, Y_test = snakes['X_test'], snakes['Y_test'] - print "TEST len=", len(X_test) - if bADD_HIDDEN_SNAKES: - nb_hidden, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", bOneHot=False) - print "TEST len=", len(X_test) - Y_test_pict = np.array([1]*(len(X_test)-nb_hidden) + [0]*nb_hidden) - - X_test = [one_hot_colors(x) for x in X_test] - X_test_pict_feat = prepare_picture_data(X_test) - X_test_pict_feat = np.vstack(X_test_pict_feat) - - Y_pred = mdl.predict( X_test_pict_feat ) - print("Results using only directional features for edges") - print("Test accuracy: %.3f" - % accuracy_score(Y_test_pict, Y_pred)) - print(confusion_matrix(Y_test_pict, Y_pred)) - - -""" - - - """ \ No newline at end of file diff --git a/examples/plot_hidden_snakes_typed.py b/examples/plot_hidden_snakes_typed.py deleted file mode 100644 index 6534a818..00000000 --- a/examples/plot_hidden_snakes_typed.py +++ /dev/null @@ -1,346 +0,0 @@ -""" -============================================== -Conditional Interactions on the Snakes Dataset -============================================== - -This is a variant of plot_snakes.py - -Snake are hidding, so another task is both to determine if a snake is in the picture, and -identify its head to tail body. - -We use the NodeTypeEdgeFeatureGraphCRF class with 2 type of nodes. - - -This example uses the snake dataset introduced in -Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 - -This dataset is specifically designed to require the pairwise interaction terms -to be conditioned on the input, in other words to use non-trival edge-features. - -The task is as following: a "snake" of length ten wandered over a grid. For -each cell, it had the option to go up, down, left or right (unless it came from -there). The input consists of these decisions, while the desired output is an -annotation of the snake from 0 (head) to 9 (tail). See the plots for an -example. - -As input features we use a 3x3 window around each pixel (and pad with background -where necessary). We code the five different input colors (for up, down, left, right, -background) using a one-hot encoding. This is a rather naive approach, not using any -information about the dataset (other than that it is a 2d grid). - -The task can not be solved using the simple DirectionalGridCRF - which can only -infer head and tail (which are also possible to infer just from the unary -features). If we add edge-features that contain the features of the nodes that are -connected by the edge, the CRF can solve the task. - -From an inference point of view, this task is very hard. QPBO move-making is -not able to solve it alone, so we use the relaxed AD3 inference for learning. - -PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). -But it does work as well as Decision Tree Fields ;) - - - - JL Meunier - January 2017 - - Developed for the EU project READ. The READ project has received funding - from the European Union's Horizon 2020 research and innovation programme - under grant agreement No 674943 - - Copyright Xerox - -""" -import numpy as np -import matplotlib.pyplot as plt -import random -from sklearn.preprocessing import label_binarize -from sklearn.metrics import confusion_matrix, accuracy_score -import time -import sys - -from pystruct.learners import OneSlackSSVM -from pystruct.datasets import load_snakes -from pystruct.utils import make_grid_edges, edge_list_to_features -#from pystruct.models import EdgeFeatureGraphCRF -from pystruct.models import NodeTypeEdgeFeatureGraphCRF - -from plot_snakes import one_hot_colors, neighborhood_feature, prepare_data - -from plot_hidden_snakes import shufflePictureCells, shuffleSnakeCells, changeOneSnakeCell, augmentWithNoSnakeImages, shuffle_in_unison - -def shuffleSnake(a_picture, bOneHot=True): - """ - Shuffle either the snake's cells or the pcitures' pixels. - """ - if True: - changeOneSnakeCell(a_picture, bOneHot) - changeOneSnakeCell(a_picture, bOneHot) - else: - if random.randint(0,1): - shuffleSnakeCells(a_picture, bOneHot) - else: - shufflePictureCells(a_picture) - -def plot_snake(picture): - plt.imshow(picture, interpolation='nearest') - plt.show() - -def prepare_picture_data(X): - """ - compute picture features (on 1-hot encoded pictures) - """ - lPictFeat = list() - for a_hot_picture in X: - #count number of cells of each color - #feat = np.zeros((1,5), dtype=np.int8) - feat = np.zeros((1,7), dtype=np.int64) - - #Histogram of pixels from 0 to 4 - """ - Test accuracy: 0.500 - [[45 55] - [45 55]] - """ - for i in xrange(5): - ai, aj = np.where(a_hot_picture[...,i] == 1) - feat[0,i] = len(ai) - - #adding height and width of the snake - """ - Test accuracy: 0.420 Test accuracy: 0.515 Test accuracy: 0.495 - [[39 61] [[48 52] [[52 48] - [55 45]] [45 55]] [53 47]] - """ - ai, aj = np.where(a_hot_picture[...,3] != 1) - feat[0,5] = max(ai)-min(ai) #height - feat[0,6] = max(aj)-min(aj) #width - - lPictFeat.append(feat) - - return lPictFeat - -def convertToTwoType(X_train, #list of hot pictures - X_train_directions, # list of node_feat (2D array) , edges (_ x 2 array), edge_feat (2D array) for pixel nodes - Y_train, # list of 2D arrays - X_train_pict_feat, #a list of picture_node_features - Y_train_pict): #a list of integers [0,1] - """ - return X,Y for NodeTypeEdgeFeatureGraphCRF - - - X and Y - ------- - Node features are given as a list of n_types arrays of shape (n_type_nodes, n_type_features): - - n_type_nodes is the number of nodes of that type - - n_type_features is the number of features for this type of node - - Edges are given as a list of n_types x n_types arrays of shape (n_type_edges, 2). - Columns are resp.: node index (in corresponding node type), node index (in corresponding node type) - - Edge features are given as a list of n_types x n_types arrays of shape (n_type_type_edge, n_type_type_edge_features) - - n_type_type_edge is the number of edges of type type_type - - n_type_type_edge_features is the number of features for edge of type type_type - - An instance ``X`` is represented as a tuple ``([node_features, ..], [edges, ..], [edge_features, ..])`` - - Labels ``Y`` are given as one array of shape (n_nodes) The meaning of a label depends upon the node type. - - """ - - lX, lY = list(), list() - - for (X, - (aPixelFeat, aPixelPixelEdges, aPixelPixelEdgeFeat), - aPixelLbl, - aPictFeat, - iPictLbl) in zip(X_train, X_train_directions, Y_train, X_train_pict_feat, Y_train_pict ): - - - aPixelPictEdges = np.zeros( (aPixelFeat.shape[0], 2), np.int64) - aPixelPictEdges[:,0] = np.arange(aPixelFeat.shape[0]) - features = neighborhood_feature(X) - aPixelPictEdgeFeat = features - - lNodeFeat = [aPixelFeat, aPictFeat] - lEdge = [aPixelPixelEdges, - aPixelPictEdges, #pixel to picture - None, #picture to pixel - None] #picture to picture - lEdgeFeat = [aPixelPixelEdgeFeat, - aPixelPictEdgeFeat, - None, - None] - - #Y is flat for each graph - y = np.zeros((aPixelLbl.size+1, ), dtype=np.int64) - y[:-1] = aPixelLbl.ravel() - y[-1] = int(iPictLbl)+11 - - x = (lNodeFeat, lEdge, lEdgeFeat) - - lX.append(x) - lY.append(y) - - return lX,lY - - - - - -if __name__ == '__main__': - - np.random.seed(1605) - random.seed(98) - - print("Please be patient...") - snakes = load_snakes() - X_train, Y_train = snakes['X_train'], snakes['Y_train'] - - bADD_HIDDEN_SNAKES = True - #bADD_HIDDEN_SNAKES = False - #JL - X_train, Y_train = X_train[:3], Y_train[:3] - print len(X_train), len(Y_train) - #print `X_train[0]` - - if bADD_HIDDEN_SNAKES: - nb_hidden, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False) - print len(X_train), len(Y_train) - Y_train_pict = np.array([1]*(len(X_train)-nb_hidden) + [0]*nb_hidden) - - X_train = [one_hot_colors(x) for x in X_train] - - X_train, Y_train, Y_train_pict = shuffle_in_unison(X_train, Y_train, Y_train_pict) - - - X_train_pict_feat = prepare_picture_data(X_train) - - #X_train_pixel_pict_edge, X_train_pixel_pict_edge_feat = prepare_picture_edge_data(X_train) - - X_train_directions, X_train_edge_features = prepare_data(X_train) - - inference = 'ad3' - # first, train on X with directions only: - #crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[2]], inference_method=inference) - # first, train on X with directions only: -# l_weights = [ -# [10.0/200] + [10.0/200]*10, -# [10.0/20 , 10.0/20] -# ] -# print "WEIGHTS:", l_weights - crf = NodeTypeEdgeFeatureGraphCRF(2, # 2 node types: pixels and pictures - [11, 2], # 11 states for pixel nodes, 2 states for pictures - [45, 7], # 45 features for pixels, 7 for pictures - [[180, 45], # 2 feature between pixel nodes, 1 between pixel and picture - [45 , 0]], # , nothing between picture nodes (no picture_to_picture edge anyway) - inference_method=inference -# , l_class_weight = l_weights - ) - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, - #max_iter=1000, - n_jobs=1 - ,verbose=1 - ) - - print "YY[0].shape", Y_train[0].shape - XX, YY = convertToTwoType(X_train, - X_train_edge_features, # list of node_feat , edges, edge_feat for pixel nodes - Y_train, - X_train_pict_feat, #a list of picture_node_features - Y_train_pict) #a list of integers [0,1] - - print np.histogram( np.hstack([y.ravel() for y in YY]), bins=range(14)) -# print np.histogram( np.hstack([y.ravel()[:-1] for y in YY]), bins=range(12)) -# print np.histogram( np.hstack([y.ravel()[-1] for y in YY]), bins=range(3)) -# yy_trn = np.hstack([y.ravel()[:-1] for y in YY]) -# print(confusion_matrix(yy_trn,yy_trn)) -# yy_trn_pic = np.hstack([y.ravel()[-1] for y in YY]) -# print(confusion_matrix(np.hstack(yy_trn_pic), np.hstack(yy_trn_pic))) - - - print "YY[0].shape", YY[0].shape - crf.initialize(XX, YY)# check if the data is properly built - sys.stdout.flush() - - t0 = time.time() - ssvm.fit(XX, YY) - print "FIT DONE IN %.1fs"%(time.time() - t0) - sys.stdout.flush() - -# import sys -# sys.exit(0) - - # Evaluate using confusion matrix. - # Clearly the middel of the snake is the hardest part. - X_test, Y_test = snakes['X_test'], snakes['Y_test'] -# X_test, Y_test = X_test[:3], Y_test[:3] - - if bADD_HIDDEN_SNAKES: - nb_hidden, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", False) - print len(X_test), len(Y_test) - Y_test_pict = np.array([1]*(len(X_test)-nb_hidden) + [0]*nb_hidden) - - X_test = [one_hot_colors(x) for x in X_test] - - #useless X_test, Y_test, Y_test_pict = shuffle_in_unison(X_test, Y_test, Y_test_pict) - - X_test_pict_feat = prepare_picture_data(X_test) - - X_test_directions, X_test_edge_features = prepare_data(X_test) - - XX_test, YY_test =convertToTwoType(X_test, - X_test_edge_features, # list of node_feat , edges, edge_feat for pixel nodes - Y_test, - X_test_pict_feat, #a list of picture_node_features - Y_test_pict) #a list of integers [0,1] - - print np.histogram( np.hstack([y.ravel() for y in YY_test]), bins=range(14)) - - YY_pred = ssvm.predict( XX_test ) - print len(XX_test), len(YY_pred) - - print confusion_matrix(np.hstack([y.ravel() for y in YY_test]), - np.hstack([y.ravel() for y in YY_pred])) - -# Y_test_flat = np.hstack([y.ravel()[:-1] for y in YY_test]) -# Y_pred_flat = np.hstack([y.ravel()[:-1] for y in YY_pred]) -# -# print("Results using only relevant features for edges") -# print("Test accuracy: %.3f" -# % accuracy_score(Y_test_flat, Y_pred_flat)) -# print(confusion_matrix(Y_test_flat, Y_pred_flat)) -# -# Y_pict_pred = [yy.ravel()[-1] for yy in YY_pred] -# print("Results AT PICTURE LEVEL using only directional features for edges") -# print("Test accuracy: %.3f" -# % accuracy_score(Y_test_pict, Y_pict_pred)) -# print(confusion_matrix(Y_test_pict, Y_pict_pred)) - - - if False: - # plot stuff - fig, axes = plt.subplots(2, 2) - axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') - axes[0, 0].set_title('Input') - y = Y_test[0].astype(np.int) - bg = 2 * (y != 0) # enhance contrast - axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) - axes[0, 1].set_title("Ground Truth") - axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 0].set_title("Prediction w/o edge features") - axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 1].set_title("Prediction with edge features") - for a in axes.ravel(): - a.set_xticks(()) - a.set_yticks(()) - plt.show() - - print "DONE" - - -""" - - - - -""" \ No newline at end of file diff --git a/pystruct/inference/__init__.py b/pystruct/inference/__init__.py index b8a9f1e4..c6460aff 100644 --- a/pystruct/inference/__init__.py +++ b/pystruct/inference/__init__.py @@ -1,8 +1,10 @@ from .inference_methods import (inference_qpbo, inference_lp, inference_ad3, inference_ogm, - inference_dispatch, get_installed) + inference_dispatch, get_installed, + inference_ad3plus, InferenceException) from .common import compute_energy __all__ = ["inference_qpbo", "inference_lp", "inference_ad3", "inference_dispatch", "get_installed", "compute_energy", - "inference_ogm"] + "inference_ogm", + "inference_ad3plus", "InferenceException"] diff --git a/pystruct/inference/inference_methods.py b/pystruct/inference/inference_methods.py index 31c5fa61..0f80e9ef 100644 --- a/pystruct/inference/inference_methods.py +++ b/pystruct/inference/inference_methods.py @@ -6,7 +6,7 @@ def get_installed(method_filter=None): if method_filter is None: - method_filter = ["max-product", 'ad3', 'qpbo', 'ogm', 'lp'] + method_filter = ["max-product", 'ad3', 'ad3+', 'qpbo', 'ogm', 'lp'] installed = [] unary = np.zeros((1, 1)) @@ -20,6 +20,12 @@ def get_installed(method_filter=None): pass return installed +class InferenceException(Exception): + """ + When inference status is fractional or unsolved, this exception can be raised. + The exception message is the solver status. + """ + pass def inference_dispatch(unary_potentials, pairwise_potentials, edges, inference_method, return_energy=False, **kwargs): @@ -88,6 +94,9 @@ def inference_dispatch(unary_potentials, pairwise_potentials, edges, elif inference_method == "ad3": return inference_ad3(unary_potentials, pairwise_potentials, edges, return_energy=return_energy, **kwargs) + elif inference_method == "ad3+": + return inference_ad3plus(unary_potentials, pairwise_potentials, edges, + return_energy=return_energy, **kwargs) elif inference_method == "ogm": return inference_ogm(unary_potentials, pairwise_potentials, edges, return_energy=return_energy, **kwargs) @@ -370,6 +379,31 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, n_states, pairwise_potentials = \ _validate_params(unary_potentials, pairwise_potentials, edges) unaries = unary_potentials.reshape(-1, n_states) + res = ad3.general_graph(unaries, edges, pairwise_potentials, verbose=verbose, + n_iterations=4000, exact=branch_and_bound) + unary_marginals, pairwise_marginals, energy, solver_status = res + if verbose: + print(solver_status[0]) + + if solver_status in ["fractional", "unsolved"] and relaxed: + unary_marginals = unary_marginals.reshape(unary_potentials.shape) + y = (unary_marginals, pairwise_marginals) + #print solver_status, pairwise_marginals + else: + y = np.argmax(unary_marginals, axis=-1) + if return_energy: + return y, -energy + return y + +def inference_ad3plus(unary_potentials, pairwise_potentials, edges, relaxed=False, + verbose=0, return_energy=False, branch_and_bound=False, + constraints=None, + inference_exception=None, + nodetype=None): + import ad3 + n_states, pairwise_potentials = \ + _validate_params(unary_potentials, pairwise_potentials, edges) + unaries = unary_potentials.reshape(-1, n_states) if constraints or nodetype: res = ad3.general_constrained_graph(unaries, edges, pairwise_potentials, constraints, verbose=verbose, n_iterations=4000, exact=branch_and_bound, nodetype=nodetype) @@ -380,20 +414,18 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, if verbose: print(solver_status[0]) - if solver_status in ["fractional", "unsolved"] and relaxed: + if relaxed and solver_status in ["fractional", "unsolved"]: unary_marginals = unary_marginals.reshape(unary_potentials.shape) y = (unary_marginals, pairwise_marginals) #print solver_status, pairwise_marginals else: - if nodetype: - y = ad3.getY_from_typedmarginals(unary_marginals, nodetype) - else: - y = np.argmax(unary_marginals, axis=-1) + if inference_exception and solver_status in ["fractional", "unsolved"]: + raise InferenceException(solver_status) + y = np.argmax(unary_marginals, axis=-1) if return_energy: return y, -energy return y - def inference_unaries(unary_potentials, pairwise_potentials, edges, verbose=0, **kwargs): """Inference that only uses unary potentials. diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index d427c281..a9603479 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -104,6 +104,8 @@ def _set_size_joint_feature(self): We have: - 1 weight per node feature per label per node type - 1 weight per edge feature per label of node1 type, per label of node2 type + + NOTE: for now, a typ1, typ2 type of edge with 0 features is simply ignored. While it could get a state x state matrix of weights """ if self.l_n_features: self.size_unaries = sum( n_states * n_features for n_states, n_features in zip(self.l_n_states, self.l_n_features) ) @@ -111,14 +113,12 @@ def _set_size_joint_feature(self): self.size_pairwise = 0 #detailed non-optimized computation to make things clear for typ1,typ2 in self._iter_type_pairs(): self.size_pairwise += self.a_n_edge_features[typ1,typ2] * self.l_n_states[typ1] * self.l_n_states[typ2] - #print "\t %d = %d x %d x %d"%(self.a_n_edge_features[typ1,typ2] * self.l_n_states[typ1] * self.l_n_states[typ2], self.a_n_edge_features[typ1,typ2] , self.l_n_states[typ1] , self.l_n_states[typ2]) + self.size_joint_feature = self.size_unaries + self.size_pairwise - #print "size = ", self.size_unaries, " + " , self.size_pairwise - def __repr__(self): - return ("%s(n_states: %d, inference_method: %s, n_features: %d, " - "n_edge_features: %d)" + return ("%s(n_states: %s, inference_method: %s, n_features: %s, " + "n_edge_features: %s)" % (type(self).__name__, self.l_n_states, self.inference_method, self.l_n_features, self.a_n_edge_features)) @@ -200,7 +200,7 @@ def _get_pairwise_potentials(self, x, w): Returns ------- - pairwise : ndarray, shape=(n_states, n_states) + pairwise : ndarray, shape=(n_edges, n_states, n_states) Pairwise weights. """ self._check_size_w(w) @@ -213,28 +213,7 @@ def _get_pairwise_potentials(self, x, w): wpw = w[self.size_unaries:] a_edges_states_states = np.zeros((n_edges_total, self._n_states, self._n_states), dtype=w.dtype) -# i_w, i_edges, i_states1, i_states2 = 0, 0, 0, 0 -# # for (typ1, typ2), edge_features, edgetype_start_index in zip(self._iter_type_pairs(), l_edge_features, self._l_edgetype_start_index): -# for (typ1, typ2), edge_features in zip(self._iter_type_pairs(), l_edge_features): -# if edge_features is None: continue -# -# n_edges, n_features = edge_features.shape -# n_states1 = self.l_n_states[typ1] -# n_states2 = self.l_n_states[typ2] -# i_w_stop = i_w + self.a_n_edge_features[typ1,typ2] * n_states1 * n_states2 -# i_edges_stop = i_edges + n_edges -# i_states1_stop = i_states1 + n_states1 -# i_states2_stop = i_states2 + n_states2 -# -# pw_typ_typ = wpw[i_w:i_w_stop].reshape(n_features, -1) # n_states1*n_states2 x nb_feat -# pot_typ_typ = np.dot(edge_features, pw_typ_typ).reshape(n_edges, n_states1, n_states2) -# print "pot_typ_typ.shape ", pot_typ_typ.shape -# a_edges_states_states[ i_edges:i_edges_stop, i_states1:i_states1_stop , i_states2:i_states2_stop ] = pot_typ_typ -# -# i_w, i_edges, i_states1, i_states2 = i_w_stop, i_edges_stop, i_states1_stop, i_states2_stop - i_edges = 0 - #print map(len, [self._cache_pairwise_potentials, l_edge_features, l_edge_nb]) for ((n_features, n_states1, n_states2, i_states1, i_states1_stop, i_states2, i_states2_stop, i_w, i_w_stop) , edge_features, n_edges) in zip(self._cache_pairwise_potentials, l_edge_features, l_edge_nb): @@ -243,9 +222,6 @@ def _get_pairwise_potentials(self, x, w): if not edge_features is None: pw_typ_typ = wpw[i_w:i_w_stop].reshape(n_features, -1) # n_states1*n_states2 x nb_feat pot_typ_typ = np.dot(edge_features, pw_typ_typ).reshape(n_edges, n_states1, n_states2) -# print i_states1,i_states1_stop , i_states2,i_states2_stop, n_states1, n_states2 -# print "a_edges_states_states.shape ", a_edges_states_states.shape -# print "a_edges_states_states[ ].shape ", a_edges_states_states[ i_edges:i_edges_stop, i_states1:i_states1_stop , i_states2:i_states2_stop ].shape a_edges_states_states[ i_edges:i_edges_stop, i_states1:i_states1_stop , i_states2:i_states2_stop ] = pot_typ_typ i_edges = i_edges_stop @@ -293,15 +269,7 @@ def joint_feature(self, x, y): l_n_edges = [edges.shape[0] for edges in self._get_edges(x, True)] n_nodes = sum(l_n_nodes) n_edges = sum(l_n_edges) - if False: - print - print type(y) - print "l_n_nodes = ", l_n_nodes - for nf in l_node_features: print "nf.shape ", None if nf is None else nf.shape, - print - print "l_n_edges = ", l_n_edges - for ef in l_edge_features: print "ef.shape ", None if ef is None else ef.shape, - print + if isinstance(y, tuple): #print "y=", `y` # y is result of relaxation, tuple of unary and pairwise marginals @@ -313,23 +281,15 @@ def joint_feature(self, x, y): #each type is assigned a range of columns, each starting at self._a_state_startindex_by_typ[ ] #in the arnge column I is for state i of that type unary_marginals = np.zeros((n_nodes, self._n_states), dtype=np.int) + i_start = 0 - #print self.l_n_states, self._l_type_startindex, y -# print "l_node_features shapes", map(lambda x: x.shape, l_node_features) -# print "y.shape", y.shape -# print "y", y.ravel() for node_features, typ_start_index in zip(l_node_features, self._l_type_startindex): if node_features is None: continue i_stop = i_start + node_features.shape[0] -# print "typ_start_index ", typ_start_index -# print "y. ", y.shape, i_start, i_stop -# print y[i_start:i_stop].ravel() - unary_marginals[ :, typ_start_index + y[i_start:i_stop] ] unary_marginals[ np.ogrid[i_start:i_stop] - , typ_start_index + y[i_start:i_stop] + , y[i_start:i_stop] ] = 1 i_start = i_stop - #print "--- unary_marginals \n", `unary_marginals` ## pairwise #same thing, but the type of an edge is a pair of node types @@ -338,16 +298,16 @@ def joint_feature(self, x, y): i_start = 0 for (typ1, typ2), edges, edgetype_start_index in zip(self._iter_type_pairs(), l_edges, self._l_edgetype_start_index): if edges is None: continue - #the label of those pairs of nodes - y1 = y[node_offset_by_typ[typ1] + edges[:,0]] - y2 = y[node_offset_by_typ[typ2] + edges[:,1]] + y1 = y[node_offset_by_typ[typ1] + edges[:,0]] - self._l_type_startindex[typ1] + assert (0<=y1).all() and (y1 <= self.l_n_states[typ1]).all() + y2 = y[node_offset_by_typ[typ2] + edges[:,1]] - self._l_type_startindex[typ2] + assert (0<=y2).all() and (y2 <= self.l_n_states[typ2]).all() #set the 1s where they should i_stop = i_start + edges.shape[0] pw[ np.ogrid[i_start:i_stop] , edgetype_start_index + self.l_n_states[typ2] * y1 + y2 ] = 1 i_start = i_stop - #print "--- pw = \n", `pw` assert i_start == n_edges #UNARY @@ -360,38 +320,30 @@ def joint_feature(self, x, y): , _a_feature_slice] = node_features i_start = i_stop assert i_start == n_nodes - #print "--- all_node_features =\n", `all_node_features` unaries_acc = np.dot(unary_marginals.T, all_node_features) # node_states x sum_of_features matrix - #print "--- unaries_acc =\n", `unaries_acc` #assign the edges feature to the right range of columns, depending on edge type all_edge_features = np.zeros( (n_edges, self._n_edge_features) ) i_start = 0 i_col_start = 0 - for edge_features in l_edge_features: - if edge_features is None: continue - nb_edges, nb_features = edge_features.shape - i_stop = i_start + nb_edges - i_col_stop = i_col_start + nb_features - all_edge_features[ i_start:i_stop - , i_col_start:i_col_stop ] = edge_features - i_col_start = i_col_stop - i_start = i_stop - #print "--- all_edge_features =\n", `all_edge_features` - - #print all_edge_features.T.shape, pw.shape + for edge_features, n_feat in zip(l_edge_features, self.a_n_edge_features.ravel()): + i_col_stop = i_col_start + n_feat - pairwise_acc = np.dot(all_edge_features.T, pw) # sum_of_features x edge_states - - -# print '-'*30 -# print np.dot(pw.T, all_edge_features).T -# print '-'*30 + if not edge_features is None: + nb_edges = edge_features.shape[0] + i_stop = i_start + nb_edges + all_edge_features[ i_start:i_stop + , i_col_start:i_col_stop ] = edge_features + i_start = i_stop + i_col_start = i_col_stop - #easier to read... :-( pairwise_acc = np.dot(pw.T, all_edge_features) # sum_of_features x edge_states - #print "--- pairwise_acc.shape = ", pairwise_acc.shape - #print "--- pairwise_acc =\n", `pairwise_acc` +# if False: +# np.set_printoptions(precision=3, linewidth=9999) +# print "all_edge_features (edgexfeat) \n", `all_edge_features` +# print "pw (edgexstate)\n", `pw` + pairwise_acc = np.dot(all_edge_features.T, pw) # sum_of_features x edge_states +# This forced symetry / antisymetry is not supported for now # for i in self.symmetric_edge_features: # pw_ = pw[i].reshape(self.n_states, self.n_states) # pw[i] = (pw_ + pw_.T).ravel() / 2. @@ -400,33 +352,19 @@ def joint_feature(self, x, y): # pw_ = pw[i].reshape(self.n_states, self.n_states) # pw[i] = (pw_ - pw_.T).ravel() / 2. - -# print `unaries_acc` -# print "unaries_acc.size = ", unaries_acc.size - #we need to linearize it, while keeping only meaningful data unaries_acc_ravelled = self._block_ravel(unaries_acc, [(0,0)]+zip(np.cumsum(self.l_n_states), np.cumsum(self.l_n_features))) - #print "--- unaries_acc_ravelled =\n", `unaries_acc_ravelled` assert len(unaries_acc_ravelled) == self.size_unaries L1 = np.cumsum(self.a_n_edge_features.ravel()) L2 = np.cumsum([self.l_n_states[typ1] * self.l_n_states[typ2] for typ1, typ2 in self._iter_type_pairs() ]) -# easier to read... aux=L1; L1=L2; L2=aux pairwise_acc_ravelled = self._block_ravel(pairwise_acc, [(0,0)]+zip(L1,L2)) - #print "--- pairwise_acc_ravelled =\n", `pairwise_acc_ravelled` assert len(pairwise_acc_ravelled) == self.size_pairwise - -# print `unaries_acc_ravelled` -# print "unaries_acc_ravelled.size = ", unaries_acc_ravelled.size -# print "unaries_acc_ravelled.shape = ", unaries_acc_ravelled.shape - -# print "pairwise_acc_ravelled.size = ", pairwise_acc_ravelled.size -# print "pairwise_acc_ravelled.shape = ", pairwise_acc_ravelled.shape -# print `pairwise_acc_ravelled` joint_feature_vector = np.hstack([unaries_acc_ravelled, pairwise_acc_ravelled]) assert joint_feature_vector.shape[0] == self.size_joint_feature, (joint_feature_vector.shape[0], self.size_joint_feature) + return joint_feature_vector diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index f9bb3b00..ed91f717 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -25,12 +25,16 @@ """ import numpy as np +import random from .base import StructuredModel from ..inference import inference_dispatch, get_installed from .utils import loss_augment_unaries +class InconsistentLabel(Exception): + pass + class TypedCRF(StructuredModel): """Abstract base class""" def __init__(self @@ -47,6 +51,7 @@ def __init__(self inference_method = get_installed(['ad3', 'max-product', 'lp'])[0] self.inference_method = inference_method self.inference_calls = 0 + self.inference_exception = False #if inference cannot be done, raises an exception if len(l_n_states) != n_types: raise ValueError("Expected 1 number of states per node type.") @@ -80,7 +85,8 @@ def __init__(self #internal stuff #when putting features in a single sequence, index of 1st state for type i self._l_type_startindex = [ sum(self.l_n_states[:i]) for i in range(self.n_types)] - + self._l_type_startindex.append(self._n_states) #convenience + #when putting states in a single sequence, index of 1st feature for type i (is at Ith position) #we store the slice objects self._a_feature_slice_by_typ = np.array([ slice(sum(self.l_n_features[:i]), sum(self.l_n_features[:i+1])) for i in range(self.n_types)]) @@ -102,7 +108,14 @@ def initialize(self, X, Y=None): else: self._check_size_x(X) self._check_size_xy(X, Y) - + + def setInferenceException(self, bRaiseExceptionWhenInferenceNotSuccessful): + """ + set exception on or off when inference canoot be done. + """ + self.inference_exception = bRaiseExceptionWhenInferenceNotSuccessful + return self.inference_exception + def _set_size_joint_feature(self): """ We have: @@ -158,14 +171,16 @@ def _check_size_xy(self, X, Y): if Y.shape[0] != nb_nodes: raise ValueError("Expected 1 label for each of the %d nodes. Gopt %d labels."%(nb_nodes, Y.shape[0])) - i_start = 0 + i_start = 0 for typ, nf, n_states in zip(range(self.n_types), l_node_features, self.l_n_states): nb_nodes = nf.shape[0] Y_typ = Y[i_start:i_start+nb_nodes] if np.min(Y_typ) < 0: raise ValueError("Got a negative label for type %d"%typ) - if np.max(Y_typ) >= n_states: - raise ValueError("Got a label outside of [0, %d] for type %d: %s"%(n_states-1, typ, Y_typ)) +# if np.max(Y_typ) >= n_states: +# raise ValueError("Got a label outside of [0, %d] for type %d: %s"%(n_states-1, typ, Y_typ)) + if np.min(Y_typ) < self._l_type_startindex[typ] : raise InconsistentLabel("labels of type %d start at %d"%(typ, self._l_type_startindex[typ])) + if np.max(Y_typ) >= self._l_type_startindex[typ+1]: raise InconsistentLabel("labels of type %d end at %d"%(typ, self._l_type_startindex[typ+1]-1)) i_start = i_start + nb_nodes @@ -190,7 +205,7 @@ def _index_all_edges(self, x): return all edges as a single 2-column matrix, taking care of node indices!! """ n_edges_total = sum(0 if e is None else e.shape[0] for e in x[1]) - all_edges = np.zeros((n_edges_total, 2), dtype=np.int32) + all_edges = np.zeros((n_edges_total, 2), dtype=np.int) node_offset_by_typ = np.cumsum([0]+[0 if n is None else n.shape[0] for n in x[0]]) i_start = 0 @@ -213,19 +228,6 @@ def _iter_type_pairs(self): yield (typ1, typ2) raise StopIteration -# -# def _get_unary_potentials_slow(self, x, w): -# self._check_size_w(w) -# self._check_size_x(x) -# l_node_features = self._get_node_features(x) -# a_nodes_features = scipy.sparse.block_diag(l_node_features) #.toarray() -# w_unaries = w[:self.size_unaries] -# l_w_block = [] -# for ((i_w,i_w2), (n_states, n_features)) in self._cache_unary_potentials: -# unary_params = w_unaries[i_w:i_w2].reshape(n_states, n_features) -# l_w_block.append(unary_params.T) -# a_features_states = scipy.sparse.block_diag(l_w_block) -# return a_nodes_features.dot(a_features_states).toarray() def _get_unary_potentials_initialize(self): """ @@ -233,7 +235,6 @@ def _get_unary_potentials_initialize(self): """ self._cache_unary_potentials = list() - #l_w_block = [] i_w, i_states = 0, 0 for n_states, n_features in zip(self.l_n_states, self.l_n_features): i_w2 = i_w + n_states*n_features #number of weights for the type @@ -259,28 +260,10 @@ def _get_unary_potentials(self, x, w): """ self._check_size_w(w) l_node_features = self._get_node_features(x) - #code for single type CRF - # unary_params = w[:self.n_states * self.n_features].reshape( - # self.n_states, self.n_features) - # return np.dot(features, unary_params.T) - #self.size_unaries == sum( n_states * n_features for n_states, n_features in zip(self.l_n_states, self.l_n_features) ) w_unaries = w[:self.size_unaries] a_nodes_states = np.zeros((sum(nf.shape[0] for nf in l_node_features) , self._n_states), dtype=w.dtype) -# #we work type by type and assemble the unaries -# #"irrelevant" unaries (i.e. for state not applicable to a type, will get a 0 -# i_w, i_nodes, i_states = 0, 0, 0 -# for features, n_states, n_features in zip(l_node_features, self.l_n_states, self.l_n_features): -# i_w2 = i_w + n_states*n_features #number of weights for the type -# i_nodes2 = i_nodes + features.shape[0] #number of nodes of that type -# i_states2 = i_states + n_states #number of state of that type -# w_unaries_type = w_unaries[i_w:i_w2] #range for weights for that type -# #back to "usual" code! -# unary_params = w_unaries_type.reshape(n_states, n_features) -# #apart that we fill a sub-part of the unaries matrix -# a_nodes_states[i_nodes:i_nodes2, i_states:i_states2] = np.dot(features, unary_params.T) -# i_w, i_nodes, i_states = i_w2, i_nodes2, i_states2 i_nodes = 0 for features, ((i_w,i_w2), (i_states, i_states2), (n_states, n_features)) in zip(l_node_features, self._cache_unary_potentials): i_nodes2 = i_nodes + features.shape[0] #number of nodes of that type @@ -348,53 +331,37 @@ def loss_augmented_inference(self, x, y, w, relaxed=False, l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] nodetype_data = (l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type -# print "pairwise_potentials ", `pairwise_potentials` -# print "pairwise_potentials.shape ", pairwise_potentials.shape -# print "flat_edges = ", `flat_edges` -# print "flat_edges.shape = ", flat_edges.shape -# print " nb non zero = ", len(np.flatnonzero(pairwise_potentials)) - -# print "loss_inference" -# print " UP ", show(unary_potentials) -# print " PP ", show(pairwise_potentials) -# print " E ", show(flat_edges) - Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, self.inference_method, relaxed=relaxed, return_energy=return_energy, nodetype=nodetype_data) - #print " LAI->", show(Y_pred) - -# print "=====", Y_pred.shape - if isinstance(Y_pred, tuple): - import ad3 - unary_marginals, pairwise_marginals = Y_pred - _Y_pred = ad3.getY_from_typedmarginals(unary_marginals, nodetype_data) - else: - try: - self._check_size_xy(x, Y_pred) - except ValueError as e: - print "Y_pred is BAD, FIXING IT WITH RANDOM VALUES" - Y_pred = self.fix_Y_at_random(x, Y_pred) + #if self.inference_calls % 1000 == 0: print "%d inference calls"%self.inference_calls - if self.inference_calls % 1000 == 0: print "%d inference calls"%self.inference_calls - - #print "Y_pred ", `Y_pred` - + try: + if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) + except InconsistentLabel: + #the inference engine predicted inconsistent labels + #with ad3+ this should never occur + assert self.inference_method != "ad3+", "Internal error in AD3+: inconsistent labels" + Y_pred = self.fix_Y_at_random(x, Y_pred) + return Y_pred def fix_Y_at_random(self, x, Y_pred): - import random + print "\tY is BAD, FIXING IT AT RANDOM", `Y_pred` + l_node_features = self._get_node_features(x, True) i_start = 0 - for nf, n_states in zip(l_node_features, self.l_n_states): + for typ, (nf, n_states) in enumerate(zip(l_node_features, self.l_n_states)): nb_nodes = nf.shape[0] if nb_nodes: Y_typ = Y_pred[i_start:i_start+nb_nodes] - if np.max(Y_typ) >= n_states: + typ_start = self._l_type_startindex[typ] + typ_end = self._l_type_startindex[typ+1] + if np.min(Y_typ) < typ_start or typ_end <= np.max(Y_typ): for i in range(nb_nodes): - if Y_pred[i_start+i] >= n_states: Y_pred[i_start+i] = random.randint(0, n_states-1) + if Y_pred[i_start+i] < typ_start or typ_end <= Y_pred[i_start+i]: Y_pred[i_start+i] = random.randint(typ_start, typ_end-1) i_start = i_start + nb_nodes self._check_size_xy(x, Y_pred) return Y_pred @@ -453,29 +420,32 @@ def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] nodetype_data=(l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type - if constraints: -# print "inference" -# print " UP ", show(unary_potentials) -# print " PP ", show(pairwise_potentials) -# print " E ", show(flat_edges) - + if self.inference_method == "ad3+": + #preferred method for TypedCRF inferences (called by the 'predict' method of the learner) Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy, constraints=constraints, - nodetype=nodetype_data) - #print " I ->", show(Y_pred) + self.inference_method, relaxed=relaxed, + return_energy=return_energy, + constraints=constraints, + nodetype=nodetype_data, + inference_exception=self.inference_exception) #<-- else: - Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy, - nodetype=nodetype_data) -# print "===", Y_pred.shape -# -# try: -# self._check_size_xy(x, Y_pred) -# except ValueError as e: -# print "\tY is BAD, FIXING IT AT RANDOM" -# Y_pred = self.fix_Y_at_random(x, Y_pred) + if constraints: + Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, + self.inference_method, relaxed=relaxed, + return_energy=return_energy, + constraints=constraints, #<-- + nodetype=nodetype_data) #<-- + else: + Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, + self.inference_method, relaxed=relaxed, + return_energy=return_energy, + nodetype=nodetype_data) #<-- + + try: + if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) + except: + Y_pred = self.fix_Y_at_random(x, Y_pred) + if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) return Y_pred From cf50735636a02b512c6e6174fc14e7846ed35853 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 6 Feb 2017 14:27:01 +0100 Subject: [PATCH 035/155] added inference_ad3plus method and InferenceException exception --- pystruct/inference/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pystruct/inference/__init__.py b/pystruct/inference/__init__.py index c6460aff..041432ee 100644 --- a/pystruct/inference/__init__.py +++ b/pystruct/inference/__init__.py @@ -7,4 +7,4 @@ __all__ = ["inference_qpbo", "inference_lp", "inference_ad3", "inference_dispatch", "get_installed", "compute_energy", "inference_ogm", - "inference_ad3plus", "InferenceException"] + "inference_ad3plus", "InferenceException"] \ No newline at end of file From d03703599abdec5161ca0912ebbeb03ef78afb5a Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 6 Feb 2017 14:29:00 +0100 Subject: [PATCH 036/155] new inference_ad3plus method InferenceException exception for the new method --- pystruct/inference/inference_methods.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pystruct/inference/inference_methods.py b/pystruct/inference/inference_methods.py index 0f80e9ef..55033c5f 100644 --- a/pystruct/inference/inference_methods.py +++ b/pystruct/inference/inference_methods.py @@ -23,6 +23,7 @@ def get_installed(method_filter=None): class InferenceException(Exception): """ When inference status is fractional or unsolved, this exception can be raised. + (If relaxed is not True and if an inference exception is requested by the calling code) The exception message is the solver status. """ pass From 36b03cdddd0274eb7d45954fcf1ed9729299291e Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 6 Feb 2017 14:34:03 +0100 Subject: [PATCH 037/155] Class to suport multi-type CRF graphs --- pystruct/models/node_type_edge_feature_graph_crf.py | 3 +++ pystruct/models/typed_crf.py | 2 ++ 2 files changed, 5 insertions(+) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index a9603479..36b3f68e 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -52,6 +52,9 @@ class NodeTypeEdgeFeatureGraphCRF(TypedCRF): a_n_edge_features: an array of shape (n_types, n_types) given the number of features as a function of the node types + NOTE: there should always be at least 1 feature for any pairs of types with some edge of that type in the graph. + Said differently, if you put 0 somewhere in that matrix, do not create any egde corresponding to that type of edge!! + class_weight : None, or list of array-like Class weights. If a list of array-like is passed, the Ith one must have length equal to l_n_states[i] None means equal class weights (across node types) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index ed91f717..c6330843 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -2,6 +2,8 @@ """ CRF with different types of nodes + + NOTE: this is an abstract class. Do not use directly. Copyright Xerox(C) 2017 JL. Meunier From 32ec5a7022c8aa0790da1ba9630403848a99f141 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 7 Feb 2017 09:40:14 +0100 Subject: [PATCH 038/155] fixed method doc --- pystruct/inference/inference_methods.py | 71 +++++++++++++++++++------ 1 file changed, 54 insertions(+), 17 deletions(-) diff --git a/pystruct/inference/inference_methods.py b/pystruct/inference/inference_methods.py index 55033c5f..5d384a8d 100644 --- a/pystruct/inference/inference_methods.py +++ b/pystruct/inference/inference_methods.py @@ -320,9 +320,7 @@ def inference_lp(unary_potentials, pairwise_potentials, edges, relaxed=False, def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, - verbose=0, return_energy=False, branch_and_bound=False, - constraints=None, - nodetype=None): + verbose=0, return_energy=False, branch_and_bound=False): """Inference with AD3 dual decomposition subgradient solver. Parameters @@ -356,20 +354,6 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, Whether to attempt to produce an integral solution using branch-and-bound. - constraints : list of logical constraints or None (default:=None) - A logical constraint is tuple like ( , , , ) - where: - - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' - - unaries is a list of the index of each unary involved in this constraint - - states is a list of unary states (class), 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. - - negated is a list of boolean indicating if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list - - NOTE: this hard logic constraint mechanism has been developed for the EU project READ, by JL Meunier (Xerox), in November 2016. - The READ project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. - - nodetype : internal use for NodeTypeEdgeFeatureGraphCRF model - NOTE: developed for the EU project READ (grant agreement No 674943), by JL Meunier (Xerox), in Q1 2017. - Returns ------- labels : nd-array @@ -401,6 +385,59 @@ def inference_ad3plus(unary_potentials, pairwise_potentials, edges, relaxed=Fals constraints=None, inference_exception=None, nodetype=None): + """Inference with AD3 dual decomposition subgradient solver. + + Parameters + ---------- + unary_potentials : nd-array, shape (n_nodes, n_states) + Unary potentials of energy function. + + pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + Pairwise potentials of energy function. + If the first case, edge potentials are assumed to be the same for all edges. + In the second case, the sequence needs to correspond to the edges. + + edges : nd-array, shape (n_edges, 2) + Graph edges for pairwise potentials, given as pair of node indices. As + pairwise potentials are not assumed to be symmetric, the direction of + the edge matters. + + relaxed : bool (default=False) + Whether to return the relaxed solution (``True``) or round to the next + integer solution (``False``). + + verbose : int (default=0) + Degree of verbosity for solver. + + return_energy : bool (default=False) + Additionally return the energy of the returned solution (according to + the solver). If relaxed=False, this is the energy of the relaxed, not + the rounded solution. + + branch_and_bound : bool (default=False) + Whether to attempt to produce an integral solution using + branch-and-bound. + + constraints : list of logical constraints or None (default:=None) + A logical constraint is tuple like ( , , , ) + where: + - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - unaries is a list of the index of each unary involved in this constraint + - states is a list of unary states (class), 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. + - negated is a list of boolean indicating if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list + + NOTE: this hard logic constraint mechanism has been developed for the EU project READ, by JL Meunier (Xerox), in November 2016. + The READ project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. + + nodetype : internal use for NodeTypeEdgeFeatureGraphCRF model + NOTE: developed for the EU project READ (grant agreement No 674943), by JL Meunier (Xerox), in Q1 2017. + + Returns + ------- + labels : nd-array + Approximate (usually) MAP variable assignment. + If relaxed=False, this is a tuple of unary and edge 'marginals'. + """ import ad3 n_states, pairwise_potentials = \ _validate_params(unary_potentials, pairwise_potentials, edges) From a81dd9a240e94e354d73c4c03cf4ec39a9d1c4ba Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 7 Feb 2017 09:40:39 +0100 Subject: [PATCH 039/155] declare TypedCRF --- pystruct/models/__init__.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pystruct/models/__init__.py b/pystruct/models/__init__.py index 00ebe47f..8b02ab64 100644 --- a/pystruct/models/__init__.py +++ b/pystruct/models/__init__.py @@ -9,11 +9,12 @@ from .unstructured_svm import BinaryClf, MultiClassClf from .multilabel_svm import MultiLabelClf from .edge_feature_graph_crf import EdgeFeatureGraphCRF +from .typed_crf import TypedCRF from .node_type_edge_feature_graph_crf import NodeTypeEdgeFeatureGraphCRF __all__ = ["StructuredModel", "CRF", "GridCRF", "GraphCRF", "DirectionalGridCRF", "BinaryClf", "LatentGridCRF", "LatentDirectionalGridCRF", "MultiClassClf", "LatentGraphCRF", "MultiLabelClf", "ChainCRF", "LatentNodeCRF", "EdgeFeatureGraphCRF", - "EdgeFeatureLatentNodeCRF", "NodeTypeEdgeFeatureGraphCRF", - "NodeTypeEdgeFeatureGraphCRF"] + "EdgeFeatureLatentNodeCRF", + "TypedCRF", "NodeTypeEdgeFeatureGraphCRF"] From 4fb9f522f8073d394c11f1c7203152521217c4ea Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 7 Feb 2017 09:41:54 +0100 Subject: [PATCH 040/155] change version number to 0.3.0 added me as author --- setup.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/setup.py b/setup.py index 22460fbc..6f4c2f95 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ include_dirs = [np.get_include()] setup(name="pystruct", - version="0.2.5", + version="0.3.0", install_requires=["ad3"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', @@ -19,9 +19,9 @@ 'pystruct.tests.test_utils'], include_package_data=True, description="Structured Learning and Prediction in Python", - author="Andreas Mueller", - author_email="t3kcit@gmail.com", - url="http://pystruct.github.io", + author="Andreas Mueller, Jean-Luc Meunier", + author_email="jean-luc.meunier@xrce.xerox.com", + url="https://github.com/jlmeunier/pystruct", license="BSD 2-clause", use_2to3=True, ext_modules=[Extension("pystruct.models.utils", ["src/utils.c"], From d9cc5656d389463b55b9a7c83c7f5954ea59c35e Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 7 Feb 2017 09:45:43 +0100 Subject: [PATCH 041/155] what's new in 0.3.0 --- CHANGELOG | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 2f68e86e..22c599d0 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -15,3 +15,8 @@ - Speed improvements in loss-augmented inference. - Renamed psi to joint_feature, as the joint feature function is sometimes also called phi, with psi referring to the energy. - Removed the GLPK dependency: now cvxopt is used to solve linear programs. + +0.3 +=== +- Added new model NodeTypeEdgeFeatureGraphCRF +- Added inference method ad3+ for new model and for supporting hard logic constraints in other CRF models \ No newline at end of file From e74165963e0014729b36a0df6668f0b589d9d82c Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 7 Feb 2017 10:13:23 +0100 Subject: [PATCH 042/155] v0.3.0 requiring ad3 2.1.0 --- pystruct/__init__.py | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pystruct/__init__.py b/pystruct/__init__.py index fe404ae5..493f7415 100644 --- a/pystruct/__init__.py +++ b/pystruct/__init__.py @@ -1 +1 @@ -__version__ = "0.2.5" +__version__ = "0.3.0" diff --git a/setup.py b/setup.py index 6f4c2f95..d3820795 100644 --- a/setup.py +++ b/setup.py @@ -11,7 +11,7 @@ setup(name="pystruct", version="0.3.0", - install_requires=["ad3"], + install_requires=["ad3>=2.1.0"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', 'pystruct.tests', 'pystruct.tests.test_learners', From 67aba718807f50636053f25ab1023b88adc0c71d Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 7 Feb 2017 10:18:45 +0100 Subject: [PATCH 043/155] fixed bug due to comment... --- pystruct/inference/inference_methods.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pystruct/inference/inference_methods.py b/pystruct/inference/inference_methods.py index 5d384a8d..0cf34435 100644 --- a/pystruct/inference/inference_methods.py +++ b/pystruct/inference/inference_methods.py @@ -385,7 +385,7 @@ def inference_ad3plus(unary_potentials, pairwise_potentials, edges, relaxed=Fals constraints=None, inference_exception=None, nodetype=None): - """Inference with AD3 dual decomposition subgradient solver. + """Inference with AD3 dual decomposition subgradient solver. Parameters ---------- From 144757e304d9cfa2615a710009b2ecb9d427ee85 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 8 Feb 2017 13:56:53 +0100 Subject: [PATCH 044/155] - ad3+ is the preferred and by default inference method - inference and loss_augmented_inference method moved to NodeTYpeEdgeFeatureCRF --- pystruct/models/typed_crf.py | 188 +---------------------------------- 1 file changed, 5 insertions(+), 183 deletions(-) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index c6330843..649d2306 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -27,11 +27,9 @@ """ import numpy as np -import random from .base import StructuredModel -from ..inference import inference_dispatch, get_installed -from .utils import loss_augment_unaries +from ..inference import get_installed class InconsistentLabel(Exception): @@ -50,7 +48,7 @@ def __init__(self if inference_method is None: # get first in list that is installed - inference_method = get_installed(['ad3', 'max-product', 'lp'])[0] + inference_method = get_installed(['ad3+', 'ad3', 'max-product', 'lp'])[0] self.inference_method = inference_method self.inference_calls = 0 self.inference_exception = False #if inference cannot be done, raises an exception @@ -162,6 +160,7 @@ def _check_size_x(self, x): raise ValueError("At least one edge starts from a non-existing node index: type %d to type %d"%(typ1,typ2)) if max(nodes2) >= l_node_features[typ2].shape[0]: raise ValueError("At least one edge points to a non-existing node index: type %d to type %d"%(typ1,typ2)) + return True def _check_size_xy(self, X, Y): if Y is None: return @@ -184,7 +183,7 @@ def _check_size_xy(self, X, Y): if np.min(Y_typ) < self._l_type_startindex[typ] : raise InconsistentLabel("labels of type %d start at %d"%(typ, self._l_type_startindex[typ])) if np.max(Y_typ) >= self._l_type_startindex[typ+1]: raise InconsistentLabel("labels of type %d end at %d"%(typ, self._l_type_startindex[typ+1]-1)) i_start = i_start + nb_nodes - + return True def _get_node_features(self, x, bClean=False): @@ -257,7 +256,7 @@ def _get_unary_potentials(self, x, w): Returns ------- - unary : ndarray, shape=(sum_over_types(n_states_of_type) + unary : ndarray, shape=( n_nodes, n_states ) Unary weights. """ self._check_size_w(w) @@ -274,180 +273,3 @@ def _get_unary_potentials(self, x, w): # nodes x features . features x states --> nodes x states return a_nodes_states - def loss_augmented_inference(self, x, y, w, relaxed=False, - return_energy=False): - """Loss-augmented Inference for x relative to y using parameters w. - - Finds (approximately) - armin_y_hat np.dot(w, joint_feature(x, y_hat)) + loss(y, y_hat) - using self.inference_method. - - - Parameters - ---------- - x : tuple - Instance of a graph with unary evidence. - x=(unaries, edges) - unaries are an nd-array of shape (n_nodes, n_features), - edges are an nd-array of shape (n_edges, 2) - - y : ndarray, shape (n_nodes,) - Ground truth labeling relative to which the loss - will be measured. - - w : ndarray, shape=(size_joint_feature,) - Parameters for the CRF energy function. - - relaxed : bool, default=False - Whether relaxed inference should be performed. - Only meaningful if inference method is 'lp' or 'ad3'. - By default fractional solutions are rounded. If relaxed=True, - fractional solutions are returned directly. - - return_energy : bool, default=False - Whether to return the energy of the solution (x, y) that was found. - - Returns - ------- - y_pred : ndarray or tuple - By default an inter ndarray of shape=(n_nodes) - of variable assignments for x is returned. - If ``relaxed=True`` and inference_method is ``lp`` or ``ad3``, - a tuple (unary_marginals, pairwise_marginals) - containing the relaxed inference result is returned. - unary marginals is an array of shape (n_nodes, n_states), - pairwise_marginals is an array of - shape (n_states, n_states) of accumulated pairwise marginals. - - """ -# print "y.shape ", y.shape - self.inference_calls += 1 - self._check_size_w(w) - unary_potentials = self._get_unary_potentials(x, w) - pairwise_potentials = self._get_pairwise_potentials(x, w) - flat_edges = self._index_all_edges(x) - - loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) - - - l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] - nodetype_data = (l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type - - Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy, - nodetype=nodetype_data) - - #if self.inference_calls % 1000 == 0: print "%d inference calls"%self.inference_calls - - try: - if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) - except InconsistentLabel: - #the inference engine predicted inconsistent labels - #with ad3+ this should never occur - assert self.inference_method != "ad3+", "Internal error in AD3+: inconsistent labels" - Y_pred = self.fix_Y_at_random(x, Y_pred) - - return Y_pred - - def fix_Y_at_random(self, x, Y_pred): - print "\tY is BAD, FIXING IT AT RANDOM", `Y_pred` - - l_node_features = self._get_node_features(x, True) - i_start = 0 - for typ, (nf, n_states) in enumerate(zip(l_node_features, self.l_n_states)): - nb_nodes = nf.shape[0] - if nb_nodes: - Y_typ = Y_pred[i_start:i_start+nb_nodes] - typ_start = self._l_type_startindex[typ] - typ_end = self._l_type_startindex[typ+1] - if np.min(Y_typ) < typ_start or typ_end <= np.max(Y_typ): - for i in range(nb_nodes): - if Y_pred[i_start+i] < typ_start or typ_end <= Y_pred[i_start+i]: Y_pred[i_start+i] = random.randint(typ_start, typ_end-1) - i_start = i_start + nb_nodes - self._check_size_xy(x, Y_pred) - return Y_pred - - def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): - """Inference for x using parameters w. - - Finds (approximately) - armin_y np.dot(w, joint_feature(x, y)) - using self.inference_method. - - - Parameters - ---------- - x : tuple - Instance of a graph with unary evidence. - x=(unaries, edges) - unaries are an nd-array of shape (n_nodes, n_states), - edges are an nd-array of shape (n_edges, 2) - - w : ndarray, shape=(size_joint_feature,) - Parameters for the CRF energy function. - - relaxed : bool, default=False - Whether relaxed inference should be performed. - Only meaningful if inference method is 'lp' or 'ad3'. - By default fractional solutions are rounded. If relaxed=True, - fractional solutions are returned directly. - - return_energy : bool, default=False - Whether to return the energy of the solution (x, y) that was found. - - constraints : None or list, default=False - hard logic constraints, if any - - Returns - ------- - y_pred : ndarray or tuple - By default an inter ndarray of shape=(width, height) - of variable assignments for x is returned. - If ``relaxed=True`` and inference_method is ``lp`` or ``ad3``, - a tuple (unary_marginals, pairwise_marginals) - containing the relaxed inference result is returned. - unary marginals is an array of shape (width, height, n_states), - pairwise_marginals is an array of - shape (n_states, n_states) of accumulated pairwise marginals. - - """ - self._check_size_w(w) - self.inference_calls += 1 - self.initialize(x) - unary_potentials = self._get_unary_potentials(x, w) - pairwise_potentials = self._get_pairwise_potentials(x, w) - flat_edges = self._index_all_edges(x) - - l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] - nodetype_data=(l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type - - if self.inference_method == "ad3+": - #preferred method for TypedCRF inferences (called by the 'predict' method of the learner) - Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy, - constraints=constraints, - nodetype=nodetype_data, - inference_exception=self.inference_exception) #<-- - else: - if constraints: - Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy, - constraints=constraints, #<-- - nodetype=nodetype_data) #<-- - else: - Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy, - nodetype=nodetype_data) #<-- - - try: - if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) - except: - Y_pred = self.fix_Y_at_random(x, Y_pred) - - if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) - - return Y_pred From cb5bc528b5138070ff41c7da431e112d611fd156 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 8 Feb 2017 14:01:43 +0100 Subject: [PATCH 045/155] - the 2 methods for inference are now in this module (TypedCRF is abstract class) - we tolerate all inference method at training time. Not sure it helps in any thing, actually. --- .../node_type_edge_feature_graph_crf.py | 190 +++++++++++++++++- 1 file changed, 189 insertions(+), 1 deletion(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index 36b3f68e..d027a74b 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -25,8 +25,13 @@ """ import numpy as np +import random + +from ..inference import inference_dispatch +from .utils import loss_augment_unaries + +from .typed_crf import TypedCRF, InconsistentLabel -from .typed_crf import TypedCRF class NodeTypeEdgeFeatureGraphCRF(TypedCRF): """ @@ -154,6 +159,7 @@ def _check_size_x(self, x): if edge_features is None: continue if edge_features.shape[1] != self.a_n_edge_features[typ1,typ2]: raise ValueError("Types %d x %d: bad number of edge features. expected %d got %d"%(typ1,typ2, self.a_n_edge_features[typ1,typ2], edge_features.shape[1])) + return True def _get_edge_features(self, x, bClean=False): if bClean: @@ -371,3 +377,185 @@ def joint_feature(self, x, y): return joint_feature_vector + def loss_augmented_inference(self, x, y, w, relaxed=False, + return_energy=False): + """Loss-augmented Inference for x relative to y using parameters w. + + Finds (approximately) + armin_y_hat np.dot(w, joint_feature(x, y_hat)) + loss(y, y_hat) + using self.inference_method. + + + Parameters + ---------- + x : tuple + Instance of a graph with unary evidence. + x=(unaries, edges) + unaries are an nd-array of shape (n_nodes, n_features), + edges are an nd-array of shape (n_edges, 2) + + y : ndarray, shape (n_nodes,) + Ground truth labeling relative to which the loss + will be measured. + + w : ndarray, shape=(size_joint_feature,) + Parameters for the CRF energy function. + + relaxed : bool, default=False + Whether relaxed inference should be performed. + Only meaningful if inference method is 'lp' or 'ad3'. + By default fractional solutions are rounded. If relaxed=True, + fractional solutions are returned directly. + + return_energy : bool, default=False + Whether to return the energy of the solution (x, y) that was found. + + Returns + ------- + y_pred : ndarray or tuple + By default an inter ndarray of shape=(n_nodes) + of variable assignments for x is returned. + If ``relaxed=True`` and inference_method is ``lp`` or ``ad3``, + a tuple (unary_marginals, pairwise_marginals) + containing the relaxed inference result is returned. + unary marginals is an array of shape (n_nodes, n_states), + pairwise_marginals is an array of + shape (n_states, n_states) of accumulated pairwise marginals. + + """ +# print "y.shape ", y.shape + self.inference_calls += 1 + self._check_size_w(w) + unary_potentials = self._get_unary_potentials(x, w) + pairwise_potentials = self._get_pairwise_potentials(x, w) + flat_edges = self._index_all_edges(x) + + loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) + + if self.inference_method == "ad3+": + l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] + nodetype_data = (l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type + + Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, + self.inference_method, relaxed=relaxed, + return_energy=return_energy, + nodetype=nodetype_data) + #with ad3+ this should never occur + assert self._check_size_xy(x, Y_pred), "Internal error in AD3+: inconsistent labels" + else: + Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, + self.inference_method, relaxed=relaxed, + return_energy=return_energy) + #no nodetype parameter! + #we may have inconsistent labels! + try: + if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) + except InconsistentLabel: + #the inference engine predicted inconsistent labels + Y_pred = self.fix_Y_at_random(x, Y_pred) + + #if self.inference_calls % 1000 == 0: print "%d inference calls"%self.inference_calls + + return Y_pred + + def fix_Y_at_random(self, x, Y_pred): + print "\tY is BAD, FIXING IT AT RANDOM", `Y_pred` + + l_node_features = self._get_node_features(x, True) + i_start = 0 + for typ, (nf, n_states) in enumerate(zip(l_node_features, self.l_n_states)): + nb_nodes = nf.shape[0] + if nb_nodes: + Y_typ = Y_pred[i_start:i_start+nb_nodes] + typ_start = self._l_type_startindex[typ] + typ_end = self._l_type_startindex[typ+1] + if np.min(Y_typ) < typ_start or typ_end <= np.max(Y_typ): + for i in range(nb_nodes): + if Y_pred[i_start+i] < typ_start or typ_end <= Y_pred[i_start+i]: Y_pred[i_start+i] = random.randint(typ_start, typ_end-1) + i_start = i_start + nb_nodes + self._check_size_xy(x, Y_pred) + return Y_pred + + def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): + """Inference for x using parameters w. + + Finds (approximately) + armin_y np.dot(w, joint_feature(x, y)) + using self.inference_method. + + + Parameters + ---------- + x : tuple + Instance of a graph with unary evidence. + x=(unaries, edges) + unaries are an nd-array of shape (n_nodes, n_states), + edges are an nd-array of shape (n_edges, 2) + + w : ndarray, shape=(size_joint_feature,) + Parameters for the CRF energy function. + + relaxed : bool, default=False + Whether relaxed inference should be performed. + Only meaningful if inference method is 'lp' or 'ad3'. + By default fractional solutions are rounded. If relaxed=True, + fractional solutions are returned directly. + + return_energy : bool, default=False + Whether to return the energy of the solution (x, y) that was found. + + constraints : None or list, default=False + hard logic constraints, if any + + Returns + ------- + y_pred : ndarray or tuple + By default an inter ndarray of shape=(width, height) + of variable assignments for x is returned. + If ``relaxed=True`` and inference_method is ``lp`` or ``ad3``, + a tuple (unary_marginals, pairwise_marginals) + containing the relaxed inference result is returned. + unary marginals is an array of shape (width, height, n_states), + pairwise_marginals is an array of + shape (n_states, n_states) of accumulated pairwise marginals. + + """ + self._check_size_w(w) + self.inference_calls += 1 + self.initialize(x) + unary_potentials = self._get_unary_potentials(x, w) + pairwise_potentials = self._get_pairwise_potentials(x, w) + flat_edges = self._index_all_edges(x) + + l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] + nodetype_data=(l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type + + if self.inference_method == "ad3+": + #preferred method for TypedCRF inferences (called by the 'predict' method of the learner) + Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, + self.inference_method, relaxed=relaxed, + return_energy=return_energy, + constraints=constraints, + nodetype=nodetype_data, + inference_exception=self.inference_exception) #<-- + else: + if constraints: + Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, + self.inference_method, relaxed=relaxed, + return_energy=return_energy, + constraints=constraints, #<-- + nodetype=nodetype_data) #<-- + else: + Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, + self.inference_method, relaxed=relaxed, + return_energy=return_energy, + nodetype=nodetype_data) #<-- + + try: + if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) + except: + Y_pred = self.fix_Y_at_random(x, Y_pred) + + if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) + + return Y_pred From 5e9efb5dc7fc58bf2694704ca18613c0a5bc030e Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 8 Feb 2017 14:04:09 +0100 Subject: [PATCH 046/155] - all inference methods are tolarated --- pystruct/models/node_type_edge_feature_graph_crf.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index d027a74b..e6c34359 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -543,13 +543,11 @@ def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, self.inference_method, relaxed=relaxed, return_energy=return_energy, - constraints=constraints, #<-- - nodetype=nodetype_data) #<-- + constraints=constraints) #<-- else: Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, self.inference_method, relaxed=relaxed, - return_energy=return_energy, - nodetype=nodetype_data) #<-- + return_energy=return_energy) #<-- try: if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) From a091b141d838e625c18661bb77c1e1dc03dd9f6c Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 8 Feb 2017 14:34:17 +0100 Subject: [PATCH 047/155] little fix v=0.3.1 --- pystruct/models/node_type_edge_feature_graph_crf.py | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index e6c34359..4c128578 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -441,7 +441,7 @@ def loss_augmented_inference(self, x, y, w, relaxed=False, return_energy=return_energy, nodetype=nodetype_data) #with ad3+ this should never occur - assert self._check_size_xy(x, Y_pred), "Internal error in AD3+: inconsistent labels" + if not isinstance(Y_pred, tuple): assert self._check_size_xy(x, Y_pred), "Internal error in AD3+: inconsistent labels" else: Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, self.inference_method, relaxed=relaxed, diff --git a/setup.py b/setup.py index d3820795..82ff95b4 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ include_dirs = [np.get_include()] setup(name="pystruct", - version="0.3.0", + version="0.3.1", install_requires=["ad3>=2.1.0"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', From 8fbcbf55922adcc6a39aa7556097ce1ec16a1d01 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 8 Feb 2017 14:36:54 +0100 Subject: [PATCH 048/155] v=0.3.1 !! --- pystruct/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pystruct/__init__.py b/pystruct/__init__.py index 493f7415..260c070a 100644 --- a/pystruct/__init__.py +++ b/pystruct/__init__.py @@ -1 +1 @@ -__version__ = "0.3.0" +__version__ = "0.3.1" From 3d4d4f14b3b3d5a878b11a8828fe868f36b06059 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 13 Feb 2017 10:11:23 +0100 Subject: [PATCH 049/155] in multitype mode, we pass a list of unaries instead of a big matrix for all types (with lots of 0s) --- pystruct/inference/inference_methods.py | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/pystruct/inference/inference_methods.py b/pystruct/inference/inference_methods.py index 0cf34435..090271a7 100644 --- a/pystruct/inference/inference_methods.py +++ b/pystruct/inference/inference_methods.py @@ -380,11 +380,10 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, return y, -energy return y -def inference_ad3plus(unary_potentials, pairwise_potentials, edges, relaxed=False, +def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges, relaxed=False, verbose=0, return_energy=False, branch_and_bound=False, constraints=None, - inference_exception=None, - nodetype=None): + inference_exception=None): """Inference with AD3 dual decomposition subgradient solver. Parameters @@ -439,31 +438,29 @@ def inference_ad3plus(unary_potentials, pairwise_potentials, edges, relaxed=Fals If relaxed=False, this is a tuple of unary and edge 'marginals'. """ import ad3 - n_states, pairwise_potentials = \ - _validate_params(unary_potentials, pairwise_potentials, edges) - unaries = unary_potentials.reshape(-1, n_states) - if constraints or nodetype: - res = ad3.general_constrained_graph(unaries, edges, pairwise_potentials, constraints, verbose=verbose, - n_iterations=4000, exact=branch_and_bound, nodetype=nodetype) - else: - res = ad3.general_graph(unaries, edges, pairwise_potentials, verbose=verbose, +# n_states, pairwise_potentials = \ +# _validate_params(unary_potentials, pairwise_potentials, edges) +# unaries = unary_potentials.reshape(-1, n_states) + res = ad3.general_constrained_graph(l_unary_potentials, l_edges, l_pairwise_potentials, constraints, verbose=verbose, n_iterations=4000, exact=branch_and_bound) + unary_marginals, pairwise_marginals, energy, solver_status = res if verbose: - print(solver_status[0]) + print(solver_status) if relaxed and solver_status in ["fractional", "unsolved"]: - unary_marginals = unary_marginals.reshape(unary_potentials.shape) y = (unary_marginals, pairwise_marginals) - #print solver_status, pairwise_marginals else: if inference_exception and solver_status in ["fractional", "unsolved"]: raise InferenceException(solver_status) y = np.argmax(unary_marginals, axis=-1) + if return_energy: return y, -energy return y + + def inference_unaries(unary_potentials, pairwise_potentials, edges, verbose=0, **kwargs): """Inference that only uses unary potentials. From 9dcbbbb0c4ffc1624c2b6017610c0592ea755bb6 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 13 Feb 2017 10:15:35 +0100 Subject: [PATCH 050/155] - ad3+ is the only inference method - a list of unary per type --- pystruct/models/typed_crf.py | 145 +++++++++++++++++++---------------- 1 file changed, 81 insertions(+), 64 deletions(-) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index 649d2306..323a352f 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -41,7 +41,7 @@ def __init__(self , n_types #how many node type? , l_n_states #how many labels per node type? , l_n_features #how many features per node type? - , inference_method="ad3" + , inference_method="ad3+" , l_class_weight=None): #class_weight per node type or None or None StructuredModel.__init__(self) @@ -62,9 +62,12 @@ def __init__(self self._n_states = sum(l_n_states) #total number of states self.l_n_features = l_n_features self._n_features = sum(self.l_n_features) #total number of (node) features + + #number of typextype states, or number of states per type of edge + self.l_n_edge_states = [ n1 * n2 for n1 in self.l_n_states for n2 in self.l_n_states ] - #Caching some heavily used values - self._get_unary_potentials_initialize() +# #Caching some heavily used values +# self._get_unary_potentials_initialize() #class weights: # either we get class weights for all types of nodes, or for none of them! @@ -73,38 +76,56 @@ def __init__(self raise ValueError("Expected 1 class weight list per node type.") for i, n_states in enumerate(self.l_n_states): if len(l_class_weight[i]) != n_states: - raise ValueError("Expected 1 class weight per state per node type. Wrong for l_class_weight[%d]"%i) + raise ValueError("Expected 1 class weight per state per node type. Wrong for type %d"%i) #class weights are computed by type and simply concatenated - self.class_weight = np.hstack([np.array(class_weight) for class_weight in l_class_weight]) + self.l_class_weight = [np.asarray(class_weight) for class_weight in l_class_weight] else: - self.class_weight = np.ones(self._n_states) + self.l_class_weight = [np.ones(n) for n in self.l_n_states] + self.class_weight = np.hstack(self.l_class_weight) self._set_size_joint_feature() #internal stuff #when putting features in a single sequence, index of 1st state for type i - self._l_type_startindex = [ sum(self.l_n_states[:i]) for i in range(self.n_types)] - self._l_type_startindex.append(self._n_states) #convenience + self._l_type_startindex = [ sum(self.l_n_states[:i]) for i in range(self.n_types+1)] #when putting states in a single sequence, index of 1st feature for type i (is at Ith position) #we store the slice objects self._a_feature_slice_by_typ = np.array([ slice(sum(self.l_n_features[:i]), sum(self.l_n_features[:i+1])) for i in range(self.n_types)]) + + + + + + + + #when putting edge states in a single sequence, index of 1st state of an edge of type (typ1, typ2) - self._l_edgetype_start_index = [] - i_start = 0 - for typ1_n_states in self.l_n_states: - for typ2_n_states in self.l_n_states: - self._l_edgetype_start_index.append(i_start) - i_start += typ1_n_states*typ2_n_states - self._l_edgetype_start_index.append(i_start) - assert i_start == self._n_states**2 + self.a_startindex_by_typ_typ = np.zeros((self.n_types, self.n_types), dtype=np.uint32) + i_state_start = 0 + for typ1, typ1_n_states in enumerate(self.l_n_states): + for typ2, typ2_n_states in enumerate(self.l_n_states): + self.a_startindex_by_typ_typ[typ1,typ2] = i_state_start + i_state_start += typ1_n_states*typ2_n_states + + def flatY(self, lX, lY_by_typ): + """ + It is more convenient to have the Ys grouped by type, as the Xs are. + Also, having a label starting at 0 for each type. + + This method does the job. + + lX is a list of X strutured as explained + """ + pass + def initialize(self, X, Y=None): if isinstance(X, list): map(self._check_size_x, X) - if not Y is None: map(self._check_size_xy, X, Y) + if not (Y is None): map(self._check_size_xy, X, Y) else: self._check_size_x(X) self._check_size_xy(X, Y) @@ -188,38 +209,18 @@ def _check_size_xy(self, X, Y): def _get_node_features(self, x, bClean=False): if bClean: - return [ np.empty((0,0)) if node_features is None or len(node_features)==0 else node_features for node_features in x[0]] + #we replace None by empty array with proper shape + return [ np.empty((0,_n_feat)) if node_features is None else node_features + for (node_features, _n_feat) in zip(x[0], self.l_n_features)] else: return x[0] - def _get_node_features_by_type(self, x, typ): - return x[0][typ] - def _get_edges(self, x, bClean=False): if bClean: return [ np.empty((0,0)) if edges is None or len(edges)==0 else edges for edges in x[1]] else: return x[1] - def _index_all_edges(self, x): - """ - return all edges as a single 2-column matrix, taking care of node indices!! - """ - n_edges_total = sum(0 if e is None else e.shape[0] for e in x[1]) - all_edges = np.zeros((n_edges_total, 2), dtype=np.int) - - node_offset_by_typ = np.cumsum([0]+[0 if n is None else n.shape[0] for n in x[0]]) - i_start = 0 - for edges, (typ1, typ2) in zip(x[1], self._iter_type_pairs()): - if edges is None: continue - n_edges = edges.shape[0] - i_stop = i_start + n_edges - all_edges[i_start:i_stop, 0] = edges[:,0] + node_offset_by_typ[typ1] - all_edges[i_start:i_stop, 1] = edges[:,1] + node_offset_by_typ[typ2] - i_start = i_stop - - return all_edges - def _get_edges_by_type(self, x, typ1, typ2): return x[1][typ1*self.n_types+typ2] @@ -230,19 +231,20 @@ def _iter_type_pairs(self): raise StopIteration - def _get_unary_potentials_initialize(self): - """ - pre-compute iteration params - """ - self._cache_unary_potentials = list() - - i_w, i_states = 0, 0 - for n_states, n_features in zip(self.l_n_states, self.l_n_features): - i_w2 = i_w + n_states*n_features #number of weights for the type - i_states2 = i_states + n_states #number of state of that type - self._cache_unary_potentials.append( ((i_w,i_w2), (i_states, i_states2), (n_states, n_features)) ) - i_w, i_states = i_w2, i_states2 - +# def _get_unary_potentials_initialize(self): +# """ +# pre-compute iteration params +# """ +# +# self._cache_unary_potentials = list() +# +# i_w, i_states = 0, 0 +# for n_states, n_features in zip(self.l_n_states, self.l_n_features): +# i_w2 = i_w + n_states*n_features #number of weights for the type +# i_states2 = i_states + n_states #number of state of that type +# self._cache_unary_potentials.append( ((i_w,i_w2), (i_states, i_states2), (n_states, n_features)) ) +# i_w, i_states = i_w2, i_states2 + def _get_unary_potentials(self, x, w): """Computes unary potentials for x and w. @@ -256,20 +258,35 @@ def _get_unary_potentials(self, x, w): Returns ------- - unary : ndarray, shape=( n_nodes, n_states ) + unaries : list of ndarray, shape=( n_nodes_typ, n_states_typ ) Unary weights. """ self._check_size_w(w) - l_node_features = self._get_node_features(x) + l_node_features = self._get_node_features(x, True) - w_unaries = w[:self.size_unaries] - a_nodes_states = np.zeros((sum(nf.shape[0] for nf in l_node_features) - , self._n_states), dtype=w.dtype) - i_nodes = 0 - for features, ((i_w,i_w2), (i_states, i_states2), (n_states, n_features)) in zip(l_node_features, self._cache_unary_potentials): - i_nodes2 = i_nodes + features.shape[0] #number of nodes of that type - a_nodes_states[i_nodes:i_nodes2, i_states:i_states2] = np.dot(features, w_unaries[i_w:i_w2].reshape(n_states, n_features).T) - i_nodes = i_nodes2 + l_unary_potentials = [] + + i_w = 0 + for (features, n_states, n_features) in zip(l_node_features, self.l_n_states, self.l_n_features): + n_w = n_states*n_features + l_unary_potentials.append( np.dot(features, w[i_w:i_w+n_w].reshape(n_states, n_features).T) ) + i_w += n_w + assert i_w == self.size_unaries + # nodes x features . features x states --> nodes x states - return a_nodes_states + return l_unary_potentials + +# self._check_size_w(w) +# l_node_features = self._get_node_features(x) +# +# w_unaries = w[:self.size_unaries] +# a_nodes_states = np.zeros((sum(nf.shape[0] for nf in l_node_features) +# , self._n_states), dtype=w.dtype) +# i_nodes = 0 +# for features, ((i_w,i_w2), (i_states, i_states2), (n_states, n_features)) in zip(l_node_features, self._cache_unary_potentials): +# i_nodes2 = i_nodes + features.shape[0] #number of nodes of that type +# a_nodes_states[i_nodes:i_nodes2, i_states:i_states2] = np.dot(features, w_unaries[i_w:i_w2].reshape(n_states, n_features).T) +# i_nodes = i_nodes2 +# # nodes x features . features x states --> nodes x states +# return a_nodes_states From 8b5688afc3857636fba807e4d341324bd6e9d372 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 13 Feb 2017 10:16:55 +0100 Subject: [PATCH 051/155] the pairwise is now a list per type --- .../node_type_edge_feature_graph_crf.py | 384 ++++++++++-------- 1 file changed, 218 insertions(+), 166 deletions(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index 4c128578..09073161 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -2,6 +2,8 @@ """ Pairwise CRF with features/strength associated to each edge and different types of nodes + + Copyright Xerox(C) 2017 JL. Meunier @@ -55,10 +57,9 @@ class NodeTypeEdgeFeatureGraphCRF(TypedCRF): l_n_features : list of int, default=None Number of features per type of node. - a_n_edge_features: an array of shape (n_types, n_types) given the number of features as a function of the node types + a_n_edge_features: an array of shape (n_types, n_types) giving the number of features per pair of types - NOTE: there should always be at least 1 feature for any pairs of types with some edge of that type in the graph. - Said differently, if you put 0 somewhere in that matrix, do not create any egde corresponding to that type of edge!! + NOTE: there should always be at least 1 feature for any pairs of types which has some edge in the graph. class_weight : None, or list of array-like Class weights. If a list of array-like is passed, the Ith one must have length equal to l_n_states[i] @@ -89,7 +90,7 @@ def __init__(self , l_n_states #how many labels per node type? , l_n_features #how many features per node type? , a_n_edge_features #how many features per edge type? - , inference_method="ad3" + , inference_method="ad3+" , l_class_weight=None): #class_weight per node type or None or None #internal stuff @@ -101,6 +102,7 @@ def __init__(self if not (self.a_n_edge_features == self.a_n_edge_features.T).all(): raise ValueError("Expected a symmetric array of edge feature numbers") + self.l_n_edge_features = self.a_n_edge_features.ravel() #number of (edge) features per edge type self._n_edge_features = self.a_n_edge_features.sum(axis=None) #total number of (edge) features TypedCRF.__init__(self, n_types, l_n_states, l_n_features, inference_method=inference_method, l_class_weight=l_class_weight) @@ -155,19 +157,19 @@ def _check_size_x(self, x): #check edge feature size for typ1,typ2 in self._iter_type_pairs(): - edge_features = self._get_edge_features_by_type(x, typ1, typ2) + edge_features = l_edge_features[typ1*self.n_types+typ2] if edge_features is None: continue if edge_features.shape[1] != self.a_n_edge_features[typ1,typ2]: raise ValueError("Types %d x %d: bad number of edge features. expected %d got %d"%(typ1,typ2, self.a_n_edge_features[typ1,typ2], edge_features.shape[1])) return True def _get_edge_features(self, x, bClean=False): - if bClean: - return [ np.empty((0,0)) if o is None or len(o)==0 else o for o in x[2]] + if bClean: + #we replace None by empty array with proper shape + return [ np.empty((0,_n_feat)) if _ef is None else _ef + for _ef, _n_feat in zip(x[2], self.l_n_edge_features)] else: return x[2] - def _get_edge_features_by_type(self, x, typ1, typ2): - return x[2][typ1*self.n_types+typ2] def _get_pairwise_potentials_initialize(self): """ @@ -209,43 +211,56 @@ def _get_pairwise_potentials(self, x, w): Returns ------- - pairwise : ndarray, shape=(n_edges, n_states, n_states) + pairwise : list of ndarray, shape=(n_edges, n_states_typ1, n_states_typ2) Pairwise weights. """ self._check_size_w(w) - #self._check_size_x(x) #call initialize once and only once before!! - - l_edge_features = self._get_edge_features(x) - l_edge_nb = [0 if ef is None else ef.shape[0] for ef in l_edge_features] - n_edges_total = sum(l_edge_nb) + l_edge_features = self._get_edge_features(x, True) wpw = w[self.size_unaries:] - a_edges_states_states = np.zeros((n_edges_total, self._n_states, self._n_states), dtype=w.dtype) - - i_edges = 0 - for ((n_features, n_states1, n_states2, i_states1, i_states1_stop, i_states2, i_states2_stop, i_w, i_w_stop) - , edge_features, n_edges) in zip(self._cache_pairwise_potentials, l_edge_features, l_edge_nb): - - i_edges_stop = i_edges + n_edges - - if not edge_features is None: - pw_typ_typ = wpw[i_w:i_w_stop].reshape(n_features, -1) # n_states1*n_states2 x nb_feat - pot_typ_typ = np.dot(edge_features, pw_typ_typ).reshape(n_edges, n_states1, n_states2) - a_edges_states_states[ i_edges:i_edges_stop, i_states1:i_states1_stop , i_states2:i_states2_stop ] = pot_typ_typ + + l_pairwise_potentials = [] + + i_w = 0 + for (typ1, typ2), edge_features in zip(self._iter_type_pairs(), l_edge_features): + n_edges, n_features = edge_features.shape + n_states1 = self.l_n_states[typ1] + n_states2 = self.l_n_states[typ2] + n_w = n_features * n_states1 * n_states2 + if n_w: + pw_typ_typ = wpw[i_w:i_w + n_w].reshape(n_features, -1) # n_states1*n_states2 x nb_feat + l_pairwise_potentials.append( np.dot(edge_features, pw_typ_typ).reshape(n_edges, n_states1, n_states2) ) + else: + l_pairwise_potentials.append( np.array([]) ) #first reshaping above complains: "ValueError: total size of new array must be unchanged" + i_w += n_w - i_edges = i_edges_stop - - return a_edges_states_states.reshape(n_edges_total, self._n_states, self._n_states) + return l_pairwise_potentials +# +# self._check_size_w(w) +# #self._check_size_x(x) #call initialize once and only once before!! +# +# l_edge_features = self._get_edge_features(x) +# l_edge_nb = [0 if ef is None else ef.shape[0] for ef in l_edge_features] +# n_edges_total = sum(l_edge_nb) +# +# wpw = w[self.size_unaries:] +# a_edges_states_states = np.zeros((n_edges_total, self._n_states, self._n_states), dtype=w.dtype) +# +# i_edges = 0 +# for ((n_features, n_states1, n_states2, i_states1, i_states1_stop, i_states2, i_states2_stop, i_w, i_w_stop) +# , edge_features, n_edges) in zip(self._cache_pairwise_potentials, l_edge_features, l_edge_nb): +# +# i_edges_stop = i_edges + n_edges +# +# if not edge_features is None: +# pw_typ_typ = wpw[i_w:i_w_stop].reshape(n_features, -1) # n_states1*n_states2 x nb_feat +# pot_typ_typ = np.dot(edge_features, pw_typ_typ).reshape(n_edges, n_states1, n_states2) +# a_edges_states_states[ i_edges:i_edges_stop, i_states1:i_states1_stop , i_states2:i_states2_stop ] = pot_typ_typ +# +# i_edges = i_edges_stop +# +# return a_edges_states_states.reshape(n_edges_total, self._n_states, self._n_states) - def _block_ravel(self, a, lij): - """ - Ravel the array block by block - """ - li, lj = zip(*lij) - return np.hstack( [a[i0:i1,j0:j1].ravel() - for (i0, i1), (j0,j1) - in zip( zip(li, li[1:]), zip(lj, lj[1:]) ) - ]) def joint_feature(self, x, y): """Feature vector associated with instance (x, y). @@ -272,10 +287,10 @@ def joint_feature(self, x, y): # print "x=", `x` # print "y=", `y` self._check_size_x(x) #call initialize once! - l_node_features = self._get_node_features(x) - l_edges, l_edge_features = self._get_edges(x), self._get_edge_features(x) - l_n_nodes = [len(o) for o in self._get_node_features(x, True)] - l_n_edges = [edges.shape[0] for edges in self._get_edges(x, True)] + l_node_features = self._get_node_features(x, True) + l_edges, l_edge_features = self._get_edges(x), self._get_edge_features(x, True) + l_n_nodes = [len(nf) for nf in self._get_node_features(x, True)] + l_n_edges = [len(ef) for ef in self._get_edges (x, True)] n_nodes = sum(l_n_nodes) n_edges = sum(l_n_edges) @@ -283,74 +298,92 @@ def joint_feature(self, x, y): #print "y=", `y` # y is result of relaxation, tuple of unary and pairwise marginals unary_marginals, pw = y - unary_marginals = unary_marginals.reshape(n_nodes, self._n_states) + + #I tried to have the ad3+ inference to return lists, but the learner then fails... + #I do not want to interfere wit hit, so I "mangle" /"unmangle" the data... + + if isinstance(unary_marginals, list): + l_unary_marginals = unary_marginals + else: + l_unary_marginals = [] + i,j = 0,0 + for (_n_nodes, _n_states) in zip(l_n_nodes, self.l_n_states): #iteration by type + _n_binaries = _n_nodes * _n_states + _unary_marginals = unary_marginals[ i:i+_n_nodes , j:j+_n_states ] + i += _n_nodes + j += _n_states + l_unary_marginals.append(_unary_marginals) + + if isinstance(pw, list): + l_pw = pw + else: + #until we do better in ad3+ inference, but we cannot I think without touching the learners... + l_pw = [] + i_start = 0 + for _n_edges, (typ1, typ2) in zip(l_n_edges, self._iter_type_pairs()): + n = self.l_n_states[typ1] * self.l_n_states[typ2] + i_stop = i_start + _n_edges + i_state_start = self.a_startindex_by_typ_typ[typ1,typ2] + _edge_marginals = pw[i_start:i_stop, i_state_start:i_state_start+n] + i_start = i_stop + l_pw.append(_edge_marginals) else: self._check_size_xy(x, y) - #make one hot encoding - #each type is assigned a range of columns, each starting at self._a_state_startindex_by_typ[ ] - #in the arnge column I is for state i of that type - unary_marginals = np.zeros((n_nodes, self._n_states), dtype=np.int) - + #make one hot encoding per type + l_unary_marginals = [] i_start = 0 - for node_features, typ_start_index in zip(l_node_features, self._l_type_startindex): - if node_features is None: continue - i_stop = i_start + node_features.shape[0] - unary_marginals[ np.ogrid[i_start:i_stop] - , y[i_start:i_stop] - ] = 1 + #PBY for _n_nodes, _n_states in zip(l_n_nodes, self.l_n_states): + for _n_nodes, _n_states, typ_start_index in zip(l_n_nodes, self.l_n_states, self._l_type_startindex): + i_stop = i_start + _n_nodes + _unary_marginals = np.zeros((_n_nodes, _n_states), dtype=np.int) + gx = np.ogrid[:_n_nodes] + _unary_marginals[gx, y[i_start:i_stop]-typ_start_index] = 1 + l_unary_marginals.append(_unary_marginals) i_start = i_stop ## pairwise #same thing, but the type of an edge is a pair of node types - pw = np.zeros((n_edges, self._n_states ** 2)) + l_pw = [] node_offset_by_typ = np.cumsum([0]+[0 if n is None else n.shape[0] for n in x[0]]) - i_start = 0 - for (typ1, typ2), edges, edgetype_start_index in zip(self._iter_type_pairs(), l_edges, self._l_edgetype_start_index): - if edges is None: continue - y1 = y[node_offset_by_typ[typ1] + edges[:,0]] - self._l_type_startindex[typ1] - assert (0<=y1).all() and (y1 <= self.l_n_states[typ1]).all() - y2 = y[node_offset_by_typ[typ2] + edges[:,1]] - self._l_type_startindex[typ2] - assert (0<=y2).all() and (y2 <= self.l_n_states[typ2]).all() - #set the 1s where they should - i_stop = i_start + edges.shape[0] - pw[ np.ogrid[i_start:i_stop] - , edgetype_start_index + self.l_n_states[typ2] * y1 + y2 - ] = 1 - i_start = i_stop - assert i_start == n_edges + for _n_edges, (typ1, typ2), edges in zip(l_n_edges, self._iter_type_pairs(), l_edges): + _n_states_typ1 = self.l_n_states[typ1] + _n_states_typ2 = self.l_n_states[typ2] + _pw = np.zeros((_n_edges, _n_states_typ1 * _n_states_typ2)) + if _n_edges: + y1 = y[node_offset_by_typ[typ1] + edges[:,0]] - self._l_type_startindex[typ1] + y2 = y[node_offset_by_typ[typ2] + edges[:,1]] - self._l_type_startindex[typ2] + assert (0<=y1).all() and (y1 <= self.l_n_states[typ1]).all() + assert (0<=y2).all() and (y2 <= self.l_n_states[typ2]).all() + #set the 1s where they should + class_pair_ind = (y2 + _n_states_typ2 * y1) + _pw[np.arange(_n_edges), class_pair_ind] = 1 + l_pw.append(_pw) #UNARY - #assign the feature of each node t the right range of column according to the node type - all_node_features = np.zeros((n_nodes, self._n_features)) - i_start = 0 - for (_a_feature_slice, node_features) in zip(self._a_feature_slice_by_typ, l_node_features): - i_stop = i_start + node_features.shape[0] - all_node_features[ i_start:i_stop - , _a_feature_slice] = node_features - i_start = i_stop - assert i_start == n_nodes - unaries_acc = np.dot(unary_marginals.T, all_node_features) # node_states x sum_of_features matrix - - #assign the edges feature to the right range of columns, depending on edge type - all_edge_features = np.zeros( (n_edges, self._n_edge_features) ) - i_start = 0 - i_col_start = 0 - for edge_features, n_feat in zip(l_edge_features, self.a_n_edge_features.ravel()): - i_col_stop = i_col_start + n_feat - - if not edge_features is None: - nb_edges = edge_features.shape[0] - i_stop = i_start + nb_edges - all_edge_features[ i_start:i_stop - , i_col_start:i_col_stop ] = edge_features - i_start = i_stop - i_col_start = i_col_stop + l_unary_acc_ravelled = [np.dot(unary_marginals.T, features).ravel() for (unary_marginals, features) in zip(l_unary_marginals, l_node_features)] + unaries_acc_ravelled = np.hstack(l_unary_acc_ravelled) + + #PW + l_pw_ravelled = [np.dot(ef.T, pw).ravel() for (ef, pw) in zip(l_edge_features, l_pw)] +# l_pw_ravelled = [np.zeros((n_edge_states,)) if pw is None else np.dot(ef.T, pw).ravel() for (ef, pw, n_edge_states) in zip(l_edge_features, l_pw, self.l_n_edge_states)] + pairwise_acc_ravelled = np.hstack(l_pw_ravelled) -# if False: -# np.set_printoptions(precision=3, linewidth=9999) -# print "all_edge_features (edgexfeat) \n", `all_edge_features` -# print "pw (edgexstate)\n", `pw` - pairwise_acc = np.dot(all_edge_features.T, pw) # sum_of_features x edge_states +# #assign the edges feature to the right range of columns, depending on edge type +# all_edge_features = np.zeros( (n_edges, self._n_edge_features) ) +# i_start = 0 +# i_col_start = 0 +# for edge_features, n_feat in zip(l_edge_features, self.a_n_edge_features.ravel()): +# i_col_stop = i_col_start + n_feat +# +# if not edge_features is None: +# nb_edges = edge_features.shape[0] +# i_stop = i_start + nb_edges +# all_edge_features[ i_start:i_stop +# , i_col_start:i_col_stop ] = edge_features +# i_start = i_stop +# i_col_start = i_col_stop +# +# pairwise_acc = np.dot(all_edge_features.T, pw) # sum_of_features x edge_states # This forced symetry / antisymetry is not supported for now # for i in self.symmetric_edge_features: @@ -362,14 +395,14 @@ def joint_feature(self, x, y): # pw[i] = (pw_ - pw_.T).ravel() / 2. #we need to linearize it, while keeping only meaningful data - unaries_acc_ravelled = self._block_ravel(unaries_acc, [(0,0)]+zip(np.cumsum(self.l_n_states), np.cumsum(self.l_n_features))) - assert len(unaries_acc_ravelled) == self.size_unaries +# unaries_acc_ravelled = self._block_ravel(unaries_acc, [(0,0)]+zip(np.cumsum(self.l_n_states), np.cumsum(self.l_n_features))) +# assert len(unaries_acc_ravelled) == self.size_unaries - L1 = np.cumsum(self.a_n_edge_features.ravel()) - L2 = np.cumsum([self.l_n_states[typ1] * self.l_n_states[typ2] for typ1, typ2 in self._iter_type_pairs() ]) - pairwise_acc_ravelled = self._block_ravel(pairwise_acc, [(0,0)]+zip(L1,L2)) - - assert len(pairwise_acc_ravelled) == self.size_pairwise +# L1 = np.cumsum(self.a_n_edge_features.ravel()) +# L2 = np.cumsum([self.l_n_states[typ1] * self.l_n_states[typ2] for typ1, typ2 in self._iter_type_pairs() ]) +# pairwise_acc_ravelled = self._block_ravel(pairwise_acc, [(0,0)]+zip(L1,L2)) +# +# assert len(pairwise_acc_ravelled) == self.size_pairwise joint_feature_vector = np.hstack([unaries_acc_ravelled, pairwise_acc_ravelled]) assert joint_feature_vector.shape[0] == self.size_joint_feature, (joint_feature_vector.shape[0], self.size_joint_feature) @@ -423,59 +456,93 @@ def loss_augmented_inference(self, x, y, w, relaxed=False, shape (n_states, n_states) of accumulated pairwise marginals. """ -# print "y.shape ", y.shape self.inference_calls += 1 self._check_size_w(w) - unary_potentials = self._get_unary_potentials(x, w) - pairwise_potentials = self._get_pairwise_potentials(x, w) - flat_edges = self._index_all_edges(x) + l_unary_potentials = self._get_unary_potentials(x, w) + l_pairwise_potentials = self._get_pairwise_potentials(x, w) + edges = self._get_edges(x, True) + + i_start = 0 + a_y = np.asarray(y) + + #REF loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) + - loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) + for typ, (unary_potentials, class_weight) in enumerate(zip(l_unary_potentials, self.l_class_weight)): + n_y = unary_potentials.shape[0] + y_typ = a_y[i_start:i_start+n_y] - self._l_type_startindex[typ] #label 0 must correspond to 1st weight + loss_augment_unaries(unary_potentials, y_typ, class_weight) + i_start += n_y + if self.inference_method == "ad3+": l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] nodetype_data = (l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type - Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, + Y_pred = inference_dispatch(l_unary_potentials, l_pairwise_potentials, edges, self.inference_method, relaxed=relaxed, - return_energy=return_energy, - nodetype=nodetype_data) + return_energy=return_energy) +# nodetype=nodetype_data) #with ad3+ this should never occur if not isinstance(Y_pred, tuple): assert self._check_size_xy(x, Y_pred), "Internal error in AD3+: inconsistent labels" else: - Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy) - #no nodetype parameter! - #we may have inconsistent labels! - try: - if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) - except InconsistentLabel: - #the inference engine predicted inconsistent labels - Y_pred = self.fix_Y_at_random(x, Y_pred) - + raise Exception("You must use ad3+ as inference method") #if self.inference_calls % 1000 == 0: print "%d inference calls"%self.inference_calls return Y_pred + +# self.inference_calls += 1 +# self._check_size_w(w) +# unary_potentials = self._get_unary_potentials(x, w) +# pairwise_potentials = self._get_pairwise_potentials(x, w) +# flat_edges = self._index_all_edges(x) +# +# loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) +# +# if self.inference_method == "ad3+": +# l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] +# nodetype_data = (l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type +# +# Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, +# self.inference_method, relaxed=relaxed, +# return_energy=return_energy, +# nodetype=nodetype_data) +# #with ad3+ this should never occur +# if not isinstance(Y_pred, tuple): assert self._check_size_xy(x, Y_pred), "Internal error in AD3+: inconsistent labels" +# else: +# Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, +# self.inference_method, relaxed=relaxed, +# return_energy=return_energy) +# #no nodetype parameter! +# #we may have inconsistent labels! +# try: +# if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) +# except InconsistentLabel: +# #the inference engine predicted inconsistent labels +# Y_pred = self.fix_Y_at_random(x, Y_pred) +# +# #if self.inference_calls % 1000 == 0: print "%d inference calls"%self.inference_calls +# +# return Y_pred - def fix_Y_at_random(self, x, Y_pred): - print "\tY is BAD, FIXING IT AT RANDOM", `Y_pred` - - l_node_features = self._get_node_features(x, True) - i_start = 0 - for typ, (nf, n_states) in enumerate(zip(l_node_features, self.l_n_states)): - nb_nodes = nf.shape[0] - if nb_nodes: - Y_typ = Y_pred[i_start:i_start+nb_nodes] - typ_start = self._l_type_startindex[typ] - typ_end = self._l_type_startindex[typ+1] - if np.min(Y_typ) < typ_start or typ_end <= np.max(Y_typ): - for i in range(nb_nodes): - if Y_pred[i_start+i] < typ_start or typ_end <= Y_pred[i_start+i]: Y_pred[i_start+i] = random.randint(typ_start, typ_end-1) - i_start = i_start + nb_nodes - self._check_size_xy(x, Y_pred) - return Y_pred - +# def fix_Y_at_random(self, x, Y_pred): +# print "\tY is BAD, FIXING IT AT RANDOM", `Y_pred` +# +# l_node_features = self._get_node_features(x, True) +# i_start = 0 +# for typ, (nf, n_states) in enumerate(zip(l_node_features, self.l_n_states)): +# nb_nodes = nf.shape[0] +# if nb_nodes: +# Y_typ = Y_pred[i_start:i_start+nb_nodes] +# typ_start = self._l_type_startindex[typ] +# typ_end = self._l_type_startindex[typ+1] +# if np.min(Y_typ) < typ_start or typ_end <= np.max(Y_typ): +# for i in range(nb_nodes): +# if Y_pred[i_start+i] < typ_start or typ_end <= Y_pred[i_start+i]: Y_pred[i_start+i] = random.randint(typ_start, typ_end-1) +# i_start = i_start + nb_nodes +# self._check_size_xy(x, Y_pred) +# return Y_pred +# def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): """Inference for x using parameters w. @@ -523,37 +590,22 @@ def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): self._check_size_w(w) self.inference_calls += 1 self.initialize(x) - unary_potentials = self._get_unary_potentials(x, w) - pairwise_potentials = self._get_pairwise_potentials(x, w) - flat_edges = self._index_all_edges(x) + l_unary_potentials = self._get_unary_potentials(x, w) + l_pairwise_potentials = self._get_pairwise_potentials(x, w) + edges = self._get_edges(x, True) l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] + assert l_n_nodes == [un.shape[0] for un in l_unary_potentials] + nodetype_data=(l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type if self.inference_method == "ad3+": - #preferred method for TypedCRF inferences (called by the 'predict' method of the learner) - Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, + Y_pred = inference_dispatch(l_unary_potentials, l_pairwise_potentials, edges, self.inference_method, relaxed=relaxed, return_energy=return_energy, constraints=constraints, - nodetype=nodetype_data, inference_exception=self.inference_exception) #<-- else: - if constraints: - Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy, - constraints=constraints) #<-- - else: - Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy) #<-- - - try: - if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) - except: - Y_pred = self.fix_Y_at_random(x, Y_pred) + raise Exception("You must use ad3+ as inference method") - if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) - return Y_pred From 20bbed5013f0bff0f55d19ed5c520371c307d4eb Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 13 Feb 2017 10:18:34 +0100 Subject: [PATCH 052/155] - test ok - pairwise is a list --- .../test_node_type_edge_feature_graph_crf.py | 147 +++++++++--------- 1 file changed, 74 insertions(+), 73 deletions(-) diff --git a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py index d154033a..efb4cdb2 100644 --- a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py +++ b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py @@ -166,7 +166,8 @@ def test_joint_feature(): print "joint_feature = \n", `jf` print assert_array_equal(g.joint_feature(x,y) - , np.array([ 0., 0., 0., 1., 1., 1., 2., 2., 2., 0., 0., 0., 0., + , np.array([ 0., 0., 0., 1., 1., 1., 2., 2., 2., 0., 0., 0. + , 0., 0., 0., 0., 0., 0., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 3., 0., @@ -466,41 +467,38 @@ def test_joint_feature3(): print `w` ret_u = g._get_unary_potentials(x, w) print `ret_u` - assert_array_almost_equal(ret_u,np.array([ #n_nodes x n_states - [3, 6, 0,0,0], - [6, 12, 0,0,0], - [0, 0, 5, 10, 15], - [0, 0, 9, 18, 27], - [0, 0, 13, 26, 39] - ]) - ) + assert len(ret_u) == 2 + assert_array_almost_equal(ret_u[0], np.array([ #n_nodes x n_states + [3, 6], + [6, 12]])) + + assert_array_almost_equal(ret_u[1], np.array([ #n_nodes x n_states + [5, 10, 15], + [9, 18, 27], + [13, 26, 39]])) assert len(w) == g.size_joint_feature ret_pw = g._get_pairwise_potentials(x, w) - print "PW ", `ret_pw` - assert_array_almost_equal(ret_pw,np.array([ #n_edges, n_states, n_states - # 3 edges 5 states in total - [ #edge: typ0 - typ1, 2 features - [ 0, 0, 0.443, 0.443, 0.443], - [ 0, 0, 0.443, 0.443, 0.443], - [ 0, 0, 0, 0, 0], - [ 0, 0, 0, 0, 0], - [ 0, 0, 0, 0, 0] - ], - [ #edge: typ1 - typ1, 2 features - [ 0. , 0. , 0. , 0. , 0. ], - [ 0. , 0. , 0. , 0. , 0. ], - [ 0. , 0. , 0.06 , 0.06 , 0.06 ], - [ 0. , 0. , 0.06 , 0.06 , 0.06 ], - [ 0. , 0. , 0.06 , 0.06 , 0.06 ]], - [ #edge: typ1 - typ1, 2 features - [ 0. , 0. , 0. , 0. , 0. ], - [ 0. , 0. , 0. , 0. , 0. ], - [ 0. , 0. , 0.006, 0.006, 0.006], - [ 0. , 0. , 0.006, 0.006, 0.006], - [ 0. , 0. , 0.006, 0.006, 0.006]] - ])) + for _pw in ret_pw: + print "_pw ", `_pw` + pw00, pw01, pw10, pw11 = ret_pw + assert len(pw00) == 0 + assert_array_almost_equal(pw01,np.array([ #n_edges, n_states, n_states + [[0.443, 0.443, 0.443], + [0.443, 0.443, 0.443]] + ])) + assert len(pw10) == 0 + assert_array_almost_equal(pw11,np.array([ #n_edges, n_states, n_states + [[0.06 , 0.06 , 0.06], + [0.06 , 0.06 , 0.06], + [0.06 , 0.06 , 0.06]] + , + [[0.006, 0.006, 0.006], + [0.006, 0.006, 0.006], + [0.006, 0.006, 0.006]] + ])) + def test_unary_potentials(): @@ -536,48 +534,48 @@ def test_unary_potentials(): w = np.arange(g.size_joint_feature) pot = g._get_unary_potentials(x, w) print `pot` - assert_array_equal(pot, potref) + assert_array_equal(pot, [potref]) pwpotref = gref._get_pairwise_potentials(xref, wref) print `pwpotref` pwpot = g._get_pairwise_potentials(x, w) print `pwpot` - assert_array_equal(pwpot, pwpotref) + assert_array_equal(pwpot, [pwpotref]) -def test_inference_util(): - g = NodeTypeEdgeFeatureGraphCRF( - 3 #how many node type? - , [2, 3, 1] #how many labels per node type? - , [3, 4, 1] #how many features per node type? - , np.array([ [1, 2, 2] - , [2, 3, 2] - , [2, 2, 1]]) #how many features per node type X node type? - ) - node_f = [ np.array([ [2,2,2], [1,1,1] ]) - , np.array([ [.31, .32, .33, .34], [.11, .12, .13, .14], [.21, .22, .23, .24]]) - , np.array([ [77], [88], [99]]) - ] - edges = [ np.array( [ [1, 0]] ), - np.array( [ [1,0]] ) #an edge from 0 to 2 - , None - - , None - , None - , None - - , np.array( [[1,1]] ) - , None - , None ] - - x = ( node_f, edges, None) - - reindexed_exdges = g._index_all_edges(x) - #print `reindexed_exdges` - assert_array_equal(reindexed_exdges, - np.array( [[1,0], - [1,2], - [6,1]])) - +# def test_inference_util(): +# g = NodeTypeEdgeFeatureGraphCRF( +# 3 #how many node type? +# , [2, 3, 1] #how many labels per node type? +# , [3, 4, 1] #how many features per node type? +# , np.array([ [1, 2, 2] +# , [2, 3, 2] +# , [2, 2, 1]]) #how many features per node type X node type? +# ) +# node_f = [ np.array([ [2,2,2], [1,1,1] ]) +# , np.array([ [.31, .32, .33, .34], [.11, .12, .13, .14], [.21, .22, .23, .24]]) +# , np.array([ [77], [88], [99]]) +# ] +# edges = [ np.array( [ [1, 0]] ), +# np.array( [ [1,0]] ) #an edge from 0 to 2 +# , None +# +# , None +# , None +# , None +# +# , np.array( [[1,1]] ) +# , None +# , None ] +# +# x = ( node_f, edges, None) +# +# reindexed_exdges = g._index_all_edges(x) +# #print `reindexed_exdges` +# assert_array_equal(reindexed_exdges, +# np.array( [[1,0], +# [1,2], +# [6,1]])) +# def report_model_config(crf): print crf.n_states @@ -631,8 +629,9 @@ def test_inference(): y_pred = crf.inference(x, w, relaxed=True) if isinstance(y_pred, tuple): # ad3 produces an integer result if it found the exact solution - assert_array_almost_equal(res[1], y_pred[1], 5) + #np.set_printoptions(precision=2, threshold=9999) assert_array_almost_equal(res[0], y_pred[0].reshape(-1, n_states), 5) + assert_array_almost_equal(res[1], y_pred[1], 5) assert_array_equal(y, np.argmax(y_pred[0], axis=-1), 5) #for inference_method in get_installed(["lp", "ad3", "qpbo"]): @@ -770,9 +769,9 @@ def test_energy_discrete(): w = np.hstack([unary_params.ravel(), pw1.ravel(), pw2.ravel()]) crf.initialize(x) y_hat = crf.inference(x, w, relaxed=False) - flat_edges = crf._index_all_edges(x) - energy = compute_energy(crf._get_unary_potentials(x, w), - crf._get_pairwise_potentials(x, w), flat_edges, #CAUTION: pass the flatened edges!! + #flat_edges = crf._index_all_edges(x) + energy = compute_energy(crf._get_unary_potentials(x, w)[0], + crf._get_pairwise_potentials(x, w)[0], edges, #CAUTION: pass the flatened edges!! y_hat) joint_feature = crf.joint_feature(x, y_hat) @@ -795,9 +794,11 @@ def test_energy_discrete(): test_joint_feature3() if 1: test_unary_potentials() - if 1: test_inference_util() +# if 1: test_inference_util() if 1: test_inference() if 1: test_joint_feature_discrete() if 1: test_joint_feature_continuous() if 1: test_energy_continuous() if 1: test_energy_discrete() + + print "OK" From 38998270470b26bc11234ffbef08e2dc79df2f5c Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 13 Feb 2017 14:06:49 +0100 Subject: [PATCH 053/155] ad3+ inference returns a list of unaries and a list of pairwise (smaller total size than all this in a big matrix with lots of zeros) --- pystruct/inference/inference_methods.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/pystruct/inference/inference_methods.py b/pystruct/inference/inference_methods.py index 090271a7..d285c48e 100644 --- a/pystruct/inference/inference_methods.py +++ b/pystruct/inference/inference_methods.py @@ -444,16 +444,23 @@ def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges, relaxe res = ad3.general_constrained_graph(l_unary_potentials, l_edges, l_pairwise_potentials, constraints, verbose=verbose, n_iterations=4000, exact=branch_and_bound) - unary_marginals, pairwise_marginals, energy, solver_status = res + l_unary_marginals, l_pairwise_marginals, energy, solver_status = res if verbose: print(solver_status) if relaxed and solver_status in ["fractional", "unsolved"]: - y = (unary_marginals, pairwise_marginals) + y = (l_unary_marginals, l_pairwise_marginals) else: if inference_exception and solver_status in ["fractional", "unsolved"]: raise InferenceException(solver_status) - y = np.argmax(unary_marginals, axis=-1) + #we now get a list of unary marginals + ly = list() + _cum_n_states = 0 + for unary_marg in l_unary_marginals: + ly.append( _cum_n_states + np.argmax(unary_marg, axis=-1) ) + _cum_n_states += unary_marg.shape[1] #number of states for that type + y = np.hstack(ly) + # when we will simplify y: y = [_cum_n_statesnp.argmax(unary_marg, axis=-1) for unary_marg in l_unary_marginals] if return_energy: return y, -energy From ee7398350d772389a2a3d5c98cfd1f9383b05c12 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 13 Feb 2017 14:08:09 +0100 Subject: [PATCH 054/155] - supports the case of an inference method returning a tuple of LIST OF marginals, in relaxed mode --- pystruct/learners/one_slack_ssvm.py | 34 ++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/pystruct/learners/one_slack_ssvm.py b/pystruct/learners/one_slack_ssvm.py index c5f6a162..1dcfe9a2 100644 --- a/pystruct/learners/one_slack_ssvm.py +++ b/pystruct/learners/one_slack_ssvm.py @@ -277,6 +277,30 @@ def _check_bad_constraint(self, violation, djoint_feature_mean, loss, return True return False + @classmethod + def constraint_equal(cls, y_1, y_2): + """ + This now more complex. y_1 and/or y_2 (I think) can be: array, pair of arrays, pair of list of arrays (multitype) + We need to compare those! + """ + if isinstance(y_1, tuple): + #y_1 is relaxed Y + #y_1 and y_2 might be lists of ndarray (multitype) instead of ndarray (single type) + u_m_1, pw_m_1 = y_1 + if isinstance(y_2, tuple): #we then compare two relaxed Ys + u_m_2, pw_m_2 = y_2 + #now, do we multitype or single type relaxed marginals?? + if isinstance(u_m_1, list): + return all( np.all(_um1 == _um2) for _um1, _um2 in zip( u_m_1, u_m_2) ) \ + and all( np.all(_pw1 == _pw2) for _pw1, _pw2 in zip(pw_m_1, pw_m_2)) + else: + return np.all(u_m_1 == u_m_2) and np.all(pw_m_1, pw_m_2) + else: + #NOTE original code was possibly comparing array and scalar + #return np.all(y_1[0] == y_2[0]) and np.all(y_1[1] == y_2[1]) + return False + return np.all(y_1 == y_2) #might compare array and tuple... :-/ Was like that, Ikeep + def _update_cache(self, X, Y, Y_hat): """Updated cached constraints.""" if self.inference_cache == 0: @@ -285,13 +309,13 @@ def _update_cache(self, X, Y, Y_hat): or self.inference_cache_ is None): self.inference_cache_ = [[] for y in Y_hat] - def constraint_equal(y_1, y_2): - if isinstance(y_1, tuple): - return np.all(y_1[0] == y_2[0]) and np.all(y_1[1] == y_2[1]) - return np.all(y_1 == y_2) +# def constraint_equal(y_1, y_2): +# if isinstance(y_1, tuple): +# return np.all(y_1[0] == y_2[0]) and np.all(y_1[1] == y_2[1]) +# return np.all(y_1 == y_2) for sample, x, y, y_hat in zip(self.inference_cache_, X, Y, Y_hat): - already_there = [constraint_equal(y_hat, cache[2]) + already_there = [self.constraint_equal(y_hat, cache[2]) for cache in sample] if np.any(already_there): continue From a4b1949f9cd0366fcc282f5d5a326dc972261990 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 13 Feb 2017 14:10:02 +0100 Subject: [PATCH 055/155] - code cleaning - convenience method flattenY unflattenY - continuous_loss re-implemented for the case of the relaxed marginals returned as lists --- pystruct/models/typed_crf.py | 110 ++++++++++++++++++----------------- 1 file changed, 56 insertions(+), 54 deletions(-) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index 323a352f..c6c893f3 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -66,9 +66,6 @@ def __init__(self #number of typextype states, or number of states per type of edge self.l_n_edge_states = [ n1 * n2 for n1 in self.l_n_states for n2 in self.l_n_states ] -# #Caching some heavily used values -# self._get_unary_potentials_initialize() - #class weights: # either we get class weights for all types of nodes, or for none of them! if l_class_weight: @@ -87,21 +84,9 @@ def __init__(self self._set_size_joint_feature() #internal stuff - #when putting features in a single sequence, index of 1st state for type i + #when putting node states in a single sequence, index of 1st state for type i self._l_type_startindex = [ sum(self.l_n_states[:i]) for i in range(self.n_types+1)] - #when putting states in a single sequence, index of 1st feature for type i (is at Ith position) - #we store the slice objects - self._a_feature_slice_by_typ = np.array([ slice(sum(self.l_n_features[:i]), sum(self.l_n_features[:i+1])) for i in range(self.n_types)]) - - - - - - - - - #when putting edge states in a single sequence, index of 1st state of an edge of type (typ1, typ2) self.a_startindex_by_typ_typ = np.zeros((self.n_types, self.n_types), dtype=np.uint32) i_state_start = 0 @@ -110,19 +95,36 @@ def __init__(self self.a_startindex_by_typ_typ[typ1,typ2] = i_state_start i_state_start += typ1_n_states*typ2_n_states - - def flatY(self, lX, lY_by_typ): + # -------------- CONVENIENCE -------------------------- + def flatY(self, lY_by_typ): """ - It is more convenient to have the Ys grouped by type, as the Xs are. - Also, having a label starting at 0 for each type. - - This method does the job. + It is more convenient to have the Ys grouped by type, as the Xs are, and to have the first label of each type encoded as 0. - lX is a list of X strutured as explained + This method does the job. It returns a flat Y array, with unique code per class label, which can be passed to 'fit' """ - pass + lY = list() + for n_start_state, Y_typ in zip(self._l_type_startindex, lY_by_typ): + lY.append( np.asarray(Y_typ) + n_start_state ) + return np.hstack(lY) + def unflatY(self, lX, flatY): + """ + predict returns a flat array of Y (same structure as for 'fit') + This method structures the Y as a list of Y_per_type, where the first label of any type is 0 + """ + lY = list() + i_start_node = 0 + for n_start_state, X in zip(self._l_type_startindex, lX): + n_nodes = X.shape[0] + Y = flatY[i_start_node : i_start_node+n_nodes] - n_start_state + lY.append(Y) + i_start_node += n_nodes + return lY + def initialize(self, X, Y=None): + """ + It is optional to call it. Does data checking only! + """ if isinstance(X, list): map(self._check_size_x, X) if not (Y is None): map(self._check_size_xy, X, Y) @@ -137,6 +139,7 @@ def setInferenceException(self, bRaiseExceptionWhenInferenceNotSuccessful): self.inference_exception = bRaiseExceptionWhenInferenceNotSuccessful return self.inference_exception + # -------------- INTERNAL STUFF -------------------------- def _set_size_joint_feature(self): """ We have: @@ -199,8 +202,6 @@ def _check_size_xy(self, X, Y): Y_typ = Y[i_start:i_start+nb_nodes] if np.min(Y_typ) < 0: raise ValueError("Got a negative label for type %d"%typ) -# if np.max(Y_typ) >= n_states: -# raise ValueError("Got a label outside of [0, %d] for type %d: %s"%(n_states-1, typ, Y_typ)) if np.min(Y_typ) < self._l_type_startindex[typ] : raise InconsistentLabel("labels of type %d start at %d"%(typ, self._l_type_startindex[typ])) if np.max(Y_typ) >= self._l_type_startindex[typ+1]: raise InconsistentLabel("labels of type %d end at %d"%(typ, self._l_type_startindex[typ+1]-1)) i_start = i_start + nb_nodes @@ -231,20 +232,6 @@ def _iter_type_pairs(self): raise StopIteration -# def _get_unary_potentials_initialize(self): -# """ -# pre-compute iteration params -# """ -# -# self._cache_unary_potentials = list() -# -# i_w, i_states = 0, 0 -# for n_states, n_features in zip(self.l_n_states, self.l_n_features): -# i_w2 = i_w + n_states*n_features #number of weights for the type -# i_states2 = i_states + n_states #number of state of that type -# self._cache_unary_potentials.append( ((i_w,i_w2), (i_states, i_states2), (n_states, n_features)) ) -# i_w, i_states = i_w2, i_states2 - def _get_unary_potentials(self, x, w): """Computes unary potentials for x and w. @@ -276,17 +263,32 @@ def _get_unary_potentials(self, x, w): # nodes x features . features x states --> nodes x states return l_unary_potentials -# self._check_size_w(w) -# l_node_features = self._get_node_features(x) -# -# w_unaries = w[:self.size_unaries] -# a_nodes_states = np.zeros((sum(nf.shape[0] for nf in l_node_features) -# , self._n_states), dtype=w.dtype) -# i_nodes = 0 -# for features, ((i_w,i_w2), (i_states, i_states2), (n_states, n_features)) in zip(l_node_features, self._cache_unary_potentials): -# i_nodes2 = i_nodes + features.shape[0] #number of nodes of that type -# a_nodes_states[i_nodes:i_nodes2, i_states:i_states2] = np.dot(features, w_unaries[i_w:i_w2].reshape(n_states, n_features).T) -# i_nodes = i_nodes2 -# # nodes x features . features x states --> nodes x states -# return a_nodes_states - + + def continuous_loss(self, y, l_y_hat): + # continuous version of the loss + # y is the result of linear programming + #BUT, in multitype mode, y_hat is a list of unaries + if y.ndim == 2: + raise ValueError("FIXME!") +# gx = np.indices(y.shape) +# # all entries minus correct ones +# result = 1 - y_hat[gx, y] + + l_result = list() + cum_n_node = 0 + cum_n_state = 0 + for y_hat in l_y_hat: + n_node, n_state = y_hat.shape + # all entries minus correct ones + y_type = y[cum_n_node:cum_n_node+n_node] - cum_n_state #select the correct range of labels and make the labels start at 0 + gx = np.indices(y_type.shape) + result = 1 - y_hat[gx, y_type] + l_result.append(result) + cum_n_node += n_node + cum_n_state += n_state + result = np.hstack(l_result) + + if hasattr(self, 'class_weight'): + return np.sum(self.class_weight[y] * result) + return np.sum(result) + From ccb8c58c64bb1cc2e101f5df9b16e0b9a8e8c58f Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 13 Feb 2017 14:10:33 +0100 Subject: [PATCH 056/155] same as before --- pystruct/models/typed_crf.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index c6c893f3..d7be0ec1 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -96,7 +96,7 @@ def __init__(self i_state_start += typ1_n_states*typ2_n_states # -------------- CONVENIENCE -------------------------- - def flatY(self, lY_by_typ): + def flattenY(self, lY_by_typ): """ It is more convenient to have the Ys grouped by type, as the Xs are, and to have the first label of each type encoded as 0. @@ -107,7 +107,7 @@ def flatY(self, lY_by_typ): lY.append( np.asarray(Y_typ) + n_start_state ) return np.hstack(lY) - def unflatY(self, lX, flatY): + def unflattenY(self, lX, flatY): """ predict returns a flat array of Y (same structure as for 'fit') This method structures the Y as a list of Y_per_type, where the first label of any type is 0 From 513d5eb6662eafaa04575f43b2feea5c805b263a Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 13 Feb 2017 14:22:17 +0100 Subject: [PATCH 057/155] passed --- .../test_models/test_node_type_edge_feature_graph_crf.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py index efb4cdb2..f15e5a1b 100644 --- a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py +++ b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py @@ -630,9 +630,9 @@ def test_inference(): if isinstance(y_pred, tuple): # ad3 produces an integer result if it found the exact solution #np.set_printoptions(precision=2, threshold=9999) - assert_array_almost_equal(res[0], y_pred[0].reshape(-1, n_states), 5) - assert_array_almost_equal(res[1], y_pred[1], 5) - assert_array_equal(y, np.argmax(y_pred[0], axis=-1), 5) + assert_array_almost_equal(res[0], y_pred[0][0].reshape(-1, n_states), 5) + assert_array_almost_equal(res[1], y_pred[1][0], 5) + assert_array_equal(y, np.argmax(y_pred[0][0], axis=-1), 5) #for inference_method in get_installed(["lp", "ad3", "qpbo"]): # again, this time discrete predictions only From 417f291fd9c5772c261f902f566b05f23e65c152 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 13 Feb 2017 14:24:10 +0100 Subject: [PATCH 058/155] code cleaning --- .../node_type_edge_feature_graph_crf.py | 131 ++---------------- 1 file changed, 10 insertions(+), 121 deletions(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index 09073161..ea497fba 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -3,8 +3,6 @@ """ Pairwise CRF with features/strength associated to each edge and different types of nodes - - Copyright Xerox(C) 2017 JL. Meunier This program is free software: you can redistribute it and/or modify @@ -60,12 +58,12 @@ class NodeTypeEdgeFeatureGraphCRF(TypedCRF): a_n_edge_features: an array of shape (n_types, n_types) giving the number of features per pair of types NOTE: there should always be at least 1 feature for any pairs of types which has some edge in the graph. + To mimic GraphCRF, pass 1 and make a constant feature of 1.0 for all those edges. - class_weight : None, or list of array-like + class_weight : None, or list of array-like (ndim=1) Class weights. If a list of array-like is passed, the Ith one must have length equal to l_n_states[i] None means equal class weights (across node types) - X and Y ------- Node features are given as a list of n_types arrays of shape (n_type_nodes, n_type_features): @@ -81,7 +79,10 @@ class NodeTypeEdgeFeatureGraphCRF(TypedCRF): An instance ``X`` is represented as a tuple ``([node_features, ..], [edges, ..], [edge_features, ..])`` - Labels ``Y`` are given as one array of shape (n_nodes) The meaning of a label depends upon the node type. + Labels ``Y`` are given as one array of shape (n_nodes) + Labels are numbered from 0 so that each label across types is encoded by a unique integer. + + Look at flattenY and unflattentY if you want to pass/obtain list of labels per type, with first label of each type being encoded by 0 """ @@ -176,8 +177,6 @@ def _get_pairwise_potentials_initialize(self): Putting in cache the params required to build the pairwise potentials given x and w """ self._cache_pairwise_potentials = list() -# i_w, n_states1, n_states2, i_states1, i_states2 = 0, 0, 0, 0, 0 -# for (typ1, typ2) in self._iter_type_pairs(): i_w, n_states1, i_states1 = 0, 0, 0 @@ -235,32 +234,6 @@ def _get_pairwise_potentials(self, x, w): i_w += n_w return l_pairwise_potentials -# -# self._check_size_w(w) -# #self._check_size_x(x) #call initialize once and only once before!! -# -# l_edge_features = self._get_edge_features(x) -# l_edge_nb = [0 if ef is None else ef.shape[0] for ef in l_edge_features] -# n_edges_total = sum(l_edge_nb) -# -# wpw = w[self.size_unaries:] -# a_edges_states_states = np.zeros((n_edges_total, self._n_states, self._n_states), dtype=w.dtype) -# -# i_edges = 0 -# for ((n_features, n_states1, n_states2, i_states1, i_states1_stop, i_states2, i_states2_stop, i_w, i_w_stop) -# , edge_features, n_edges) in zip(self._cache_pairwise_potentials, l_edge_features, l_edge_nb): -# -# i_edges_stop = i_edges + n_edges -# -# if not edge_features is None: -# pw_typ_typ = wpw[i_w:i_w_stop].reshape(n_features, -1) # n_states1*n_states2 x nb_feat -# pot_typ_typ = np.dot(edge_features, pw_typ_typ).reshape(n_edges, n_states1, n_states2) -# a_edges_states_states[ i_edges:i_edges_stop, i_states1:i_states1_stop , i_states2:i_states2_stop ] = pot_typ_typ -# -# i_edges = i_edges_stop -# -# return a_edges_states_states.reshape(n_edges_total, self._n_states, self._n_states) - def joint_feature(self, x, y): """Feature vector associated with instance (x, y). @@ -284,8 +257,6 @@ def joint_feature(self, x, y): Feature vector associated with state (x, y). """ -# print "x=", `x` -# print "y=", `y` self._check_size_x(x) #call initialize once! l_node_features = self._get_node_features(x, True) l_edges, l_edge_features = self._get_edges(x), self._get_edge_features(x, True) @@ -295,16 +266,14 @@ def joint_feature(self, x, y): n_edges = sum(l_n_edges) if isinstance(y, tuple): - #print "y=", `y` # y is result of relaxation, tuple of unary and pairwise marginals unary_marginals, pw = y - #I tried to have the ad3+ inference to return lists, but the learner then fails... - #I do not want to interfere wit hit, so I "mangle" /"unmangle" the data... - if isinstance(unary_marginals, list): + #ad3+ returns a list of unaries, nothing to do here!! :) l_unary_marginals = unary_marginals else: + #in case we use someother method (not supported for now actually) l_unary_marginals = [] i,j = 0,0 for (_n_nodes, _n_states) in zip(l_n_nodes, self.l_n_states): #iteration by type @@ -315,6 +284,7 @@ def joint_feature(self, x, y): l_unary_marginals.append(_unary_marginals) if isinstance(pw, list): + #ad3+ returns a list of pairwise l_pw = pw else: #until we do better in ad3+ inference, but we cannot I think without touching the learners... @@ -365,47 +335,11 @@ def joint_feature(self, x, y): #PW l_pw_ravelled = [np.dot(ef.T, pw).ravel() for (ef, pw) in zip(l_edge_features, l_pw)] -# l_pw_ravelled = [np.zeros((n_edge_states,)) if pw is None else np.dot(ef.T, pw).ravel() for (ef, pw, n_edge_states) in zip(l_edge_features, l_pw, self.l_n_edge_states)] pairwise_acc_ravelled = np.hstack(l_pw_ravelled) -# #assign the edges feature to the right range of columns, depending on edge type -# all_edge_features = np.zeros( (n_edges, self._n_edge_features) ) -# i_start = 0 -# i_col_start = 0 -# for edge_features, n_feat in zip(l_edge_features, self.a_n_edge_features.ravel()): -# i_col_stop = i_col_start + n_feat -# -# if not edge_features is None: -# nb_edges = edge_features.shape[0] -# i_stop = i_start + nb_edges -# all_edge_features[ i_start:i_stop -# , i_col_start:i_col_stop ] = edge_features -# i_start = i_stop -# i_col_start = i_col_stop -# -# pairwise_acc = np.dot(all_edge_features.T, pw) # sum_of_features x edge_states - -# This forced symetry / antisymetry is not supported for now -# for i in self.symmetric_edge_features: -# pw_ = pw[i].reshape(self.n_states, self.n_states) -# pw[i] = (pw_ + pw_.T).ravel() / 2. -# -# for i in self.antisymmetric_edge_features: -# pw_ = pw[i].reshape(self.n_states, self.n_states) -# pw[i] = (pw_ - pw_.T).ravel() / 2. - - #we need to linearize it, while keeping only meaningful data -# unaries_acc_ravelled = self._block_ravel(unaries_acc, [(0,0)]+zip(np.cumsum(self.l_n_states), np.cumsum(self.l_n_features))) -# assert len(unaries_acc_ravelled) == self.size_unaries - -# L1 = np.cumsum(self.a_n_edge_features.ravel()) -# L2 = np.cumsum([self.l_n_states[typ1] * self.l_n_states[typ2] for typ1, typ2 in self._iter_type_pairs() ]) -# pairwise_acc_ravelled = self._block_ravel(pairwise_acc, [(0,0)]+zip(L1,L2)) -# -# assert len(pairwise_acc_ravelled) == self.size_pairwise joint_feature_vector = np.hstack([unaries_acc_ravelled, pairwise_acc_ravelled]) - assert joint_feature_vector.shape[0] == self.size_joint_feature, (joint_feature_vector.shape[0], self.size_joint_feature) + #assert joint_feature_vector.shape[0] == self.size_joint_feature, (joint_feature_vector.shape[0], self.size_joint_feature) return joint_feature_vector @@ -465,9 +399,6 @@ def loss_augmented_inference(self, x, y, w, relaxed=False, i_start = 0 a_y = np.asarray(y) - #REF loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) - - for typ, (unary_potentials, class_weight) in enumerate(zip(l_unary_potentials, self.l_class_weight)): n_y = unary_potentials.shape[0] y_typ = a_y[i_start:i_start+n_y] - self._l_type_startindex[typ] #label 0 must correspond to 1st weight @@ -476,54 +407,17 @@ def loss_augmented_inference(self, x, y, w, relaxed=False, if self.inference_method == "ad3+": - l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] - nodetype_data = (l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type Y_pred = inference_dispatch(l_unary_potentials, l_pairwise_potentials, edges, self.inference_method, relaxed=relaxed, return_energy=return_energy) -# nodetype=nodetype_data) #with ad3+ this should never occur if not isinstance(Y_pred, tuple): assert self._check_size_xy(x, Y_pred), "Internal error in AD3+: inconsistent labels" else: raise Exception("You must use ad3+ as inference method") - #if self.inference_calls % 1000 == 0: print "%d inference calls"%self.inference_calls return Y_pred -# self.inference_calls += 1 -# self._check_size_w(w) -# unary_potentials = self._get_unary_potentials(x, w) -# pairwise_potentials = self._get_pairwise_potentials(x, w) -# flat_edges = self._index_all_edges(x) -# -# loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) -# -# if self.inference_method == "ad3+": -# l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] -# nodetype_data = (l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type -# -# Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, -# self.inference_method, relaxed=relaxed, -# return_energy=return_energy, -# nodetype=nodetype_data) -# #with ad3+ this should never occur -# if not isinstance(Y_pred, tuple): assert self._check_size_xy(x, Y_pred), "Internal error in AD3+: inconsistent labels" -# else: -# Y_pred = inference_dispatch(unary_potentials, pairwise_potentials, flat_edges, -# self.inference_method, relaxed=relaxed, -# return_energy=return_energy) -# #no nodetype parameter! -# #we may have inconsistent labels! -# try: -# if not isinstance(Y_pred, tuple): self._check_size_xy(x, Y_pred) -# except InconsistentLabel: -# #the inference engine predicted inconsistent labels -# Y_pred = self.fix_Y_at_random(x, Y_pred) -# -# #if self.inference_calls % 1000 == 0: print "%d inference calls"%self.inference_calls -# -# return Y_pred # def fix_Y_at_random(self, x, Y_pred): # print "\tY is BAD, FIXING IT AT RANDOM", `Y_pred` @@ -594,11 +488,6 @@ def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): l_pairwise_potentials = self._get_pairwise_potentials(x, w) edges = self._get_edges(x, True) - l_n_nodes = [nf.shape[0] for nf in self._get_node_features(x, True)] - assert l_n_nodes == [un.shape[0] for un in l_unary_potentials] - - nodetype_data=(l_n_nodes, self.l_n_states) #the type of the nodes, the number of state by type - if self.inference_method == "ad3+": Y_pred = inference_dispatch(l_unary_potentials, l_pairwise_potentials, edges, self.inference_method, relaxed=relaxed, From 95ce1fc3817fd3d02610cb9b33e9de87bd45b9fa Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 13 Feb 2017 15:09:05 +0100 Subject: [PATCH 059/155] 0.3.2 --- pystruct/__init__.py | 2 +- setup.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pystruct/__init__.py b/pystruct/__init__.py index 260c070a..f9aa3e11 100644 --- a/pystruct/__init__.py +++ b/pystruct/__init__.py @@ -1 +1 @@ -__version__ = "0.3.1" +__version__ = "0.3.2" diff --git a/setup.py b/setup.py index 82ff95b4..62e4cd10 100644 --- a/setup.py +++ b/setup.py @@ -10,8 +10,8 @@ include_dirs = [np.get_include()] setup(name="pystruct", - version="0.3.1", - install_requires=["ad3>=2.1.0"], + version="0.3.2", + install_requires=["ad3>=2.1.1"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', 'pystruct.tests', 'pystruct.tests.test_learners', From 3353986e5da6c250a6c0747295e2c1bf8b46b9ed Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 14 Feb 2017 15:18:35 +0100 Subject: [PATCH 060/155] the loss augmentation of the unaires is noz encapsulated in a method for possible specialization by sub class --- pystruct/models/crf.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/pystruct/models/crf.py b/pystruct/models/crf.py index c042fe06..855bdf93 100644 --- a/pystruct/models/crf.py +++ b/pystruct/models/crf.py @@ -52,6 +52,13 @@ def _check_size_x(self, x): " got %s instead." % (self.n_features, features.shape[1])) + def loss_augment_unaries(self, unary_potentials, y): + """ + we define it as a method so that subclasses can specialize it. + """ + loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) + + def loss_augmented_inference(self, x, y, w, relaxed=False, return_energy=False): """Loss-augmented Inference for x relative to y using parameters w. @@ -103,8 +110,10 @@ def loss_augmented_inference(self, x, y, w, relaxed=False, unary_potentials = self._get_unary_potentials(x, w) pairwise_potentials = self._get_pairwise_potentials(x, w) edges = self._get_edges(x) - loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) - + + #loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) + self.loss_augment_unaries(unary_potentials, y) + return inference_dispatch(unary_potentials, pairwise_potentials, edges, self.inference_method, relaxed=relaxed, return_energy=return_energy) From 94406dbb814dd5ced6daab9e97a3aded0c286623 Mon Sep 17 00:00:00 2001 From: meunier Date: Tue, 14 Feb 2017 15:20:45 +0100 Subject: [PATCH 061/155] - inherits now from CRF - setInferenceMethod method available --- pystruct/models/typed_crf.py | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index d7be0ec1..494dc092 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -28,14 +28,14 @@ """ import numpy as np -from .base import StructuredModel +from .crf import CRF from ..inference import get_installed class InconsistentLabel(Exception): pass -class TypedCRF(StructuredModel): +class TypedCRF(CRF): """Abstract base class""" def __init__(self , n_types #how many node type? @@ -44,12 +44,11 @@ def __init__(self , inference_method="ad3+" , l_class_weight=None): #class_weight per node type or None or None - StructuredModel.__init__(self) - if inference_method is None: # get first in list that is installed - inference_method = get_installed(['ad3+', 'ad3', 'max-product', 'lp'])[0] - self.inference_method = inference_method + inference_method = get_installed(['ad3+', 'ad3'])[0] + self.setInferenceMethod(inference_method) + self.inference_calls = 0 self.inference_exception = False #if inference cannot be done, raises an exception @@ -62,7 +61,7 @@ def __init__(self self._n_states = sum(l_n_states) #total number of states self.l_n_features = l_n_features self._n_features = sum(self.l_n_features) #total number of (node) features - + #number of typextype states, or number of states per type of edge self.l_n_edge_states = [ n1 * n2 for n1 in self.l_n_states for n2 in self.l_n_states ] @@ -96,6 +95,12 @@ def __init__(self i_state_start += typ1_n_states*typ2_n_states # -------------- CONVENIENCE -------------------------- + def setInferenceMethod(self, inference_method): + if inference_method in ["ad3", "ad3+"]: + self.inference_method = inference_method + else: + raise Exception("You must use ad3 or ad3+ as inference method") + def flattenY(self, lY_by_typ): """ It is more convenient to have the Ys grouped by type, as the Xs are, and to have the first label of each type encoded as 0. @@ -216,11 +221,8 @@ def _get_node_features(self, x, bClean=False): else: return x[0] - def _get_edges(self, x, bClean=False): - if bClean: - return [ np.empty((0,0)) if edges is None or len(edges)==0 else edges for edges in x[1]] - else: - return x[1] + def _get_edges(self, x): + return [ np.empty((0,2)) if edges is None or len(edges)==0 else edges for edges in x[1]] def _get_edges_by_type(self, x, typ1, typ2): return x[1][typ1*self.n_types+typ2] From 0ce95eecc1cf1804962b1248bb7f155772f610d5 Mon Sep 17 00:00:00 2001 From: meunier Date: Tue, 14 Feb 2017 15:26:28 +0100 Subject: [PATCH 062/155] - the 2 inference methods are now inherited!! - loss-augmentation method --- .../node_type_edge_feature_graph_crf.py | 168 ++---------------- 1 file changed, 12 insertions(+), 156 deletions(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index ea497fba..8bb218da 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -164,13 +164,10 @@ def _check_size_x(self, x): raise ValueError("Types %d x %d: bad number of edge features. expected %d got %d"%(typ1,typ2, self.a_n_edge_features[typ1,typ2], edge_features.shape[1])) return True - def _get_edge_features(self, x, bClean=False): - if bClean: - #we replace None by empty array with proper shape - return [ np.empty((0,_n_feat)) if _ef is None else _ef - for _ef, _n_feat in zip(x[2], self.l_n_edge_features)] - else: - return x[2] + def _get_edge_features(self, x): + #we replace None by empty array with proper shape + return [ np.empty((0,_n_feat)) if _ef is None else _ef + for _ef, _n_feat in zip(x[2], self.l_n_edge_features)] def _get_pairwise_potentials_initialize(self): """ @@ -215,7 +212,7 @@ def _get_pairwise_potentials(self, x, w): """ self._check_size_w(w) - l_edge_features = self._get_edge_features(x, True) + l_edge_features = self._get_edge_features(x) wpw = w[self.size_unaries:] l_pairwise_potentials = [] @@ -259,9 +256,9 @@ def joint_feature(self, x, y): """ self._check_size_x(x) #call initialize once! l_node_features = self._get_node_features(x, True) - l_edges, l_edge_features = self._get_edges(x), self._get_edge_features(x, True) - l_n_nodes = [len(nf) for nf in self._get_node_features(x, True)] - l_n_edges = [len(ef) for ef in self._get_edges (x, True)] + l_edges, l_edge_features = self._get_edges(x), self._get_edge_features(x) + l_n_nodes = [len(nf) for nf in self._get_node_features(x)] + l_n_edges = [len(ef) for ef in self._get_edges (x)] n_nodes = sum(l_n_nodes) n_edges = sum(l_n_edges) @@ -343,59 +340,10 @@ def joint_feature(self, x, y): return joint_feature_vector - - def loss_augmented_inference(self, x, y, w, relaxed=False, - return_energy=False): - """Loss-augmented Inference for x relative to y using parameters w. - - Finds (approximately) - armin_y_hat np.dot(w, joint_feature(x, y_hat)) + loss(y, y_hat) - using self.inference_method. - - - Parameters - ---------- - x : tuple - Instance of a graph with unary evidence. - x=(unaries, edges) - unaries are an nd-array of shape (n_nodes, n_features), - edges are an nd-array of shape (n_edges, 2) - - y : ndarray, shape (n_nodes,) - Ground truth labeling relative to which the loss - will be measured. - - w : ndarray, shape=(size_joint_feature,) - Parameters for the CRF energy function. - - relaxed : bool, default=False - Whether relaxed inference should be performed. - Only meaningful if inference method is 'lp' or 'ad3'. - By default fractional solutions are rounded. If relaxed=True, - fractional solutions are returned directly. - - return_energy : bool, default=False - Whether to return the energy of the solution (x, y) that was found. - - Returns - ------- - y_pred : ndarray or tuple - By default an inter ndarray of shape=(n_nodes) - of variable assignments for x is returned. - If ``relaxed=True`` and inference_method is ``lp`` or ``ad3``, - a tuple (unary_marginals, pairwise_marginals) - containing the relaxed inference result is returned. - unary marginals is an array of shape (n_nodes, n_states), - pairwise_marginals is an array of - shape (n_states, n_states) of accumulated pairwise marginals. - + def loss_augment_unaries(self, l_unary_potentials, y): + """ + we do it type-wise """ - self.inference_calls += 1 - self._check_size_w(w) - l_unary_potentials = self._get_unary_potentials(x, w) - l_pairwise_potentials = self._get_pairwise_potentials(x, w) - edges = self._get_edges(x, True) - i_start = 0 a_y = np.asarray(y) @@ -404,97 +352,5 @@ def loss_augmented_inference(self, x, y, w, relaxed=False, y_typ = a_y[i_start:i_start+n_y] - self._l_type_startindex[typ] #label 0 must correspond to 1st weight loss_augment_unaries(unary_potentials, y_typ, class_weight) i_start += n_y + - - if self.inference_method == "ad3+": - - Y_pred = inference_dispatch(l_unary_potentials, l_pairwise_potentials, edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy) - #with ad3+ this should never occur - if not isinstance(Y_pred, tuple): assert self._check_size_xy(x, Y_pred), "Internal error in AD3+: inconsistent labels" - else: - raise Exception("You must use ad3+ as inference method") - - return Y_pred - - -# def fix_Y_at_random(self, x, Y_pred): -# print "\tY is BAD, FIXING IT AT RANDOM", `Y_pred` -# -# l_node_features = self._get_node_features(x, True) -# i_start = 0 -# for typ, (nf, n_states) in enumerate(zip(l_node_features, self.l_n_states)): -# nb_nodes = nf.shape[0] -# if nb_nodes: -# Y_typ = Y_pred[i_start:i_start+nb_nodes] -# typ_start = self._l_type_startindex[typ] -# typ_end = self._l_type_startindex[typ+1] -# if np.min(Y_typ) < typ_start or typ_end <= np.max(Y_typ): -# for i in range(nb_nodes): -# if Y_pred[i_start+i] < typ_start or typ_end <= Y_pred[i_start+i]: Y_pred[i_start+i] = random.randint(typ_start, typ_end-1) -# i_start = i_start + nb_nodes -# self._check_size_xy(x, Y_pred) -# return Y_pred -# - def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): - """Inference for x using parameters w. - - Finds (approximately) - armin_y np.dot(w, joint_feature(x, y)) - using self.inference_method. - - - Parameters - ---------- - x : tuple - Instance of a graph with unary evidence. - x=(unaries, edges) - unaries are an nd-array of shape (n_nodes, n_states), - edges are an nd-array of shape (n_edges, 2) - - w : ndarray, shape=(size_joint_feature,) - Parameters for the CRF energy function. - - relaxed : bool, default=False - Whether relaxed inference should be performed. - Only meaningful if inference method is 'lp' or 'ad3'. - By default fractional solutions are rounded. If relaxed=True, - fractional solutions are returned directly. - - return_energy : bool, default=False - Whether to return the energy of the solution (x, y) that was found. - - constraints : None or list, default=False - hard logic constraints, if any - - Returns - ------- - y_pred : ndarray or tuple - By default an inter ndarray of shape=(width, height) - of variable assignments for x is returned. - If ``relaxed=True`` and inference_method is ``lp`` or ``ad3``, - a tuple (unary_marginals, pairwise_marginals) - containing the relaxed inference result is returned. - unary marginals is an array of shape (width, height, n_states), - pairwise_marginals is an array of - shape (n_states, n_states) of accumulated pairwise marginals. - - """ - self._check_size_w(w) - self.inference_calls += 1 - self.initialize(x) - l_unary_potentials = self._get_unary_potentials(x, w) - l_pairwise_potentials = self._get_pairwise_potentials(x, w) - edges = self._get_edges(x, True) - - if self.inference_method == "ad3+": - Y_pred = inference_dispatch(l_unary_potentials, l_pairwise_potentials, edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy, - constraints=constraints, - inference_exception=self.inference_exception) #<-- - else: - raise Exception("You must use ad3+ as inference method") - - return Y_pred From 5066668769e5b2d6a78cbbdc142f13880d3e51ee Mon Sep 17 00:00:00 2001 From: meunier Date: Tue, 14 Feb 2017 15:27:37 +0100 Subject: [PATCH 063/155] ad3 can now deal with multitype CRFs --- pystruct/inference/inference_methods.py | 53 +++++++++++++++++++------ 1 file changed, 41 insertions(+), 12 deletions(-) diff --git a/pystruct/inference/inference_methods.py b/pystruct/inference/inference_methods.py index d285c48e..d2172cc3 100644 --- a/pystruct/inference/inference_methods.py +++ b/pystruct/inference/inference_methods.py @@ -320,7 +320,8 @@ def inference_lp(unary_potentials, pairwise_potentials, edges, relaxed=False, def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, - verbose=0, return_energy=False, branch_and_bound=False): + verbose=0, return_energy=False, branch_and_bound=False, + inference_exception=None): """Inference with AD3 dual decomposition subgradient solver. Parameters @@ -359,23 +360,50 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, labels : nd-array Approximate (usually) MAP variable assignment. If relaxed=False, this is a tuple of unary and edge 'marginals'. + + Code updated on Feb 2017 to deal with multiple node types, by JL Meunier, for the EU READ project (grant agreement No 674943) + Copyright JL Meunier, Xerox 2017 """ import ad3 - n_states, pairwise_potentials = \ - _validate_params(unary_potentials, pairwise_potentials, edges) - unaries = unary_potentials.reshape(-1, n_states) - res = ad3.general_graph(unaries, edges, pairwise_potentials, verbose=verbose, + bMultiType = isinstance(unary_potentials, list) + if bMultiType: + res = ad3.general_graph(unary_potentials, edges, pairwise_potentials, verbose=verbose, + n_iterations=4000, exact=branch_and_bound) + else: + #usual code + n_states, pairwise_potentials = \ + _validate_params(unary_potentials, pairwise_potentials, edges) + unaries = unary_potentials.reshape(-1, n_states) + res = ad3.general_graph(unaries, edges, pairwise_potentials, verbose=verbose, n_iterations=4000, exact=branch_and_bound) + unary_marginals, pairwise_marginals, energy, solver_status = res if verbose: - print(solver_status[0]) + print(solver_status) if solver_status in ["fractional", "unsolved"] and relaxed: - unary_marginals = unary_marginals.reshape(unary_potentials.shape) - y = (unary_marginals, pairwise_marginals) + if bMultiType: + y = (unary_marginals, pairwise_marginals) #those two are lists + else: + #usual code + unary_marginals = unary_marginals.reshape(unary_potentials.shape) + y = (unary_marginals, pairwise_marginals) #print solver_status, pairwise_marginals else: - y = np.argmax(unary_marginals, axis=-1) + if bMultiType: + #we now get a list of unary marginals + if inference_exception and solver_status in ["fractional", "unsolved"]: + raise InferenceException(solver_status) + ly = list() + _cum_n_states = 0 + for unary_marg in unary_marginals: + ly.append( _cum_n_states + np.argmax(unary_marg, axis=-1) ) + _cum_n_states += unary_marg.shape[1] #number of states for that type + y = np.hstack(ly) + else: + #usual code + y = np.argmax(unary_marginals, axis=-1) + if return_energy: return y, -energy return y @@ -428,14 +456,15 @@ def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges, relaxe NOTE: this hard logic constraint mechanism has been developed for the EU project READ, by JL Meunier (Xerox), in November 2016. The READ project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. - nodetype : internal use for NodeTypeEdgeFeatureGraphCRF model - NOTE: developed for the EU project READ (grant agreement No 674943), by JL Meunier (Xerox), in Q1 2017. - Returns ------- labels : nd-array Approximate (usually) MAP variable assignment. If relaxed=False, this is a tuple of unary and edge 'marginals'. + + Code written on Feb 2017 to deal with multiple node types, by JL Meunier, for the EU READ project (grant agreement No 674943) + Copyright JL Meunier, Xerox 2017 + """ import ad3 # n_states, pairwise_potentials = \ From 569150eabe3f25e3147d0764bad72237598a325a Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 14 Feb 2017 17:14:41 +0100 Subject: [PATCH 064/155] ok --- .../node_type_edge_feature_graph_crf.py | 2 +- .../test_node_type_edge_feature_graph_crf.py | 76 +++++++++++++------ 2 files changed, 54 insertions(+), 24 deletions(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index 8bb218da..d23d106e 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -20,7 +20,7 @@ Developed for the EU project READ. The READ project has received funding - from the European Union�s Horizon 2020 research and innovation programme + from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. """ diff --git a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py index f15e5a1b..6ed8e9d8 100644 --- a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py +++ b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py @@ -582,7 +582,7 @@ def report_model_config(crf): print crf.n_features print crf.n_edge_features -def test_inference(): +def inference_data(): """ Testing with a single type of nodes. Must do as well as EdgeFeatureGraphCRF """ @@ -618,30 +618,59 @@ def test_inference(): edge_features = edge_list_to_features(edge_list) x = ([x.reshape(-1, n_states)], [edges], [edge_features]) y = y.ravel() + return x, y, pw_horz, pw_vert, res, n_states - #for inference_method in get_installed(["lp", "ad3"]): - if True: - # same inference through CRF inferface - crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) # ad3 only is supported..., inference_method=inference_method) - crf.initialize(x, y) - #crf.initialize([x], [y]) - w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) - y_pred = crf.inference(x, w, relaxed=True) - if isinstance(y_pred, tuple): - # ad3 produces an integer result if it found the exact solution - #np.set_printoptions(precision=2, threshold=9999) - assert_array_almost_equal(res[0], y_pred[0][0].reshape(-1, n_states), 5) - assert_array_almost_equal(res[1], y_pred[1][0], 5) - assert_array_equal(y, np.argmax(y_pred[0][0], axis=-1), 5) +def test_inference_ad3plus(): + + x, y, pw_horz, pw_vert, res, n_states = inference_data() + # same inference through CRF inferface + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]] + , inference_method="ad3+") + crf.initialize(x, y) + #crf.initialize([x], [y]) + w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) + y_pred = crf.inference(x, w, relaxed=True) + if isinstance(y_pred, tuple): + # ad3 produces an integer result if it found the exact solution + #np.set_printoptions(precision=2, threshold=9999) + assert_array_almost_equal(res[0], y_pred[0][0].reshape(-1, n_states), 5) + assert_array_almost_equal(res[1], y_pred[1][0], 5) + assert_array_equal(y, np.argmax(y_pred[0][0], axis=-1), 5) - #for inference_method in get_installed(["lp", "ad3", "qpbo"]): # again, this time discrete predictions only - crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) - #crf.initialize([x], [y]) - w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) - crf.initialize(x) - y_pred = crf.inference(x, w, relaxed=False) - assert_array_equal(y, y_pred) + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]] + , inference_method="ad3+") + #crf.initialize([x], [y]) + w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) + crf.initialize(x) + y_pred = crf.inference(x, w, relaxed=False) + assert_array_equal(y, y_pred) + +def test_inference_ad3(): + + x, y, pw_horz, pw_vert, res, n_states = inference_data() + # same inference through CRF inferface + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]] + , inference_method="ad3") + crf.initialize(x, y) + #crf.initialize([x], [y]) + w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) + y_pred = crf.inference(x, w, relaxed=True) + if isinstance(y_pred, tuple): + # ad3 produces an integer result if it found the exact solution + #np.set_printoptions(precision=2, threshold=9999) + assert_array_almost_equal(res[0], y_pred[0][0].reshape(-1, n_states), 5) + assert_array_almost_equal(res[1], y_pred[1][0], 5) + assert_array_equal(y, np.argmax(y_pred[0][0], axis=-1), 5) + + # again, this time discrete predictions only + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]] + , inference_method="ad3") + #crf.initialize([x], [y]) + w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) + crf.initialize(x) + y_pred = crf.inference(x, w, relaxed=False) + assert_array_equal(y, y_pred) def test_joint_feature_discrete(): """ @@ -795,7 +824,8 @@ def test_energy_discrete(): if 1: test_unary_potentials() # if 1: test_inference_util() - if 1: test_inference() + if 1: test_inference_ad3() + if 1: test_inference_ad3plus() if 1: test_joint_feature_discrete() if 1: test_joint_feature_continuous() if 1: test_energy_continuous() From f75c66a194c650dcabb0c8477beb5f9cf1ff5a07 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 14 Feb 2017 17:46:07 +0100 Subject: [PATCH 065/155] 0.3.3 --- pystruct/__init__.py | 2 +- setup.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/pystruct/__init__.py b/pystruct/__init__.py index f9aa3e11..e19434e2 100644 --- a/pystruct/__init__.py +++ b/pystruct/__init__.py @@ -1 +1 @@ -__version__ = "0.3.2" +__version__ = "0.3.3" diff --git a/setup.py b/setup.py index 62e4cd10..c3ebaaf7 100644 --- a/setup.py +++ b/setup.py @@ -10,8 +10,8 @@ include_dirs = [np.get_include()] setup(name="pystruct", - version="0.3.2", - install_requires=["ad3>=2.1.1"], + version="0.3.3", + install_requires=["ad3>=2.1.2"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', 'pystruct.tests', 'pystruct.tests.test_learners', From 9f65776053c38b59b121a38c90a941ba752345f4 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 15 Feb 2017 09:12:16 +0100 Subject: [PATCH 066/155] comment for ad3+ failure --- pystruct/tests/test_models/test_grid_crf.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pystruct/tests/test_models/test_grid_crf.py b/pystruct/tests/test_models/test_grid_crf.py index cc953a9f..1bc178d0 100644 --- a/pystruct/tests/test_models/test_grid_crf.py +++ b/pystruct/tests/test_models/test_grid_crf.py @@ -121,6 +121,7 @@ def test_blocks_multinomial_crf(): -.3, .3, -.5, -.1, .3]) for inference_method in get_installed(): + #NOTE: ad3+ fails because it requires a different data structure crf = GridCRF(inference_method=inference_method) crf.initialize(X, Y) y_hat = crf.inference(x, w) From 61ced542b123d4c267ca4e204bd9623c0bc19515 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 15 Feb 2017 09:13:37 +0100 Subject: [PATCH 067/155] log of the test of 0.3.3 --- pystruct/tests/pytest-0.3.3.log | 703 ++++++++++++++++++++++++++++++++ 1 file changed, 703 insertions(+) create mode 100644 pystruct/tests/pytest-0.3.3.log diff --git a/pystruct/tests/pytest-0.3.3.log b/pystruct/tests/pytest-0.3.3.log new file mode 100644 index 00000000..572d4d7a --- /dev/null +++ b/pystruct/tests/pytest-0.3.3.log @@ -0,0 +1,703 @@ +============================= test session starts ============================== +platform linux2 -- Python 2.7.8, pytest-3.0.5, py-1.4.32, pluggy-0.4.0 +rootdir: /opt/project/read/jl_git/pystruct_JL, inifile: +collected 150 items + +test_datasets.py . +test_libraries.py FF +test_inference/test_exact_inference.py . +test_inference/test_maxprod.py ..FF..FF +test_learners/test_binary_svm.py ....... +test_learners/test_crammer_singer_svm.py ......... +test_learners/test_edge_feature_graph_learning.py .. +test_learners/test_frankwolfe_svm.py .... +test_learners/test_graph_svm.py ... +test_learners/test_latent_node_crf_learning.py F.... +test_learners/test_latent_svm.py ..... +test_learners/test_n_slack_ssvm.py ......... +test_learners/test_one_slack_ssvm.py ........ +test_learners/test_perceptron.py ....... +test_learners/test_structured_perceptron.py .. +test_learners/test_subgradient_latent_svm.py ... +test_learners/test_subgradient_svm.py ...... +test_models/test_chain_crf.py .F +test_models/test_directional_crf.py .... +test_models/test_edge_feature_graph_crf.py ...... +test_models/test_graph_crf.py ......... +test_models/test_grid_crf.py .....FF... +test_models/test_latent_crf.py .............. +test_models/test_latent_node_crf.py ..... +test_models/test_multilabel_problem.py ... +test_models/test_node_type_edge_feature_graph_crf.py ........... +test_utils/test_utils_inference.py ... +test_utils/test_utils_logging.py . + +=================================== FAILURES =================================== +_________________________________ test_pyqpbo __________________________________ + + def test_pyqpbo(): + import pyqpbo + pyqpbo +> assert 'qpbo' in get_installed() + +test_libraries.py:7: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +../inference/inference_methods.py:17: in get_installed + inference_dispatch(unary, pw, edges, inference_method=method) +../inference/inference_methods.py:100: in inference_dispatch + return_energy=return_energy, **kwargs) +../inference/inference_methods.py:474: in inference_ad3plus + n_iterations=4000, exact=branch_and_bound) +../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:44: in general_constrained_graph + return general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose, n_iterations, eta, exact) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +unaries = array([[ 0.]]), edges = array([], shape=(0, 2), dtype=int64) +edge_weights = array([[ 0.]]), constraints = None, verbose = 0 +n_iterations = 4000, eta = 0.1, exact = False + + def general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose=1, n_iterations=1000, eta=0.1, exact=False): + """ + inference on a graph, with one type of node, taking into account logical constraints between unaries. + + The constraints must be a list of tuples like ( , , , ) + The tuple is defined differently for single- and multi-type inference. See in each function below. + + where: + - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - unaries is a list of the index of the unaries involved in this constraint + - states is a list of unary states, 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. + - negated is a list of boolean indicated if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list + + The graph is binarized as explained in Martins et al. ICML 2011 paper: "An Augmented Lagrangian Approach to Constrained MAP Inference". + + NOTE: I had to re-compile AD3 since v2.0.1 from Anaconda missed the create_binary_variable method + + JL Meunier - October 2016 + """ + if unaries.shape[1] != edge_weights.shape[1]: + raise ValueError("incompatible shapes of unaries" + " and edge_weights.") +> if edge_weights.shape[1] != edge_weights.shape[2]: +E IndexError: tuple index out of range + +../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:70: IndexError +___________________________________ test_ad3 ___________________________________ + + def test_ad3(): + import ad3 + ad3 +> assert 'ad3' in get_installed() + +test_libraries.py:13: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +../inference/inference_methods.py:17: in get_installed + inference_dispatch(unary, pw, edges, inference_method=method) +../inference/inference_methods.py:100: in inference_dispatch + return_energy=return_energy, **kwargs) +../inference/inference_methods.py:474: in inference_ad3plus + n_iterations=4000, exact=branch_and_bound) +../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:44: in general_constrained_graph + return general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose, n_iterations, eta, exact) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +unaries = array([[ 0.]]), edges = array([], shape=(0, 2), dtype=int64) +edge_weights = array([[ 0.]]), constraints = None, verbose = 0 +n_iterations = 4000, eta = 0.1, exact = False + + def general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose=1, n_iterations=1000, eta=0.1, exact=False): + """ + inference on a graph, with one type of node, taking into account logical constraints between unaries. + + The constraints must be a list of tuples like ( , , , ) + The tuple is defined differently for single- and multi-type inference. See in each function below. + + where: + - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - unaries is a list of the index of the unaries involved in this constraint + - states is a list of unary states, 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. + - negated is a list of boolean indicated if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list + + The graph is binarized as explained in Martins et al. ICML 2011 paper: "An Augmented Lagrangian Approach to Constrained MAP Inference". + + NOTE: I had to re-compile AD3 since v2.0.1 from Anaconda missed the create_binary_variable method + + JL Meunier - October 2016 + """ + if unaries.shape[1] != edge_weights.shape[1]: + raise ValueError("incompatible shapes of unaries" + " and edge_weights.") +> if edge_weights.shape[1] != edge_weights.shape[2]: +E IndexError: tuple index out of range + +../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:70: IndexError +_________________________ test_tree_max_product_chain __________________________ + + def test_tree_max_product_chain(): + rnd = np.random.RandomState(0) + forward = np.c_[np.arange(9), np.arange(1, 10)] + backward = np.c_[np.arange(1, 10), np.arange(9)] + for i in range(10): + unary_potentials = rnd.normal(size=(10, 3)) + pairwise_potentials = rnd.normal(size=(9, 3, 3)) + for chain in [forward, backward]: + result_ad3 = inference_ad3(unary_potentials, pairwise_potentials, + chain, branch_and_bound=True) + result_mp = inference_max_product(unary_potentials, +> pairwise_potentials, chain) + +test_inference/test_maxprod.py:70: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +unary_potentials = array([[ 1.76405235, 0.40015721, 0.97873798], + [ 2.2408932 , 1.867557...62, -1.45436567, 0.04575852], + [-0.18718385, 1.53277921, 1.46935877]]) +pairwise_potentials = array([[[ 0.15494743, 0.37816252, -0.88778575], + [-1.98079647, -0.3479..., -0.41361898, -0.74745481], + [ 1.92294203, 1.48051479, 1.86755896]]]) +edges = array([[0, 1], + [1, 2], + [2, 3], + [3, 4], + [4, 5], + [5, 6], + [6, 7], + [7, 8], + [8, 9]]) +max_iter = 30, damping = 0.5, tol = 1e-05, relaxed = None + + def inference_max_product(unary_potentials, pairwise_potentials, edges, + max_iter=30, damping=0.5, tol=1e-5, relaxed=None): + """Max-product inference. + + In case the edges specify a tree, dynamic programming is used + producing a result in only a single pass. + + Parameters + ---------- + unary_potentials : nd-array + Unary potentials of energy function. + + pairwise_potentials : nd-array + Pairwise potentials of energy function. + + edges : nd-array + Edges of energy function. + + max_iter : int (default=10) + Maximum number of iterations. Ignored if graph is a tree. + + damping : float (default=.5) + Daming of messages in loopy message passing. + Ignored if graph is a tree. + + tol : float (default=1e-5) + Stopping tollerance for loopy message passing. + """ +> from ._viterbi import viterbi +E ImportError: No module named _viterbi + +../inference/maxprod.py:50: ImportError +__________________________ test_tree_max_product_tree __________________________ + + def test_tree_max_product_tree(): + try: + from scipy.sparse.csgraph import minimum_spanning_tree + except: + raise SkipTest("Not testing trees, scipy version >= 0.11 required") + + rnd = np.random.RandomState(0) + for i in range(100): + # generate random tree using mst + graph = rnd.uniform(size=(10, 10)) + tree = minimum_spanning_tree(sparse.csr_matrix(graph)) + tree_edges = np.c_[tree.nonzero()] + + unary_potentials = rnd.normal(size=(10, 3)) + pairwise_potentials = rnd.normal(size=(9, 3, 3)) + result_ad3 = inference_ad3(unary_potentials, pairwise_potentials, + tree_edges, branch_and_bound=True) + result_mp = inference_max_product(unary_potentials, +> pairwise_potentials, tree_edges) + +test_inference/test_maxprod.py:92: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +unary_potentials = array([[-1.16514984, 0.90082649, 0.46566244], + [-1.53624369, 1.488252...41, 1.94362119, -0.41361898], + [-0.74745481, 1.92294203, 1.48051479]]) +pairwise_potentials = array([[[ 1.86755896, 0.90604466, -0.86122569], + [ 1.91006495, -0.2680..., -1.10438334, 0.05216508], + [-0.739563 , 1.5430146 , -1.29285691]]]) +edges = array([[1, 4], + [1, 5], + [1, 6], + [3, 4], + [6, 0], + [7, 5], + [8, 2], + [8, 7], + [9, 7]], dtype=int32) +max_iter = 30, damping = 0.5, tol = 1e-05, relaxed = None + + def inference_max_product(unary_potentials, pairwise_potentials, edges, + max_iter=30, damping=0.5, tol=1e-5, relaxed=None): + """Max-product inference. + + In case the edges specify a tree, dynamic programming is used + producing a result in only a single pass. + + Parameters + ---------- + unary_potentials : nd-array + Unary potentials of energy function. + + pairwise_potentials : nd-array + Pairwise potentials of energy function. + + edges : nd-array + Edges of energy function. + + max_iter : int (default=10) + Maximum number of iterations. Ignored if graph is a tree. + + damping : float (default=.5) + Daming of messages in loopy message passing. + Ignored if graph is a tree. + + tol : float (default=1e-5) + Stopping tollerance for loopy message passing. + """ +> from ._viterbi import viterbi +E ImportError: No module named _viterbi + +../inference/maxprod.py:50: ImportError +________________________ test_max_product_binary_blocks ________________________ + + def test_max_product_binary_blocks(): + X, Y = generate_blocks(n_samples=1) + x, y = X[0], Y[0] + w = np.array([1, 0, # unary + 0, 1, + 0, # pairwise + -4, 0]) + crf = GridCRF(inference_method='max-product') + crf.initialize(X, Y) +> y_hat = crf.inference(x, w) + +test_inference/test_maxprod.py:139: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +../models/grid_crf.py:66: in inference + return_energy=return_energy) +../models/crf.py:178: in inference + return_energy=return_energy) +../inference/inference_methods.py:109: in inference_dispatch + edges, **kwargs) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +unary_potentials = array([[-1.64607852, 1.64607852], + [ 0.39976419, -0.39976419], + [...748486], + [-1.92111906, 1.92111906], + [-2.38331001, 2.38331001]]) +pairwise_potentials = array([[ 0., -4.], + [-4., 0.]]) +edges = array([[ 0, 1], + [ 1, 2], + [ 2, 3], + [ 3, 4], + ...], + [104, 116], + [105, 117], + [106, 118], + [107, 119]]) +max_iter = 30, damping = 0.5, tol = 1e-05, relaxed = False + + def inference_max_product(unary_potentials, pairwise_potentials, edges, + max_iter=30, damping=0.5, tol=1e-5, relaxed=None): + """Max-product inference. + + In case the edges specify a tree, dynamic programming is used + producing a result in only a single pass. + + Parameters + ---------- + unary_potentials : nd-array + Unary potentials of energy function. + + pairwise_potentials : nd-array + Pairwise potentials of energy function. + + edges : nd-array + Edges of energy function. + + max_iter : int (default=10) + Maximum number of iterations. Ignored if graph is a tree. + + damping : float (default=.5) + Daming of messages in loopy message passing. + Ignored if graph is a tree. + + tol : float (default=1e-5) + Stopping tollerance for loopy message passing. + """ +> from ._viterbi import viterbi +E ImportError: No module named _viterbi + +../inference/maxprod.py:50: ImportError +_______________________ test_max_product_multinomial_crf _______________________ + + def test_max_product_multinomial_crf(): + X, Y = generate_blocks_multinomial(n_samples=1) + x, y = X[0], Y[0] + w = np.array([1., 0., 0., # unary + 0., 1., 0., + 0., 0., 1., + .4, # pairwise + -.3, .3, + -.5, -.1, .3]) + crf = GridCRF(inference_method='max-product') + crf.initialize(X, Y) +> y_hat = crf.inference(x, w) + +test_inference/test_maxprod.py:154: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +../models/grid_crf.py:66: in inference + return_energy=return_energy) +../models/crf.py:178: in inference + return_energy=return_energy) +../inference/inference_methods.py:109: in inference_dispatch + edges, **kwargs) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +unary_potentials = array([[ 1.18821277e+00, -5.49700395e-01, 1.49119087e-01], + [ 1.663....65956844e+00], + [ -4.41209409e-01, 5.64297032e-01, 1.24800047e+00]]) +pairwise_potentials = array([[ 0.4, -0.3, -0.5], + [-0.3, 0.3, -0.1], + [-0.5, -0.1, 0.3]]) +edges = array([[ 0, 1], + [ 1, 2], + [ 2, 3], + [ 3, 4], + ...], + [104, 116], + [105, 117], + [106, 118], + [107, 119]]) +max_iter = 30, damping = 0.5, tol = 1e-05, relaxed = False + + def inference_max_product(unary_potentials, pairwise_potentials, edges, + max_iter=30, damping=0.5, tol=1e-5, relaxed=None): + """Max-product inference. + + In case the edges specify a tree, dynamic programming is used + producing a result in only a single pass. + + Parameters + ---------- + unary_potentials : nd-array + Unary potentials of energy function. + + pairwise_potentials : nd-array + Pairwise potentials of energy function. + + edges : nd-array + Edges of energy function. + + max_iter : int (default=10) + Maximum number of iterations. Ignored if graph is a tree. + + damping : float (default=.5) + Daming of messages in loopy message passing. + Ignored if graph is a tree. + + tol : float (default=1e-5) + Stopping tollerance for loopy message passing. + """ +> from ._viterbi import viterbi +E ImportError: No module named _viterbi + +../inference/maxprod.py:50: ImportError +_________________ test_binary_blocks_cutting_plane_latent_node _________________ + + def test_binary_blocks_cutting_plane_latent_node(): + #testing cutting plane ssvm on easy binary dataset + # we use the LatentNodeCRF without latent nodes and check that it does the + # same as GraphCRF + X, Y = generate_blocks(n_samples=3) + crf = GraphCRF() + clf = NSlackSSVM(model=crf, max_iter=20, C=100, check_constraints=True, + break_on_bad=False, n_jobs=1) + x1, x2, x3 = X + y1, y2, y3 = Y + n_states = len(np.unique(Y)) + # delete some rows to make it more fun + x1, y1 = x1[:, :-1], y1[:, :-1] + x2, y2 = x2[:-1], y2[:-1] + # generate graphs + X_ = [x1, x2, x3] + G = [make_grid_edges(x) for x in X_] + + # reshape / flatten x and y + X_ = [x.reshape(-1, n_states) for x in X_] + Y = [y.ravel() for y in [y1, y2, y3]] + + X = list(zip(X_, G)) + + clf.fit(X, Y) + Y_pred = clf.predict(X) + for y, y_pred in zip(Y, Y_pred): + assert_array_equal(y, y_pred) + + latent_crf = LatentNodeCRF(n_labels=2, n_hidden_states=0) + latent_svm = LatentSSVM(NSlackSSVM(model=latent_crf, max_iter=20, C=100, + check_constraints=True, + break_on_bad=False, n_jobs=1), + latent_iter=3) + X_latent = list(zip(X_, G, np.zeros(len(X_)))) +> latent_svm.fit(X_latent, Y, H_init=Y) + +test_learners/test_latent_node_crf_learning.py:59: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +../learners/latent_structured_svm.py:123: in fit + initialize=False) +../learners/n_slack_ssvm.py:313: in fit + for x, y in zip(X_b, Y_b)) +../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py:804: in __call__ + while self.dispatch_one_batch(iterator): +../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py:662: in dispatch_one_batch + self._dispatch(tasks) +../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py:570: in _dispatch + job = ImmediateComputeBatch(batch) +../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py:183: in __init__ + self.results = batch() +../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py:72: in __call__ + return [func(*args, **kwargs) for func, args, kwargs in self.items] +../utils/inference.py:65: in find_constraint + y_hat = model.loss_augmented_inference(x, y, w, relaxed=relaxed) +../models/latent_node_crf.py:217: in loss_augmented_inference + unary_potentials = self._get_unary_potentials(x, w) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +self = LatentNodeCRF(n_states: 2, inference_method: ad3) +x = (array([[-1.64607852, 1.64607852], + [ 0.39976419, -0.39976419], + [...087795], + [-0.76748486, 0.767... 2, 3], + [ 3, 4], + ...], + [ 95, 106], + [ 96, 107], + [ 97, 108], + [ 98, 109]]), 0.0) +w = array([ 0., 0., 0., 0., 0., 0., 0.]) + + def _get_unary_potentials(self, x, w): + """Computes unary potentials for x and w. + + Parameters + ---------- + x : tuple + Instance Representation. + + w : ndarray, shape=(size_joint_feature,) + Weight vector for CRF instance. + + Returns + ------- + unary : ndarray, shape=(n_states) + Unary weights. + """ + self._check_size_w(w) + self._check_size_x(x) + features = self._get_features(x) + unary_params = w[:self.n_input_states * self.n_features].reshape( + self.n_input_states, self.n_features) + + if self.latent_node_features: + unaries = np.dot(features, unary_params.T) + n_hidden = x[2] + n_visible = features.shape[0] - n_hidden + else: + # we only have features for visible nodes + n_visible, n_hidden = features.shape[0], x[2] + # assemble unary potentials for all nodes from observed evidence +> unaries = np.zeros((n_visible + n_hidden, self.n_states)) +E TypeError: 'numpy.float64' object cannot be interpreted as an index + +../models/latent_node_crf.py:202: TypeError +_____________________________ test_directed_chain ______________________________ + + def test_directed_chain(): + # check that a directed model actually works differntly in the two + # directions. chain of length three, three states 0, 1, 2 which want to be + # in this order, evidence only in the middle + x = np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) + + w = np.array([1, 0, 0, # unary + 0, 1, 0, + 0, 0, 1, + 0, 1, 0, # pairwise + 0, 0, 1, + 0, 0, 0]) + crf = ChainCRF(n_states=3, n_features=3) +> y = crf.inference(x, w) + +test_models/test_chain_crf.py:41: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +../models/crf.py:178: in inference + return_energy=return_energy) +../inference/inference_methods.py:109: in inference_dispatch + edges, **kwargs) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +unary_potentials = array([[0, 0, 0], + [0, 1, 0], + [0, 0, 0]]) +pairwise_potentials = array([[0, 1, 0], + [0, 0, 1], + [0, 0, 0]]) +edges = array([[0, 1], + [1, 2]]), max_iter = 30, damping = 0.5 +tol = 1e-05, relaxed = False + + def inference_max_product(unary_potentials, pairwise_potentials, edges, + max_iter=30, damping=0.5, tol=1e-5, relaxed=None): + """Max-product inference. + + In case the edges specify a tree, dynamic programming is used + producing a result in only a single pass. + + Parameters + ---------- + unary_potentials : nd-array + Unary potentials of energy function. + + pairwise_potentials : nd-array + Pairwise potentials of energy function. + + edges : nd-array + Edges of energy function. + + max_iter : int (default=10) + Maximum number of iterations. Ignored if graph is a tree. + + damping : float (default=.5) + Daming of messages in loopy message passing. + Ignored if graph is a tree. + + tol : float (default=1e-5) + Stopping tollerance for loopy message passing. + """ +> from ._viterbi import viterbi +E ImportError: No module named _viterbi + +../inference/maxprod.py:50: ImportError +_________________________ test_blocks_multinomial_crf __________________________ + + def test_blocks_multinomial_crf(): + X, Y = generate_blocks_multinomial(n_samples=1, size_x=9, seed=0) + x, y = X[0], Y[0] + w = np.array([1., 0., 0., # unaryA + 0., 1., 0., + 0., 0., 1., + .4, # pairwise + -.3, .3, + -.5, -.1, .3]) +> for inference_method in get_installed(): + +test_models/test_grid_crf.py:123: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +../inference/inference_methods.py:17: in get_installed + inference_dispatch(unary, pw, edges, inference_method=method) +../inference/inference_methods.py:100: in inference_dispatch + return_energy=return_energy, **kwargs) +../inference/inference_methods.py:474: in inference_ad3plus + n_iterations=4000, exact=branch_and_bound) +../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:44: in general_constrained_graph + return general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose, n_iterations, eta, exact) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +unaries = array([[ 0.]]), edges = array([], shape=(0, 2), dtype=int64) +edge_weights = array([[ 0.]]), constraints = None, verbose = 0 +n_iterations = 4000, eta = 0.1, exact = False + + def general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose=1, n_iterations=1000, eta=0.1, exact=False): + """ + inference on a graph, with one type of node, taking into account logical constraints between unaries. + + The constraints must be a list of tuples like ( , , , ) + The tuple is defined differently for single- and multi-type inference. See in each function below. + + where: + - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - unaries is a list of the index of the unaries involved in this constraint + - states is a list of unary states, 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. + - negated is a list of boolean indicated if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list + + The graph is binarized as explained in Martins et al. ICML 2011 paper: "An Augmented Lagrangian Approach to Constrained MAP Inference". + + NOTE: I had to re-compile AD3 since v2.0.1 from Anaconda missed the create_binary_variable method + + JL Meunier - October 2016 + """ + if unaries.shape[1] != edge_weights.shape[1]: + raise ValueError("incompatible shapes of unaries" + " and edge_weights.") +> if edge_weights.shape[1] != edge_weights.shape[2]: +E IndexError: tuple index out of range + +../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:70: IndexError +___________________________ test_binary_grid_unaries ___________________________ + + def test_binary_grid_unaries(): + # test handling on unaries for binary grid CRFs + for ds in binary: + X, Y = ds(n_samples=1) + x, y = X[0], Y[0] +> for inference_method in get_installed(): + +test_models/test_grid_crf.py:135: +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ +../inference/inference_methods.py:17: in get_installed + inference_dispatch(unary, pw, edges, inference_method=method) +../inference/inference_methods.py:100: in inference_dispatch + return_energy=return_energy, **kwargs) +../inference/inference_methods.py:474: in inference_ad3plus + n_iterations=4000, exact=branch_and_bound) +../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:44: in general_constrained_graph + return general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose, n_iterations, eta, exact) +_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ + +unaries = array([[ 0.]]), edges = array([], shape=(0, 2), dtype=int64) +edge_weights = array([[ 0.]]), constraints = None, verbose = 0 +n_iterations = 4000, eta = 0.1, exact = False + + def general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose=1, n_iterations=1000, eta=0.1, exact=False): + """ + inference on a graph, with one type of node, taking into account logical constraints between unaries. + + The constraints must be a list of tuples like ( , , , ) + The tuple is defined differently for single- and multi-type inference. See in each function below. + + where: + - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - unaries is a list of the index of the unaries involved in this constraint + - states is a list of unary states, 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. + - negated is a list of boolean indicated if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list + + The graph is binarized as explained in Martins et al. ICML 2011 paper: "An Augmented Lagrangian Approach to Constrained MAP Inference". + + NOTE: I had to re-compile AD3 since v2.0.1 from Anaconda missed the create_binary_variable method + + JL Meunier - October 2016 + """ + if unaries.shape[1] != edge_weights.shape[1]: + raise ValueError("incompatible shapes of unaries" + " and edge_weights.") +> if edge_weights.shape[1] != edge_weights.shape[2]: +E IndexError: tuple index out of range + +../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:70: IndexError +=================== 10 failed, 140 passed in 321.52 seconds ==================== From 87f64cda5c90eb63a833816b02e4afbb6ecaf918 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 15 Feb 2017 09:22:18 +0100 Subject: [PATCH 068/155] 0.3.3 --- CHANGELOG | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 22c599d0..f018d0eb 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,14 @@ +0.3.3 +=== +- ad3 now supports the NodeTypeEdgeFeatureGraphCRF model +- ad3+ required only for hard logic constraints +- smaller memory footprint than 0.3 + +0.3 +=== +- Added new model NodeTypeEdgeFeatureGraphCRF +- Added inference method ad3+ for new model and for supporting hard logic constraints in other CRF models + 0.3 === - Removed libdai bindings that were very experimental. @@ -16,7 +27,3 @@ - Renamed psi to joint_feature, as the joint feature function is sometimes also called phi, with psi referring to the energy. - Removed the GLPK dependency: now cvxopt is used to solve linear programs. -0.3 -=== -- Added new model NodeTypeEdgeFeatureGraphCRF -- Added inference method ad3+ for new model and for supporting hard logic constraints in other CRF models \ No newline at end of file From c815cb5df2a7d46f4e69a4b3e958bc5470bcc807 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 15 Feb 2017 10:17:26 +0100 Subject: [PATCH 069/155] bug fix: ad3+ is needed in presence of constraints --- examples/plot_hidden_short_snakes_typed.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/plot_hidden_short_snakes_typed.py b/examples/plot_hidden_short_snakes_typed.py index f231c651..e0d5ce8c 100644 --- a/examples/plot_hidden_short_snakes_typed.py +++ b/examples/plot_hidden_short_snakes_typed.py @@ -82,8 +82,8 @@ bMAKE_PICT_EASY = False #DEBUG: we had a feature on the picture that tells directly if a snake is present or not -#INFERENCE="qpbo" -INFERENCE="ad3+" +#INFERENCE="ad3+" +INFERENCE="ad3" N_JOBS=8 MAXITER=750 From 3741d477fc67ae69f1d39cc6b0aaeb5d35c72326 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 15 Feb 2017 10:24:19 +0100 Subject: [PATCH 070/155] need ad3+ to infer with constraints --- examples/plot_hidden_short_snakes_typed.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/examples/plot_hidden_short_snakes_typed.py b/examples/plot_hidden_short_snakes_typed.py index e0d5ce8c..27bf7416 100644 --- a/examples/plot_hidden_short_snakes_typed.py +++ b/examples/plot_hidden_short_snakes_typed.py @@ -82,8 +82,8 @@ bMAKE_PICT_EASY = False #DEBUG: we had a feature on the picture that tells directly if a snake is present or not -#INFERENCE="ad3+" -INFERENCE="ad3" +#INFERENCE="ad3+" #ad3+ is required when there are hard logic constraints +INFERENCE="ad3" #ad3 is faster than ad3+ and both should yield same results N_JOBS=8 MAXITER=750 @@ -512,13 +512,14 @@ def REPORT(l_Y_GT, lY_Pred, t=None): if nbSWAP_Pixel_Pict_TYPES %2 == 1: XX_test, YY_test, l_constraints = swap_node_types([1,0], [NCELL+1, 2], XX_test, YY_test, l_constraints) - print "\t- results without constraints" + print "\t- results without constraints (using %s)"%INFERENCE t0 = time.time() YY_pred = ssvm.predict( XX_test ) REPORT(YY_test, YY_pred, time.time() - t0) print "_"*50 - print "\t- results exploiting constraints" + print "\t- results exploiting constraints (using ad3+)" + ssvm.model.inference_method = "ad3+" t0 = time.time() YY_pred = ssvm.predict( XX_test, l_constraints ) REPORT(YY_test, YY_pred, time.time() - t0) @@ -530,7 +531,8 @@ def REPORT(l_Y_GT, lY_Pred, t=None): ssvm.model.inference_method = "ad3+" else: ssvm.model.inference_method = "ad3" - print "INFERENCE WITH ", ssvm.model.inference_method + print "\t- results without constraints (using %s)"%ssvm.model.inference_method + t0 = time.time() YY_pred = ssvm.predict( XX_test ) REPORT(YY_test, YY_pred, time.time() - t0) From f92ec0aa7f0dde07818b6f84ced7827e5d68adad Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 15 Feb 2017 16:25:32 +0100 Subject: [PATCH 071/155] First stab at a high-level but complete documentation of the extension. --- README.md | 144 +++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 126 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index c7216a73..da46bf8f 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ + [![Build Status](https://travis-ci.org/pystruct/pystruct.png)](https://travis-ci.org/pystruct/pystruct) [![pypi version](http://img.shields.io/pypi/v/pystruct.svg?style=flat)](https://pypi.python.org/pypi/pystruct/) [![licence](http://img.shields.io/badge/licence-BSD-blue.svg?style=flat)](https://github.com/pystruct/pystruct/blob/master/LICENSE) @@ -5,29 +6,136 @@ -PyStruct -======== +# PyStruct+ +This is a fork from Andreas Mueller's [pystruct](https://github.com/pystruct/pystruct) project, which is an easy-to-use structured learning + and prediction library. In particular, pystruct provides a well-documented tool for researchers as well as non-experts to make use of structured + prediction algorithms. And the design tries to stay as close as possible to the interface and conventions of [scikit-learn](http://scikit-learn.org). + +The goal of the [pystruct+](https://github.com/jlmeunier/pystruct) project and of its companion project [AD3+](https://github.com/jlmeunier/AD3) is to extend pystruct along two directions: + * **supporting hard-logic constraints when predicting** + * **supporting nodes of different nature in CRF graphs** + +The extension of those 2 projects is 100% ascendant compatible with pystruct. Anything that you did with pystruct works the same way with pystruct+. +So you can refer to the pystruct documentation for the API, examples, etc. ( http://pystruct.github.io ) + +What is different in pystruct+ ? + * the __*predict*__ method accepts now an optional constraint parameter + * a new CRF model is proposed, __*NodeTypeEdgeFeatureGraphCRF*__ + + More details are given in next sections. + + You can contact the author on [github](https://github.com/jlmeunier/pystruct). Comments and contributions are welcome. + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943. + + +## Installation +Currently, the offered extensions rely on the __*OneSlackSSVM*__ learner and on the __*AD3+*__ solver. This means __you need to install cvxopt as well__. + +### For AD3+: + * get the source code from https://github.com/jlmeunier/AD3 + * compile and install: +> python setup.py install + +Note: on Windows10 I had trouble with compiling. One dirty workaround then consists in installing the standard AD3, overwritting the python modules with the AD3+ ones +, and changing the version number in the the lib/site-package python folder to 2.1.2. Told you, dirty trick... + +### For Pystruct+: + * get the source code from https://github.com/jlmeunier/pystruct + * compile and install: +> python setup.py install + +## Tests +To test your install, run the test of the new CRF model: +> python pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py + +(You should see a "OK" displayed at the end of the script execution.) + +## Example +Building on the [Snakes](https://pystruct.github.io/auto_examples/plot_snakes.html#sphx-glr-auto-examples-plot-snakes-py) example, there is now a new example called "HiddenSnakes". (Code in examples/plot_hidden_short_snakes_typed.py ) + +The idea is that some picture do not contain any snake despite 10 pixels have a Snake body colour. Why? Because they do not form a valid 10-long snake, as 1 pixel has a wrong colour destroying the continuity of the snake. + +The original task remains but is more difficult: some non-blue pixels are now labelled 'background'. An additional task consists in labeling the picture as Snake or NoSnake. + +This double task is solved by the use of an additional type of node tha represents the picture itself, with 7 simplistic features. There are additional edges, from each pixel to the picture node. That's all. And it improves a lot from the results of the *EdgeFeatureGraphCRF*-based model. + +In addition, we injected some more domain knowledge to illustrate the use of the hard logic constraints. In this case we enforce at most one pixel of label L per picture, for L in [1, 10]. This gives an extra accuracy bonus. + +## Prediction with Hard-Logic Constraints + +You can now pass a __list of logical constraints__ to the predict method, with a *constraints=* named parameter. + + Each constraint is tuple like *( operator, nodes, labels, negated )* + where: + - *operator* is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - *nodes* is the list of the index of each node involved in this constraint + - *labels* is the list of node label. If the labels are the same for all nodes, you can pass it directly as a scalar value. + - *negated* is a list of boolean indicating if the corresponding argument must be negated. Again, if all values are the same, pass a single boolean value instead of a list. + +The operators whose name ends with 'OUT' impose that the operator applied on the all-but-last arguments yields the truth value of the last one. +>For instance XOROUT(a,b,c) <=> XOR(a,b) = c + +When used jointly with the new *NodeTypeEdgeFeatureGraphCRF* model, the structure of the constraints list slightly differs. See in next section. + + +## CRF Graph with Nodes of Different Nature +Pystruct CRF graphs assumes that the nodes of the graph all have the same nature. In consequence, all nodes share the same weights and the same set of possible labels. Similarly, all edges have the same nature and share the same edge weights. +This was a limitation with regards to our needs (for a Document Understanding task). So we propose a new CRF model called *NodeTypeEdgeFeatureGraphCRF*. + +*NodeTypeEdgeFeatureGraphCRF* supports multiple node of multiple nature, which we call **node types**. Each type has its own weights and own set of possible labels. Similarly, edges have different nature depending on the type of their sources and target-nodes. In a graph with N types, there are N^2 types of edges. + +*NodeTypeEdgeFeatureGraphCRF* generalizes *EdgeFeatureGraphCRF*, so edges have features. NOTE: I think that you can mimics the absence opf feature on edges (as in *GraphCRF* model) by specifying one feature per edge, whose value is 1 for all edges. + +This extension has an impact on + * the structure of the Xs + * the values in Ys + * the structure of the optional constraint list at prediction + +### Xs and Ys +In single type CRF, like *EdgeFeatureGraphCRF*, an instance x is represented as a tuple + + (*node_features*, *edges*, *edge_features*) representing the graph. + +* *node_feature*s is of shape (*n_node*, *n_features*) +* *edges* is an array of shape (*n_edges*, 2) +* *edge_features* is of shape (*n_edges*, *n_edge_features*) + + Labels y are given as array of shape (*n_nodes*,) + +In multiple type graphs, with *_n_types* types, an instance x is represented as a tuple -PyStruct aims at being an easy-to-use structured learning and prediction library. -Currently it implements only max-margin methods and a perceptron, but other algorithms -might follow. + (*l_node_features*, *l_edges*, *l_edge_features*) representing the graph. +* *l_node_feature*s is a list of length *n_types* containing arrays of shape (*n_typ_node*, *n_typ_features*), where *n_typ_node* is the number of nodes of that type, while *n_typ_features* is the number of features for this type of nodes. +* *l_edges* is a list of length *n_types*^2 . The element of index i*j contains an array of shape (*n_typ_edge, 2) defining the edges from nodes of type *i* to nodes of type *j*, with *i* and *j* in [0, *n_types*-1]. +* *l_edge_features* is a list of length *n_types*^2. It contains the features of the edges for each pair of types, in same order as in previous parameter. The element of index i*j contains an array of shape (*n_typ_edges*, *n_typ_edge_features*). if *n_typ_edge_features* is 0, then *n_typ_edges* should be 0 as well for all instances of graph! If you want an edge without features, set *n_typ_edge_features* to 1 and pass 1.0 as feature for all edges (of that type). -The goal of PyStruct is to provide a well-documented tool for researchers as well as non-experts -to make use of structured prediction algorithms. -The design tries to stay as close as possible to the interface and conventions -of [scikit-learn](http://scikit-learn.org). +Each y remains a vector array. While the label could start at 0 for all types, we have chosen not to do so. (Essentially,to make clear that types do not blend into each other, which is clear when you show a confusion matrix). So the labels of the first type start at 0, while labels of next type starts right after the value of the last label of previous type. +*NodeTypeEdgeFeatureGraphCRF* provides 2 convenience methods: +* *flattenY*( [ [2,0,0], [3,3,4] ] ) --> [ 2,0,0, 5,5,7] (assuming type 0 has 3 labels) +* *unflattenY*(Xs, [ 2,0,0, 5,5,7] ) --> [ [2,0,0], [3,3,4] ] (you'll also need to pass the Xs) -You can install pystruct using +### Constraints on Multitype Graphs +As for the Xs and Ys, the constraint must be partitioned by type. -> pip install pystruct + The constraints must be a list of tuples like: + +Either -Some of the functionality (namely OneSlackSSVM and NSlackSSVM) requires that cvxopt is installed. -See the [installation instructions](http://pystruct.github.io/intro.html) for more details. + ( *operator*, *l_nodes*, *l_labels*, *l_negated* ) + with operator being one 'XOR' 'ATMOSTONE' 'OR' -The full documentation and installation instructions can be found at the website: -http://pystruct.github.io +Or -You can contact the authors either via the [mailing list](https://groups.google.com/forum/#!forum/pystruct) -or on [github](https://github.com/pystruct/pystruct). + ( *operator*, *l_nodes*, *l_labels*, *l_negated* , (*type*, *node*, *label*, *negated*)) + with operator being one 'XOROUT' 'OROUT' 'ANDOUT' 'IMPLY' + +- *l_nodes* is a list of nodes per type. Each item is a list of the index of the node of that type involved in this constraint +- *l_labels* is a list of labels per type. Each item is a list of the label of the involved node. If the labels are all the same for a type, you can pass it directly as a scalar value. +- *l_negate*d is a list of "negated" per type. Each item is a list of booleans indicating if the node must be negated. Again, if all values are the same for a type, pass a single boolean value instead of a list -Currently the project is mostly maintained by Andreas Mueller, but contributions are very welcome. +- the last (*type*, *nod*e, *label*, *negated*) allows to refer to the outcome of an 'OUT' operator. + + \ No newline at end of file From fbc64bee859fc120253caaede90015fc5ae4373a Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 15 Feb 2017 16:30:00 +0100 Subject: [PATCH 072/155] main doc ok --- README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index da46bf8f..485b5782 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ The goal of the [pystruct+](https://github.com/jlmeunier/pystruct) project and o The extension of those 2 projects is 100% ascendant compatible with pystruct. Anything that you did with pystruct works the same way with pystruct+. So you can refer to the pystruct documentation for the API, examples, etc. ( http://pystruct.github.io ) -What is different in pystruct+ ? +What is different in pystruct+? * the __*predict*__ method accepts now an optional constraint parameter * a new CRF model is proposed, __*NodeTypeEdgeFeatureGraphCRF*__ @@ -37,6 +37,7 @@ Currently, the offered extensions rely on the __*OneSlackSSVM*__ learner and on ### For AD3+: * get the source code from https://github.com/jlmeunier/AD3 * compile and install: + > python setup.py install Note: on Windows10 I had trouble with compiling. One dirty workaround then consists in installing the standard AD3, overwritting the python modules with the AD3+ ones @@ -45,6 +46,7 @@ Note: on Windows10 I had trouble with compiling. One dirty workaround then consi ### For Pystruct+: * get the source code from https://github.com/jlmeunier/pystruct * compile and install: + > python setup.py install ## Tests @@ -60,9 +62,9 @@ The idea is that some picture do not contain any snake despite 10 pixels have a The original task remains but is more difficult: some non-blue pixels are now labelled 'background'. An additional task consists in labeling the picture as Snake or NoSnake. -This double task is solved by the use of an additional type of node tha represents the picture itself, with 7 simplistic features. There are additional edges, from each pixel to the picture node. That's all. And it improves a lot from the results of the *EdgeFeatureGraphCRF*-based model. +This double task is solved by the use of an additional type of node that represents the picture itself, with 7 simplistic features. There are additional edges, from each pixel to the picture node. That's all. And it improves a lot from the results of the *EdgeFeatureGraphCRF*-based model. -In addition, we injected some more domain knowledge to illustrate the use of the hard logic constraints. In this case we enforce at most one pixel of label L per picture, for L in [1, 10]. This gives an extra accuracy bonus. +In addition, we injected some more domain knowledge to illustrate the use of the hard logic constraints. In this case we enforce *at most one pixel of label L per picture, for L in [1, 10]*. This gives an extra accuracy bonus. ## Prediction with Hard-Logic Constraints From f92f4557674aca9bd6fbea4f98d970c7d825a74d Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 16 Feb 2017 10:11:27 +0100 Subject: [PATCH 073/155] unflattenY was wrong... :-/ --- pystruct/models/typed_crf.py | 9 ++-- .../test_node_type_edge_feature_graph_crf.py | 50 ++++++++++++++++--- 2 files changed, 50 insertions(+), 9 deletions(-) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index 494dc092..1eb29133 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -112,18 +112,21 @@ def flattenY(self, lY_by_typ): lY.append( np.asarray(Y_typ) + n_start_state ) return np.hstack(lY) - def unflattenY(self, lX, flatY): + def unflattenY(self, X, flatY): """ predict returns a flat array of Y (same structure as for 'fit') This method structures the Y as a list of Y_per_type, where the first label of any type is 0 """ lY = list() i_start_node = 0 - for n_start_state, X in zip(self._l_type_startindex, lX): - n_nodes = X.shape[0] + (l_node_features, l_edges, l_edge_features) = X + for n_start_state, nf in zip(self._l_type_startindex, l_node_features): + n_nodes = nf.shape[0] Y = flatY[i_start_node : i_start_node+n_nodes] - n_start_state lY.append(Y) i_start_node += n_nodes + if flatY.shape != (i_start_node,): + raise ValueError("The total number of label does not match the total number of nodes: %d != %d"%(flatY.shape[0], i_start_node)) return lY def initialize(self, X, Y=None): diff --git a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py index 6ed8e9d8..d7bee7e0 100644 --- a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py +++ b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py @@ -149,7 +149,38 @@ def get_simple_graph2(): [4,4,4] ]) ] return (node_f, edges, edge_f) + +def test_flatten_unflattenY(): + + g, (node_f, edges, edge_f) = get_simple_graph_structure(), get_simple_graph() + y = np.array([1,2]) + l_nf = [ np.zeros((2,3)) ] #list of node feature , per type + X = (l_nf, None, None) #we give no edge + y_ref = [ np.array([1,2]) ] + assert all( [ (y_typ1 == y_typ2).all() for y_typ1, y_typ2 in zip(g.unflattenY(X, y), y_ref) ]) + + assert (y == g.flattenY(g.unflattenY(X, y))).all() + + #============================================ + g, x, y = more_complex_graph() + + Y = [ np.array([0, 0]) + , np.array([0, 0, 0]) #we start again at zero on 2nd type + ] + y = np.hstack([ np.array([0, 0]) + , 2+np.array([0, 0, 0]) + ]) + l_nf = [ np.zeros( (2,3) ), np.zeros( (3, 4) )] #2 node with 3 features, 3 node with 4 features + X = (l_nf, None, None) #we give no edge + assert (g.flattenY(Y) == y).all() + print g.unflattenY(X, y) + assert all( [ (y_typ1 == y_typ2).all() for y_typ1, y_typ2 in zip(g.unflattenY(X, y), Y) ]) + + l_nf = [ np.zeros( (1,3) ), np.zeros( (3, 4) )] #2 node with 3 features, 3 node with 4 features + X = (l_nf, None, None) #we give no edge + assert_raises(ValueError, g.unflattenY, X, y) + def test_joint_feature(): print "---SIMPLE---------------------------------------------------------------------" @@ -238,10 +269,7 @@ def test_joint_feature(): 0., 0., 0., 0., 0., 0., 0., 0.]) ) -def test_joint_feature2(): - - # ------------------------------------------------------------------------------------------- - print "---MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" +def more_complex_graph(): g = NodeTypeEdgeFeatureGraphCRF( 2 #how many node type? , [2, 3] #how many labels per node type? @@ -269,11 +297,19 @@ def test_joint_feature2(): ] x = (node_f, edges, edge_f) - print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([ np.array([0, 0]) , 2+np.array([0, 0, 0]) ]) + return g, x, y + +def test_joint_feature2(): + + # ------------------------------------------------------------------------------------------- + print "---MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" + g, x, y = more_complex_graph() print y + + g.initialize(x, y) jf = g.joint_feature(x,y) print "joint_feature = \n", `jf` @@ -814,7 +850,9 @@ def test_energy_discrete(): if 0: debug_joint_feature() - + if 1: + test_flatten_unflattenY() + if 1: test_joint_feature() if 1: From a38f1a7577cc1db0c7d1e2e5cb167d74bef1946f Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 16 Feb 2017 17:22:54 +0100 Subject: [PATCH 074/155] Update README.md OneSlackSSVM is not the only usable learner --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 485b5782..18d9fef1 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ What is different in pystruct+? ## Installation -Currently, the offered extensions rely on the __*OneSlackSSVM*__ learner and on the __*AD3+*__ solver. This means __you need to install cvxopt as well__. +Currently, the offered extensions rely on the __*AD3+*__ solver. For learning I mostly used the __*OneSlackSSVM*__ learner, which requires to install cvxopt as well. ### For AD3+: * get the source code from https://github.com/jlmeunier/AD3 @@ -140,4 +140,4 @@ Or - the last (*type*, *nod*e, *label*, *negated*) allows to refer to the outcome of an 'OUT' operator. - \ No newline at end of file + From 2a913151c873b2208e384afd3e145a68c5a8f5b7 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 17 Feb 2017 10:20:28 +0100 Subject: [PATCH 075/155] added the method to create the ATMOSTONE constraints instead of the ANDOUT+XOROUT --- examples/plot_hidden_short_snakes_typed.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/examples/plot_hidden_short_snakes_typed.py b/examples/plot_hidden_short_snakes_typed.py index 27bf7416..43e04804 100644 --- a/examples/plot_hidden_short_snakes_typed.py +++ b/examples/plot_hidden_short_snakes_typed.py @@ -294,6 +294,26 @@ def listConstraints(lX): lConstraints.append( lConstraint_for_X ) return lConstraints +def listConstraints_ATMOSTONE(lX): + """ + produce the list of constraints for this list of multi-type graphs + """ + lConstraints = list() + for _lNF, _lE, _lEF in lX: + nf_pixel, nf_pict = _lNF + nb_pixels = len(nf_pixel) + + lConstraint_for_X = list() + + for _state in range(1, NCELL+1): + lConstraint_for_X.append( ("ATMOSTONE" , [ range(nb_pixels), []] + , [ _state, None ] #atmost one cell in state _state whatever picture label + , [ False, None ]) + ) #we have a list of constraints per X + + lConstraints.append( lConstraint_for_X ) + return lConstraints + def makeItEasy(lX_pict_feat, lY_pict): """ From cd0a3b022638700c0bab5f7acfe833bf83abc714 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 17 Feb 2017 11:00:27 +0100 Subject: [PATCH 076/155] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 18d9fef1..a3e67995 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,7 @@ In multiple type graphs, with *_n_types* types, an instance x is represented as (*l_node_features*, *l_edges*, *l_edge_features*) representing the graph. * *l_node_feature*s is a list of length *n_types* containing arrays of shape (*n_typ_node*, *n_typ_features*), where *n_typ_node* is the number of nodes of that type, while *n_typ_features* is the number of features for this type of nodes. * *l_edges* is a list of length *n_types*^2 . The element of index i*j contains an array of shape (*n_typ_edge, 2) defining the edges from nodes of type *i* to nodes of type *j*, with *i* and *j* in [0, *n_types*-1]. -* *l_edge_features* is a list of length *n_types*^2. It contains the features of the edges for each pair of types, in same order as in previous parameter. The element of index i*j contains an array of shape (*n_typ_edges*, *n_typ_edge_features*). if *n_typ_edge_features* is 0, then *n_typ_edges* should be 0 as well for all instances of graph! If you want an edge without features, set *n_typ_edge_features* to 1 and pass 1.0 as feature for all edges (of that type). +* *l_edge_features* is a list of length *n_types*^2. It contains the features of the edges for each pair of types, in same order as in previous parameter (cartesian product) Each item is an array of shape (*n_typ_edges*, *n_typ_edge_features*). if *n_typ_edge_features* is 0, then *n_typ_edges* should be 0 as well for all instances of graph! If you want an edge without features, set *n_typ_edge_features* to 1 and pass 1.0 as feature for all edges (of that type). Each y remains a vector array. While the label could start at 0 for all types, we have chosen not to do so. (Essentially,to make clear that types do not blend into each other, which is clear when you show a confusion matrix). So the labels of the first type start at 0, while labels of next type starts right after the value of the last label of previous type. *NodeTypeEdgeFeatureGraphCRF* provides 2 convenience methods: From 94722d4784720a7b1c8cf608e11147656ce5b86e Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 17 Feb 2017 12:29:32 +0100 Subject: [PATCH 077/155] default inference method is ad3 --- pystruct/models/node_type_edge_feature_graph_crf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index d23d106e..df35f386 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -91,7 +91,7 @@ def __init__(self , l_n_states #how many labels per node type? , l_n_features #how many features per node type? , a_n_edge_features #how many features per edge type? - , inference_method="ad3+" + , inference_method="ad3" , l_class_weight=None): #class_weight per node type or None or None #internal stuff From d17ef855168673fd127f64211ae8960ed394c7cd Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 17 Feb 2017 12:30:06 +0100 Subject: [PATCH 078/155] Explain the new class constructor Fixed few text details --- README.md | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index a3e67995..13c65b0c 100644 --- a/README.md +++ b/README.md @@ -91,13 +91,27 @@ This was a limitation with regards to our needs (for a Document Understanding ta *NodeTypeEdgeFeatureGraphCRF* generalizes *EdgeFeatureGraphCRF*, so edges have features. NOTE: I think that you can mimics the absence opf feature on edges (as in *GraphCRF* model) by specifying one feature per edge, whose value is 1 for all edges. -This extension has an impact on +**This extension has an impact on:** + * the constructor + * the structure of the label weights, if not uniform * the structure of the Xs * the values in Ys * the structure of the optional constraint list at prediction +### Class Constructor +You need now to define the number of node types and the number of features per type (of node, and of edge) when instantiating *NodeTypeEdgeFeatureGraphCRF*. + + def __init__(self + , n_types #how many node type? + , l_n_states #how many labels per node type? + , l_n_features #how many features per node type? + , a_n_edge_features #how many features per edge type? (array-like) shape=(n_type, n_type, n_feature_per_type_pair) + , inference_method="ad3" + , l_class_weight=None): #class_weight per node type or None or None + + ### Xs and Ys -In single type CRF, like *EdgeFeatureGraphCRF*, an instance x is represented as a tuple +In single type CRF, like *EdgeFeatureGraphCRF*, an instance *X* is represented as a tuple (*node_features*, *edges*, *edge_features*) representing the graph. @@ -107,14 +121,14 @@ In single type CRF, like *EdgeFeatureGraphCRF*, an instance x is represented as Labels y are given as array of shape (*n_nodes*,) -In multiple type graphs, with *_n_types* types, an instance x is represented as a tuple +In multiple type graphs, with *_n_types* types, an instance *X* is represented as a tuple (*l_node_features*, *l_edges*, *l_edge_features*) representing the graph. * *l_node_feature*s is a list of length *n_types* containing arrays of shape (*n_typ_node*, *n_typ_features*), where *n_typ_node* is the number of nodes of that type, while *n_typ_features* is the number of features for this type of nodes. -* *l_edges* is a list of length *n_types*^2 . The element of index i*j contains an array of shape (*n_typ_edge, 2) defining the edges from nodes of type *i* to nodes of type *j*, with *i* and *j* in [0, *n_types*-1]. -* *l_edge_features* is a list of length *n_types*^2. It contains the features of the edges for each pair of types, in same order as in previous parameter (cartesian product) Each item is an array of shape (*n_typ_edges*, *n_typ_edge_features*). if *n_typ_edge_features* is 0, then *n_typ_edges* should be 0 as well for all instances of graph! If you want an edge without features, set *n_typ_edge_features* to 1 and pass 1.0 as feature for all edges (of that type). +* *l_edges* is a list of length *n_types*^2 . Each of its elements contains an array of shape (*n_typ_edge, 2) defining the edges from nodes of type *i* to nodes of type *j*, with *i* and *j* in [0, *n_types*-1], *j* being the secondary index (inner loop). +* *l_edge_features* is a list of length *n_types*^2. It contains the features of the edges for each pair of types, in same order as in previous parameter. Each item is an array of shape (*n_typ_edges*, *n_typ_edge_features*). if *n_typ_edge_features* is 0, then *n_typ_edges* should be 0 as well for all instances of graph! If you want an edge without features, set *n_typ_edge_features* to 1 and pass 1.0 as feature for all edges (of that type). -Each y remains a vector array. While the label could start at 0 for all types, we have chosen not to do so. (Essentially,to make clear that types do not blend into each other, which is clear when you show a confusion matrix). So the labels of the first type start at 0, while labels of next type starts right after the value of the last label of previous type. +Each *Y* remains a vector array. While the label could start at 0 for all types, we have chosen not to do so. (Essentially,to make clear that types do not blend into each other, which is clear when you show a confusion matrix). So the labels of the first type start at 0, while labels of next type starts right after the value of the last label of previous type. *NodeTypeEdgeFeatureGraphCRF* provides 2 convenience methods: * *flattenY*( [ [2,0,0], [3,3,4] ] ) --> [ 2,0,0, 5,5,7] (assuming type 0 has 3 labels) * *unflattenY*(Xs, [ 2,0,0, 5,5,7] ) --> [ [2,0,0], [3,3,4] ] (you'll also need to pass the Xs) From 6918cc6a34c08cd494ca02eae6e158d38ffe707e Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 20 Feb 2017 12:51:26 +0100 Subject: [PATCH 079/155] ad3+ can deal with singletype CRF with constraints --- pystruct/inference/inference_methods.py | 26 ++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/pystruct/inference/inference_methods.py b/pystruct/inference/inference_methods.py index d2172cc3..ae6c7331 100644 --- a/pystruct/inference/inference_methods.py +++ b/pystruct/inference/inference_methods.py @@ -14,7 +14,10 @@ def get_installed(method_filter=None): edges = np.empty((0, 2), dtype=np.int) for method in method_filter: try: - inference_dispatch(unary, pw, edges, inference_method=method) + if method != 'ad3+': + inference_dispatch(unary, pw, edges, inference_method=method) + else: + inference_dispatch(unary, np.zeros((0,1,1)), np.zeros((0,2), dtype=np.int), inference_method=method) installed.append(method) except ImportError: pass @@ -470,6 +473,8 @@ def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges, relaxe # n_states, pairwise_potentials = \ # _validate_params(unary_potentials, pairwise_potentials, edges) # unaries = unary_potentials.reshape(-1, n_states) + bMultiType = isinstance(l_unary_potentials, list) + res = ad3.general_constrained_graph(l_unary_potentials, l_edges, l_pairwise_potentials, constraints, verbose=verbose, n_iterations=4000, exact=branch_and_bound) @@ -482,14 +487,17 @@ def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges, relaxe else: if inference_exception and solver_status in ["fractional", "unsolved"]: raise InferenceException(solver_status) - #we now get a list of unary marginals - ly = list() - _cum_n_states = 0 - for unary_marg in l_unary_marginals: - ly.append( _cum_n_states + np.argmax(unary_marg, axis=-1) ) - _cum_n_states += unary_marg.shape[1] #number of states for that type - y = np.hstack(ly) - # when we will simplify y: y = [_cum_n_statesnp.argmax(unary_marg, axis=-1) for unary_marg in l_unary_marginals] + if bMultiType: + #we now get a list of unary marginals + ly = list() + _cum_n_states = 0 + for unary_marg in l_unary_marginals: + ly.append( _cum_n_states + np.argmax(unary_marg, axis=-1) ) + _cum_n_states += unary_marg.shape[1] #number of states for that type + y = np.hstack(ly) + # when we will simplify y: y = [_cum_n_statesnp.argmax(unary_marg, axis=-1) for unary_marg in l_unary_marginals] + else: + y = np.argmax(l_unary_marginals, axis=-1) if return_energy: return y, -energy From 595f25ee16a19824ee01bd2e794d4a0fbf271422 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 20 Feb 2017 12:51:48 +0100 Subject: [PATCH 080/155] testing ad3+ --- pystruct/tests/test_libraries.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/pystruct/tests/test_libraries.py b/pystruct/tests/test_libraries.py index 6d89afc5..1591c4c8 100644 --- a/pystruct/tests/test_libraries.py +++ b/pystruct/tests/test_libraries.py @@ -4,10 +4,17 @@ def test_pyqpbo(): import pyqpbo pyqpbo - assert 'qpbo' in get_installed() + assert 'qpbo' in get_installed(['qpbo']) def test_ad3(): import ad3 ad3 - assert 'ad3' in get_installed() + assert 'ad3' in get_installed(['ad3']) + +def test_ad3plus(): + import ad3 + ad3 + assert 'ad3+' in get_installed(['ad3+']) + + From c4b7c75bf9fb2e75714ab87cb1684292006dbf7c Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 20 Feb 2017 13:29:25 +0100 Subject: [PATCH 081/155] - MIT lmicense - minor change on _get_node_features - ad by default --- pystruct/models/typed_crf.py | 47 ++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index 1eb29133..a94fc23d 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -7,22 +7,26 @@ Copyright Xerox(C) 2017 JL. Meunier - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. Developed for the EU project READ. The READ project has received funding - from the European Union�s Horizon 2020 research and innovation programme + from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. """ @@ -41,7 +45,7 @@ def __init__(self , n_types #how many node type? , l_n_states #how many labels per node type? , l_n_features #how many features per node type? - , inference_method="ad3+" + , inference_method="ad3" , l_class_weight=None): #class_weight per node type or None or None if inference_method is None: @@ -198,7 +202,7 @@ def _check_size_xy(self, X, Y): if Y is None: return #make sure Y has the proper length and acceptable labels - l_node_features = self._get_node_features(X, True) + l_node_features = self._get_node_features(X) nb_nodes = sum(nf.shape[0] for nf in l_node_features) if Y.shape[0] != nb_nodes: @@ -216,13 +220,10 @@ def _check_size_xy(self, X, Y): return True - def _get_node_features(self, x, bClean=False): - if bClean: - #we replace None by empty array with proper shape - return [ np.empty((0,_n_feat)) if node_features is None else node_features - for (node_features, _n_feat) in zip(x[0], self.l_n_features)] - else: - return x[0] + def _get_node_features(self, x): + #we replace None by empty array with proper shape + return [ np.empty((0,_n_feat)) if node_features is None else node_features + for (node_features, _n_feat) in zip(x[0], self.l_n_features)] def _get_edges(self, x): return [ np.empty((0,2)) if edges is None or len(edges)==0 else edges for edges in x[1]] @@ -254,7 +255,7 @@ def _get_unary_potentials(self, x, w): Unary weights. """ self._check_size_w(w) - l_node_features = self._get_node_features(x, True) + l_node_features = self._get_node_features(x) l_unary_potentials = [] From 57ec6b75ee995e6f19e0db60ad1ee3fdfd1a2ee1 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 20 Feb 2017 13:29:41 +0100 Subject: [PATCH 082/155] MIT license --- .../node_type_edge_feature_graph_crf.py | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index df35f386..09380900 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -5,19 +5,23 @@ Copyright Xerox(C) 2017 JL. Meunier - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. Developed for the EU project READ. The READ project has received funding from the European Union's Horizon 2020 research and innovation programme @@ -255,7 +259,7 @@ def joint_feature(self, x, y): """ self._check_size_x(x) #call initialize once! - l_node_features = self._get_node_features(x, True) + l_node_features = self._get_node_features(x) l_edges, l_edge_features = self._get_edges(x), self._get_edge_features(x) l_n_nodes = [len(nf) for nf in self._get_node_features(x)] l_n_edges = [len(ef) for ef in self._get_edges (x)] From ad35a8f47ea13a3c5741ca8e57bb8c8425707502 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 20 Feb 2017 13:30:21 +0100 Subject: [PATCH 083/155] ad3+ does not pass. I exclude it for now --- pystruct/tests/test_models/test_grid_crf.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pystruct/tests/test_models/test_grid_crf.py b/pystruct/tests/test_models/test_grid_crf.py index 1bc178d0..6705554d 100644 --- a/pystruct/tests/test_models/test_grid_crf.py +++ b/pystruct/tests/test_models/test_grid_crf.py @@ -122,6 +122,7 @@ def test_blocks_multinomial_crf(): -.5, -.1, .3]) for inference_method in get_installed(): #NOTE: ad3+ fails because it requires a different data structure + if inference_method == 'ad3+': continue crf = GridCRF(inference_method=inference_method) crf.initialize(X, Y) y_hat = crf.inference(x, w) @@ -134,6 +135,8 @@ def test_binary_grid_unaries(): X, Y = ds(n_samples=1) x, y = X[0], Y[0] for inference_method in get_installed(): + #NOTE: ad3+ fails because it requires a different data structure + if inference_method == 'ad3+': continue crf = GridCRF(inference_method=inference_method) crf.initialize(X, Y) w_unaries_only = np.zeros(7) From 9e72ed2f93055c69a44de0bed1f23fd169ba3fa5 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 20 Feb 2017 13:57:46 +0100 Subject: [PATCH 084/155] 0.3.4 --- CHANGELOG | 6 ++++++ pystruct/__init__.py | 2 +- setup.py | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index f018d0eb..c02066ba 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,9 @@ +0.3.4 +=== +- MIT license +- all tests are passing except test_latent_node_crf_learning.py (as in 0.2.4) + + 0.3.3 === - ad3 now supports the NodeTypeEdgeFeatureGraphCRF model diff --git a/pystruct/__init__.py b/pystruct/__init__.py index e19434e2..334b8995 100644 --- a/pystruct/__init__.py +++ b/pystruct/__init__.py @@ -1 +1 @@ -__version__ = "0.3.3" +__version__ = "0.3.4" diff --git a/setup.py b/setup.py index c3ebaaf7..0a9c74f3 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ include_dirs = [np.get_include()] setup(name="pystruct", - version="0.3.3", + version="0.3.4", install_requires=["ad3>=2.1.2"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', From 3dfab3217b373c12cd134f40cabf93d28062c4a5 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 13 Apr 2017 10:28:08 +0200 Subject: [PATCH 085/155] -random.seed called once (just to be sure) - various minot code improvements --- .../plot_hidden_short_snakes_typed_gen.py | 363 ++++++++++++++++++ examples/plot_hidden_snakes.py | 7 +- 2 files changed, 366 insertions(+), 4 deletions(-) create mode 100644 examples/plot_hidden_short_snakes_typed_gen.py diff --git a/examples/plot_hidden_short_snakes_typed_gen.py b/examples/plot_hidden_short_snakes_typed_gen.py new file mode 100644 index 00000000..11c34e4e --- /dev/null +++ b/examples/plot_hidden_short_snakes_typed_gen.py @@ -0,0 +1,363 @@ +""" +============================================== +Conditional Interactions on the Snakes Dataset +============================================== + +This is a variant of plot_snakes.py + +Snake are hidding, so we have 2 tasks: +- determining if a snake is in the picture, +- identifying its head to tail body. + +We use the NodeTypeEdgeFeatureGraphCRF class with 2 type of nodes. + +HERE WE GENERATE THE SNAKES AT RANDOM INSTEAD OF USING THE SNAKE DATASET + + +This example uses the snake dataset introduced in +Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 + +This dataset is specifically designed to require the pairwise interaction terms +to be conditioned on the input, in other words to use non-trival edge-features. + +The task is as following: a "snake" of length ten wandered over a grid. For +each cell, it had the option to go up, down, left or right (unless it came from +there). The input consists of these decisions, while the desired output is an +annotation of the snake from 0 (head) to 9 (tail). See the plots for an +example. + +As input features we use a 3x3 window around each pixel (and pad with background +where necessary). We code the five different input colors (for up, down, left, right, +background) using a one-hot encoding. This is a rather naive approach, not using any +information about the dataset (other than that it is a 2d grid). + +The task can not be solved using the simple DirectionalGridCRF - which can only +infer head and tail (which are also possible to infer just from the unary +features). If we add edge-features that contain the features of the nodes that are +connected by the edge, the CRF can solve the task. + +From an inference point of view, this task is very hard. QPBO move-making is +not able to solve it alone, so we use the relaxed AD3 inference for learning. + +PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). +But it does work as well as Decision Tree Fields ;) + + + + JL Meunier - January 2017 + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943 + + Copyright Xerox + +""" + +import sys, os, time +import random, cPickle + +import numpy as np + +from sklearn.metrics import confusion_matrix, accuracy_score +from sklearn.linear_model import LogisticRegression +from sklearn.grid_search import GridSearchCV + +from pystruct.learners import OneSlackSSVM +from pystruct.datasets import load_snakes +from pystruct.models import NodeTypeEdgeFeatureGraphCRF + +from plot_snakes import one_hot_colors + +from plot_hidden_snakes import augmentWithNoSnakeImages, shuffle_in_unison, shorten_snakes + +from plot_hidden_short_snakes_typed import plot_snake, prepare_data, prepare_picture_data, convertToTwoType,listConstraints, listConstraints_ATMOSTONE, REPORT + +#============================================================================================== + +bFIXED_RANDOM_SEED = True + +NCELL=10 + +#INFERENCE="ad3+" #ad3+ is required when there are hard logic constraints +INFERENCE="ad3" #ad3 is faster than ad3+ +N_JOBS=8 + +#MAXITER=750 + +lNbSAMPLE=[200, 400, 600, 800] #how many sample do we generate for each experiment? + +nbEXPERIMENT = 10 + +#============================================================================================== + +def printConfig(): + print "== NCELL=", NCELL + print "== FIXED_SEED=", bFIXED_RANDOM_SEED + print "== INFERENCE =", INFERENCE + print "== N_JOBS =", N_JOBS + #print "== MAX_ITER=", MAXITER + print "== lNbSAMPLE=", lNbSAMPLE + print "== nbEXPERIMENT=", nbEXPERIMENT + +if __name__ == '__main__': printConfig() + + +if bFIXED_RANDOM_SEED: + np.random.seed(1605) + random.seed(98) +else: + np.random.seed() + random.seed() + +class GenSnakeException(Exception): pass + +def genSnakes(N, ncell=NCELL): + """ + Generate snakes at random. + Return N tuple (snakes, Y) + """ + ltSnakeY = [] + + ndim = 1+ ncell+1+ncell +1 #where we'll draw each snake. Border, possible straight snake, centre, possible straight snake, border + aBoard = np.zeros( (ndim, ndim) , dtype=np.int8) + im,jm = 1+ ncell, 1+ ncell #middle of board + lDirection = range(4) #assume it is N, E, S, W + lDirectionIncr = [(-1,0), (0,1), (1,0), (0,-1)] + lDirectionColor = [ [255,0,0], [255,255,0], [0,255,0], [0,255,255] ] + for _n in range(N): + while True: + aBoard[:,:] = -1 #all background + i,j = im,jm + lij = list() + ldir=list() + aSnake, Y = None, None + + try: + for _ncell in range(ncell): + random.shuffle(lDirection) #we will try each direction in turn + for dir in lDirection: + _i, _j = i+lDirectionIncr[dir][0], j+lDirectionIncr[dir][1] + if aBoard[_i,_j] == -1: break #ok, valid direction, we jump on a background pixel + if aBoard[_i,_j] != -1: raise GenSnakeException("Failed to generate a snake") #got stuck + aBoard[i,j] = dir + lij.append( (i,j) ) + ldir.append(dir) + i,j = _i,_j + #ok we have a Snake, let's create the image with background borders + imin,jmin = map(min, zip(*lij)) + imax,jmax = map(max, zip(*lij)) + aSnake = np.zeros((imax-imin+3, jmax-jmin+3, 3), dtype=np.uint8) + aSnake[:,:,2] = 255 #0,0,255 + aY = np.zeros((imax-imin+3, jmax-jmin+3) , dtype=np.uint8) + for _lbl, ((_i,_j), _dir) in enumerate(zip(lij, ldir)): + aSnake[_i-imin+1, _j-jmin+1,:] = lDirectionColor[_dir] + aY [_i-imin+1, _j-jmin+1] = _lbl + 1 + + break + except GenSnakeException: pass + ltSnakeY.append( (aSnake, aY) ) +# print aSnake +# print aY +# plot_snake(aSnake) + return ltSnakeY + + +if __name__ == '__main__': + + + print("Please be patient...") + snakes = load_snakes() + + #-------------------------------------------------------------------------------------------------- + #we always test against the original test set + X_test, Y_test = snakes['X_test'], snakes['Y_test'] + if NCELL <10: X_test, Y_test = shorten_snakes(X_test, Y_test, NCELL) + + nb_hidden, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", False, nCell=NCELL) + Y_test_pict = np.array([1]*(len(X_test)-nb_hidden) + [0]*nb_hidden) + print "TEST SET ", len(X_test), len(Y_test) + + X_test = [one_hot_colors(x) for x in X_test] + X_test_pict_feat = prepare_picture_data(X_test) + X_test_directions, X_test_edge_features = prepare_data(X_test) + + #-------------------------------------------------------------------------------------------------- + for iExp in range(nbEXPERIMENT): + print "#"*75 + print "# EXPERIMENT %d / %d"%(iExp+1, nbEXPERIMENT) + print "#"*75 + + + lXY = genSnakes(max(lNbSAMPLE)) + X_train_all, Y_train_all = zip(*lXY) + X_train_all, Y_train_all = list(X_train_all), list(Y_train_all) + print "***** GENERATED %d snakes of length %d *****"%(len(X_train_all), NCELL) + + #Also generate an additional test set + NTEST=100 + lXYTest = genSnakes( NTEST ) + X_test_gen, Y_test_gen = zip(*lXYTest) + X_test_gen, Y_test_gen = list(X_test_gen), list(Y_test_gen) + print "***** GENERATED %d snakes of length %d *****"%(NTEST, NCELL) + nb_hidden, X_test_gen, Y_test_gen = augmentWithNoSnakeImages(X_test_gen, Y_test_gen, "test_gen", False, nCell=NCELL) + Y_test_gen_pict = np.array([1]*(len(X_test_gen)-nb_hidden) + [0]*nb_hidden) + print "GENERATED TEST SET ", len(X_test_gen), len(Y_test_gen) + + + X_test_gen = [one_hot_colors(x) for x in X_test_gen] + X_test_gen_pict_feat = prepare_picture_data(X_test_gen) + X_test_gen_directions, X_test_gen_edge_features = prepare_data(X_test_gen) + + for nbSample in lNbSAMPLE: + print "======================================================================================================" + print "TRAINING" + X_train, Y_train = X_train_all[0:nbSample], Y_train_all[0:nbSample] + + nb_hidden, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False, nCell=NCELL) + print "TRAIN SET ",len(X_train), len(Y_train) + Y_train_pict = np.array([1]*(len(X_train)-nb_hidden) + [0]*nb_hidden) + + X_train = [one_hot_colors(x) for x in X_train] + X_train, Y_train, Y_train_pict = shuffle_in_unison(X_train, Y_train, Y_train_pict) + X_train_pict_feat = prepare_picture_data(X_train) + X_train_directions, X_train_edge_features = prepare_data(X_train) + + #-------------------------------------------------------------------------------------------------- + if True: + print "===========================================================================" + from pystruct.models.edge_feature_graph_crf import EdgeFeatureGraphCRF + print "ONE TYPE TRAINING AND TESTING: PIXELS" + + inference = "qpbo" + crf = EdgeFeatureGraphCRF(inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + #max_iter=MAXITER, + n_jobs=N_JOBS + #,verbose=1 + , switch_to='ad3' + ) + + Y_train_flat = [y_.ravel() for y_ in Y_train] + print "\ttrain label histogram : ", np.histogram(np.hstack(Y_train_flat), bins=range(NCELL+2)) + + t0 = time.time() + ssvm.fit(X_train_edge_features, Y_train_flat) + print "FIT DONE IN %.1fs"%(time.time() - t0) + sys.stdout.flush() + + t0 = time.time() + _Y_pred = ssvm.predict( X_test_edge_features ) + REPORT(Y_test, _Y_pred, time.time() - t0, NCELL, "gen.csv", True, "singletype_%d"%nbSample) + _Y_pred = ssvm.predict( X_test_gen_edge_features ) + REPORT(Y_test_gen, _Y_pred, None , NCELL, "gen.csv", True, "singletype_%d_gentest"%nbSample) + + #-------------------------------------------------------------------------------------------------- + if True: + print "_"*50 + print "ONE TYPE TRAINING AND TESTING: PICTURES" + + print "\ttrain label histogram : ", np.histogram(Y_train_pict, bins=range(3)) + + lr = LogisticRegression(class_weight='balanced') + + mdl = GridSearchCV(lr , {'C':[0.1, 0.5, 1.0, 2.0] }) + + XX = np.vstack(X_train_pict_feat) + + t0 = time.time() + mdl.fit(XX, Y_train_pict) + print "FIT DONE IN %.1fs"%(time.time() - t0) + + t0 = time.time() + _Y_pred = mdl.predict( np.vstack(X_test_pict_feat) ) + REPORT([Y_test_pict], _Y_pred, time.time() - t0, 2, "gen.csv", True, "picture_logit_%d"%nbSample) + + #-------------------------------------------------------------------------------------------------- + print "======================================================================================================" + + l_n_states = [NCELL+1, 2] # 11 states for pixel nodes, 2 states for pictures + l_n_feat = [45, 7] # 45 features for pixels, 7 for pictures + ll_n_feat = [[180, 45], # 2 feature between pixel nodes, 1 between pixel and picture + [45 , 0]] # , nothing between picture nodes (no picture_to_picture edge anyway) + + print " TRAINING MULTI-TYPE MODEL " + #TRAINING + crf = NodeTypeEdgeFeatureGraphCRF(2, # How many node types? + l_n_states, # How many states per type? + l_n_feat, # How many node features per type? + ll_n_feat, # How many edge features per type x type? + inference_method=INFERENCE + ) + print crf + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=0.1, + #max_iter=MAXITER, + n_jobs=N_JOBS + ) + + print "======================================================================================================" + print "YY[0].shape", Y_train[0].shape + XX, YY = convertToTwoType(X_train, + X_train_edge_features, # list of node_feat , edges, edge_feat for pixel nodes + Y_train, + X_train_pict_feat, #a list of picture_node_features + Y_train_pict, #a list of integers [0,1] + nCell=NCELL) + + print "\tlabel histogram : ", np.histogram( np.hstack([y.ravel() for y in YY]), bins=range(14)) + + + print "YY[0].shape", YY[0].shape + crf.initialize(XX, YY)# check if the data is properly built + sys.stdout.flush() + + t0 = time.time() + ssvm.fit(XX, YY) + print "FIT DONE IN %.1fs"%(time.time() - t0) + sys.stdout.flush() + + print "_"*50 + XX_test, YY_test =convertToTwoType(X_test, + X_test_edge_features, # list of node_feat , edges, edge_feat for pixel nodes + Y_test, + X_test_pict_feat, #a list of picture_node_features + Y_test_pict, #a list of integers [0,1] + nCell=NCELL) + print "\tlabel histogram (PIXELs and PICTUREs): ", np.histogram( np.hstack([y.ravel() for y in YY_test]), bins=range(14)) + XX_test_gen, YY_test_gen =convertToTwoType(X_test_gen, + X_test_gen_edge_features, # list of node_feat , edges, edge_feat for pixel nodes + Y_test_gen, + X_test_pict_feat, #a list of picture_node_features + Y_test_pict, #a list of integers [0,1] + nCell=NCELL) + + + l_constraints = listConstraints_ATMOSTONE(XX_test , NCELL) + l_constraints_gen = listConstraints_ATMOSTONE(XX_test_gen, NCELL) + + print "_"*50 + print "\t- results without constraints (using %s)"%INFERENCE + t0 = time.time() + YY_pred = ssvm.predict( XX_test ) + REPORT(YY_test, YY_pred, time.time() - t0 , NCELL+2, "gen.csv", True, "multitype_%d"%nbSample) + YY_pred = ssvm.predict( XX_test_gen ) + REPORT(YY_test_gen, YY_pred, None , NCELL+2, "gen.csv", True, "multitype_%d_gentest"%nbSample) + + print "_"*50 + print "\t- results exploiting constraints (using ad3+)" + ssvm.model.inference_method = "ad3+" + t0 = time.time() + YY_pred = ssvm.predict( XX_test , l_constraints ) + REPORT(YY_test, YY_pred, time.time() - t0 , NCELL+2, "gen.csv", True, "multitype_constraints_%d"%nbSample) + YY_pred = ssvm.predict( XX_test_gen , l_constraints_gen ) + REPORT(YY_test_gen, YY_pred, None , NCELL+2, "gen.csv", True, "multitype_constraints_%d_gentest"%nbSample) + + + print "_"*50 + + print "One Experiment DONE" + + print "ALL EXPERIMENTS DONE" + + printConfig() + \ No newline at end of file diff --git a/examples/plot_hidden_snakes.py b/examples/plot_hidden_snakes.py index ea1b05c5..b83aa3d1 100644 --- a/examples/plot_hidden_snakes.py +++ b/examples/plot_hidden_snakes.py @@ -58,10 +58,6 @@ from plot_snakes import one_hot_colors, prepare_data -if True: - np.random.seed(1605) - random.seed(98) - def isSnakePresent(a_hot_picture, nCell=10): """ Algorithmic check, to make sure that after tempering with the snake we do not have a snake! :-) @@ -211,6 +207,9 @@ def shorten_snakes(lX,lY, N): #===================================================================================================== if __name__ == '__main__': + np.random.seed(1605) + random.seed(98) + print("Please be patient. Learning will take 5-20 minutes.") #if you want to shorten all the snakes From 871ceee81e9bc8bc20b20e740d6a3b26a3ae221e Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 13 Apr 2017 10:32:15 +0200 Subject: [PATCH 086/155] code cleaning --- examples/plot_hidden_short_snakes_typed.py | 54 ++++++++++++++-------- 1 file changed, 35 insertions(+), 19 deletions(-) diff --git a/examples/plot_hidden_short_snakes_typed.py b/examples/plot_hidden_short_snakes_typed.py index 43e04804..1a979083 100644 --- a/examples/plot_hidden_short_snakes_typed.py +++ b/examples/plot_hidden_short_snakes_typed.py @@ -5,9 +5,9 @@ This is a variant of plot_snakes.py -Snake are hidding, so we have 2 tasks: +Snake are hidding, so we have 2 categorisers: - determining if a snake is in the picture, -- identifying its head to tail body. +- identifying its head to tail body (at pixel-level) We use the NodeTypeEdgeFeatureGraphCRF class with 2 type of nodes. @@ -83,7 +83,7 @@ bMAKE_PICT_EASY = False #DEBUG: we had a feature on the picture that tells directly if a snake is present or not #INFERENCE="ad3+" #ad3+ is required when there are hard logic constraints -INFERENCE="ad3" #ad3 is faster than ad3+ and both should yield same results +INFERENCE="ad3" #ad3 is faster than ad3+ N_JOBS=8 MAXITER=750 @@ -106,13 +106,6 @@ def printConfig(): if __name__ == '__main__': printConfig() -if bFIXED_RANDOM_SEED: - np.random.seed(1605) - random.seed(98) -else: - np.random.seed() - random.seed() - def plot_snake(picture): plt.imshow(picture, interpolation='nearest') plt.show() @@ -271,7 +264,7 @@ def swap_node_types(l_perm, l_n_state, lX, lY, constraints=None): return _lX, _lY, _constraints -def listConstraints(lX): +def listConstraints(lX, ncell=NCELL): """ produce the list of constraints for this list of multi-type graphs """ @@ -285,7 +278,7 @@ def listConstraints(lX): lConstraint_for_X = [("ANDOUT", l_l_unary, l_l_states, l_l_negated)] #we have a list of constraints per X - for _state in range(1, NCELL+1): + for _state in range(1, ncell+1): lConstraint_for_X.append( ("XOROUT" , l_l_unary , [ _state, 1 ] #exactly one cell in state _state with picture label being snake , l_l_negated) @@ -294,7 +287,7 @@ def listConstraints(lX): lConstraints.append( lConstraint_for_X ) return lConstraints -def listConstraints_ATMOSTONE(lX): +def listConstraints_ATMOSTONE(lX, ncell=NCELL): """ produce the list of constraints for this list of multi-type graphs """ @@ -305,7 +298,7 @@ def listConstraints_ATMOSTONE(lX): lConstraint_for_X = list() - for _state in range(1, NCELL+1): + for _state in range(1, ncell+1): lConstraint_for_X.append( ("ATMOSTONE" , [ range(nb_pixels), []] , [ _state, None ] #atmost one cell in state _state whatever picture label , [ False, None ]) @@ -323,7 +316,14 @@ def makeItEasy(lX_pict_feat, lY_pict): X[0] = y -def REPORT(l_Y_GT, lY_Pred, t=None): +def appendIntVectorToCsv(fd, name, aV): + saV = np.array_str(aV, max_line_width=99999, precision=0) + saV = saV.strip()[1:-1] #removal of brackets + saV = ','.join(saV.split()) + fd.write("%s,%s\n"%(name, saV)) + fd.flush() + +def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, name=""): if t: print "\t( predict DONE IN %.1fs)"%t _flat_GT, _flat_P = (np.hstack([y.ravel() for y in l_Y_GT]), @@ -331,10 +331,25 @@ def REPORT(l_Y_GT, lY_Pred, t=None): confmat = confusion_matrix(_flat_GT, _flat_P) print confmat print "\ttrace =", confmat.trace() - print "\tAccuracy= %.3f"%accuracy_score(_flat_GT, _flat_P) + score = accuracy_score(_flat_GT, _flat_P) + print "\tAccuracy= %.3f"%score + #CSV out? + if filename: + histo = np.histogram(np.hstack(_flat_GT), bins=range(ncell+2)) + diag = np.diag(confmat) + with open(filename, "ab") as fdCSV: + if bHisto: appendIntVectorToCsv(fdCSV, name+"_histo,", histo[0]) + appendIntVectorToCsv(fdCSV, name+",%.3f"%score, diag) if __name__ == '__main__': + + if bFIXED_RANDOM_SEED: + np.random.seed(1605) + random.seed(98) + else: + np.random.seed() + random.seed() print("Please be patient...") snakes = load_snakes() @@ -392,7 +407,7 @@ def REPORT(l_Y_GT, lY_Pred, t=None): inference=INFERENCE inference = "qpbo" crf = EdgeFeatureGraphCRF(inference_method=inference) - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=0, max_iter=MAXITER, n_jobs=N_JOBS #,verbose=1 @@ -466,7 +481,7 @@ def REPORT(l_Y_GT, lY_Pred, t=None): ) print crf - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=0, + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=0, max_iter=MAXITER, n_jobs=N_JOBS #,verbose=1 @@ -527,7 +542,8 @@ def REPORT(l_Y_GT, lY_Pred, t=None): print "\tlabel histogram (PIXELs and PICTUREs): ", np.histogram( np.hstack([y.ravel() for y in YY_test]), bins=range(14)) - l_constraints = listConstraints(XX_test) +# l_constraints = listConstraints(XX_test) + l_constraints = listConstraints_ATMOSTONE(XX_test) if nbSWAP_Pixel_Pict_TYPES %2 == 1: XX_test, YY_test, l_constraints = swap_node_types([1,0], [NCELL+1, 2], XX_test, YY_test, l_constraints) From 9a6f6f6538632b9a503e162f106ab481054c775e Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 22 Jun 2017 15:39:19 +0200 Subject: [PATCH 087/155] when a type of node is not present, _check_size_xy should not crash --- pystruct/models/typed_crf.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index a94fc23d..fc217228 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -211,6 +211,7 @@ def _check_size_xy(self, X, Y): i_start = 0 for typ, nf, n_states in zip(range(self.n_types), l_node_features, self.l_n_states): nb_nodes = nf.shape[0] + if nb_nodes == 0: continue Y_typ = Y[i_start:i_start+nb_nodes] if np.min(Y_typ) < 0: raise ValueError("Got a negative label for type %d"%typ) From aa461b39a9aa51ff8a34ed70cb17b0a5b6af7657 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 22 Jun 2017 15:39:52 +0200 Subject: [PATCH 088/155] preparing for "0.3.5" --- pystruct/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pystruct/__init__.py b/pystruct/__init__.py index 334b8995..a8d4557d 100644 --- a/pystruct/__init__.py +++ b/pystruct/__init__.py @@ -1 +1 @@ -__version__ = "0.3.4" +__version__ = "0.3.5" From fdbf5fbd8775abb093efc29b4b6a8b6b4124af6b Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 9 Aug 2017 11:20:02 +0200 Subject: [PATCH 089/155] clarification --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 13c65b0c..cb91b7ef 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,7 @@ In multiple type graphs, with *_n_types* types, an instance *X* is represented a (*l_node_features*, *l_edges*, *l_edge_features*) representing the graph. * *l_node_feature*s is a list of length *n_types* containing arrays of shape (*n_typ_node*, *n_typ_features*), where *n_typ_node* is the number of nodes of that type, while *n_typ_features* is the number of features for this type of nodes. -* *l_edges* is a list of length *n_types*^2 . Each of its elements contains an array of shape (*n_typ_edge, 2) defining the edges from nodes of type *i* to nodes of type *j*, with *i* and *j* in [0, *n_types*-1], *j* being the secondary index (inner loop). +* *l_edges* is a list of length *n_types*^2 . Each of its elements contains an array of shape (*n_typ_edge, 2) defining the edges from nodes of type *i* to nodes of type *j*, with *i* and *j* in [0, *n_types*-1], *j* being the secondary index (inner loop). The index of the nodes in each type starts at 0. * *l_edge_features* is a list of length *n_types*^2. It contains the features of the edges for each pair of types, in same order as in previous parameter. Each item is an array of shape (*n_typ_edges*, *n_typ_edge_features*). if *n_typ_edge_features* is 0, then *n_typ_edges* should be 0 as well for all instances of graph! If you want an edge without features, set *n_typ_edge_features* to 1 and pass 1.0 as feature for all edges (of that type). Each *Y* remains a vector array. While the label could start at 0 for all types, we have chosen not to do so. (Essentially,to make clear that types do not blend into each other, which is clear when you show a confusion matrix). So the labels of the first type start at 0, while labels of next type starts right after the value of the last label of previous type. From a45de7bcc72746a154440755601f094a03a35cfe Mon Sep 17 00:00:00 2001 From: meunier Date: Wed, 13 Sep 2017 17:38:34 +0200 Subject: [PATCH 090/155] grid_search.GridSearchCV deprecated --- examples/plot_hidden_short_snakes_typed.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/plot_hidden_short_snakes_typed.py b/examples/plot_hidden_short_snakes_typed.py index 1a979083..b80fe02d 100644 --- a/examples/plot_hidden_short_snakes_typed.py +++ b/examples/plot_hidden_short_snakes_typed.py @@ -60,7 +60,8 @@ from sklearn.metrics import confusion_matrix, accuracy_score from sklearn.linear_model import LogisticRegression -from sklearn.grid_search import GridSearchCV +#from sklearn.grid_search import GridSearchCV +from sklearn.model_selection import GridSearchCV from pystruct.learners import OneSlackSSVM from pystruct.datasets import load_snakes From b62c00969ddb6df15505344f6082e3f740b91ffd Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 15 Sep 2017 10:58:50 +0200 Subject: [PATCH 091/155] making sure train and test are disjoint --- .../plot_hidden_short_snakes_typed_gen.py | 123 +++++++++++++----- 1 file changed, 87 insertions(+), 36 deletions(-) diff --git a/examples/plot_hidden_short_snakes_typed_gen.py b/examples/plot_hidden_short_snakes_typed_gen.py index 11c34e4e..dce94d1d 100644 --- a/examples/plot_hidden_short_snakes_typed_gen.py +++ b/examples/plot_hidden_short_snakes_typed_gen.py @@ -82,13 +82,14 @@ #INFERENCE="ad3+" #ad3+ is required when there are hard logic constraints INFERENCE="ad3" #ad3 is faster than ad3+ N_JOBS=8 - #MAXITER=750 - lNbSAMPLE=[200, 400, 600, 800] #how many sample do we generate for each experiment? - nbEXPERIMENT = 10 +# N_JOBS=1 +# lNbSAMPLE=[20] +# nbEXPERIMENT=1 +# MAXITER=3 #============================================================================================== def printConfig(): @@ -103,18 +104,12 @@ def printConfig(): if __name__ == '__main__': printConfig() -if bFIXED_RANDOM_SEED: - np.random.seed(1605) - random.seed(98) -else: - np.random.seed() - random.seed() - class GenSnakeException(Exception): pass -def genSnakes(N, ncell=NCELL): +def genSnakes(N, dUniqueSnakelij, ncell=NCELL): """ Generate snakes at random. + dUniqueSnakelij contains the signature of all Snakes. We ensure unicity of each Snake. Return N tuple (snakes, Y) """ ltSnakeY = [] @@ -144,17 +139,22 @@ def genSnakes(N, ncell=NCELL): lij.append( (i,j) ) ldir.append(dir) i,j = _i,_j - #ok we have a Snake, let's create the image with background borders - imin,jmin = map(min, zip(*lij)) - imax,jmax = map(max, zip(*lij)) - aSnake = np.zeros((imax-imin+3, jmax-jmin+3, 3), dtype=np.uint8) - aSnake[:,:,2] = 255 #0,0,255 - aY = np.zeros((imax-imin+3, jmax-jmin+3) , dtype=np.uint8) - for _lbl, ((_i,_j), _dir) in enumerate(zip(lij, ldir)): - aSnake[_i-imin+1, _j-jmin+1,:] = lDirectionColor[_dir] - aY [_i-imin+1, _j-jmin+1] = _lbl + 1 - - break + try: + dUniqueSnakelij[tuple(lij)] + raise GenSnakeException("Same as in trainset") + except KeyError: + dUniqueSnakelij[tuple(lij)] = True + #ok we have a Snake, let's create the image with background borders + imin,jmin = map(min, zip(*lij)) + imax,jmax = map(max, zip(*lij)) + aSnake = np.zeros((imax-imin+3, jmax-jmin+3, 3), dtype=np.uint8) + aSnake[:,:,2] = 255 #0,0,255 + aY = np.zeros((imax-imin+3, jmax-jmin+3) , dtype=np.uint8) + for _lbl, ((_i,_j), _dir) in enumerate(zip(lij, ldir)): + aSnake[_i-imin+1, _j-jmin+1,:] = lDirectionColor[_dir] + aY [_i-imin+1, _j-jmin+1] = _lbl + 1 + + break except GenSnakeException: pass ltSnakeY.append( (aSnake, aY) ) # print aSnake @@ -162,9 +162,56 @@ def genSnakes(N, ncell=NCELL): # plot_snake(aSnake) return ltSnakeY +def plot_many_snakes(lX, nv=10, nh=20, ncell=NCELL): + """ + Plot the one-hot-encoded snake on grids of size nv x nh + """ + N = ncell+1 #to have border + i = 0 + while i < len(lX): + j = min(i+nv*nh, len(lX)) + lImg = lX[i:j] + allimg = np.zeros(shape=(N*nv,N*nh,3), dtype=np.uint8) + ih,iw = 0,0 + for i_img, img in enumerate(lImg): + h,w,c = img.shape + assert c == 3 + allimg[ih:ih+h, iw:iw+w, :] = img + iw += N + if i_img % nh == (nh-1): + ih += N + iw = 0 + plot_snake(allimg) + i = j + +def plot_mistakes(lY_ref, lY_pred, lX_pict, ncell=NCELL): + """ + Plot snake wrongly predicted, first NoSnake pictures, then Snake pictures + """ + _ltSnake = (list(), list()) #misclassified NoSnake pictures, misclassified Snake pictures + for _y_ref, _y_pred, _x in zip(lY_ref, lY_pred, lX_pict): + assert _y_ref.shape==_y_pred.shape + assert _y_ref.size ==_x.size/3+1 + assert _y_ref[-1] in [ncell+1,ncell+2] + if _y_ref[-1] != _y_pred[-1]: + iSnake = _y_ref[-1] - ncell - 1 #0=NoSnake 1=Snake + _ltSnake[iSnake].append(_x) + + print "NoSnake pictures predicted as Snake" + plot_many_snakes(_ltSnake[0]) + print "Snake pictures predicted as NoSnake" + plot_many_snakes(_ltSnake[1]) + + if __name__ == '__main__': + if bFIXED_RANDOM_SEED: + np.random.seed(1605) + random.seed(98) + else: + np.random.seed() + random.seed() print("Please be patient...") snakes = load_snakes() @@ -172,12 +219,14 @@ def genSnakes(N, ncell=NCELL): #-------------------------------------------------------------------------------------------------- #we always test against the original test set X_test, Y_test = snakes['X_test'], snakes['Y_test'] + #plot_many_snakes(X_test) +# X_test_img = X_test if NCELL <10: X_test, Y_test = shorten_snakes(X_test, Y_test, NCELL) - + nb_hidden, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", False, nCell=NCELL) Y_test_pict = np.array([1]*(len(X_test)-nb_hidden) + [0]*nb_hidden) print "TEST SET ", len(X_test), len(Y_test) - + X_test_pict = X_test X_test = [one_hot_colors(x) for x in X_test] X_test_pict_feat = prepare_picture_data(X_test) X_test_directions, X_test_edge_features = prepare_data(X_test) @@ -188,23 +237,24 @@ def genSnakes(N, ncell=NCELL): print "# EXPERIMENT %d / %d"%(iExp+1, nbEXPERIMENT) print "#"*75 + dUniqueSnakelij = dict() - lXY = genSnakes(max(lNbSAMPLE)) + lXY = genSnakes(max(lNbSAMPLE), dUniqueSnakelij) X_train_all, Y_train_all = zip(*lXY) X_train_all, Y_train_all = list(X_train_all), list(Y_train_all) print "***** GENERATED %d snakes of length %d *****"%(len(X_train_all), NCELL) #Also generate an additional test set NTEST=100 - lXYTest = genSnakes( NTEST ) + lXYTest = genSnakes( NTEST, dUniqueSnakelij ) X_test_gen, Y_test_gen = zip(*lXYTest) X_test_gen, Y_test_gen = list(X_test_gen), list(Y_test_gen) print "***** GENERATED %d snakes of length %d *****"%(NTEST, NCELL) +# plot_many_snakes(X_test_img+X_test_gen) nb_hidden, X_test_gen, Y_test_gen = augmentWithNoSnakeImages(X_test_gen, Y_test_gen, "test_gen", False, nCell=NCELL) Y_test_gen_pict = np.array([1]*(len(X_test_gen)-nb_hidden) + [0]*nb_hidden) print "GENERATED TEST SET ", len(X_test_gen), len(Y_test_gen) - X_test_gen = [one_hot_colors(x) for x in X_test_gen] X_test_gen_pict_feat = prepare_picture_data(X_test_gen) X_test_gen_directions, X_test_gen_edge_features = prepare_data(X_test_gen) @@ -232,7 +282,7 @@ def genSnakes(N, ncell=NCELL): inference = "qpbo" crf = EdgeFeatureGraphCRF(inference_method=inference) ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, - #max_iter=MAXITER, +# max_iter=MAXITER, n_jobs=N_JOBS #,verbose=1 , switch_to='ad3' @@ -248,9 +298,9 @@ def genSnakes(N, ncell=NCELL): t0 = time.time() _Y_pred = ssvm.predict( X_test_edge_features ) - REPORT(Y_test, _Y_pred, time.time() - t0, NCELL, "gen.csv", True, "singletype_%d"%nbSample) + REPORT(Y_test, _Y_pred, time.time() - t0, NCELL, "gen_singletype_%d.csv"%nbSample, True, "singletype_%d"%nbSample) _Y_pred = ssvm.predict( X_test_gen_edge_features ) - REPORT(Y_test_gen, _Y_pred, None , NCELL, "gen.csv", True, "singletype_%d_gentest"%nbSample) + REPORT(Y_test_gen, _Y_pred, None , NCELL, "gen_singletype_gentest_%d.csv"%nbSample, True, "singletype_%d_gentest"%nbSample) #-------------------------------------------------------------------------------------------------- if True: @@ -271,7 +321,7 @@ def genSnakes(N, ncell=NCELL): t0 = time.time() _Y_pred = mdl.predict( np.vstack(X_test_pict_feat) ) - REPORT([Y_test_pict], _Y_pred, time.time() - t0, 2, "gen.csv", True, "picture_logit_%d"%nbSample) + REPORT([Y_test_pict], _Y_pred, time.time() - t0, 2, "gen_picture.csv", True, "picture_logit_%d"%nbSample) #-------------------------------------------------------------------------------------------------- print "======================================================================================================" @@ -291,7 +341,7 @@ def genSnakes(N, ncell=NCELL): ) print crf ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=0.1, - #max_iter=MAXITER, +# max_iter=MAXITER, n_jobs=N_JOBS ) @@ -339,18 +389,19 @@ def genSnakes(N, ncell=NCELL): print "\t- results without constraints (using %s)"%INFERENCE t0 = time.time() YY_pred = ssvm.predict( XX_test ) - REPORT(YY_test, YY_pred, time.time() - t0 , NCELL+2, "gen.csv", True, "multitype_%d"%nbSample) + REPORT(YY_test, YY_pred, time.time() - t0 , NCELL+2, "gen_multitype_%d.csv"%nbSample, True, "multitype_%d"%nbSample) + #plot_mistakes(YY_test, YY_pred, X_test_pict) YY_pred = ssvm.predict( XX_test_gen ) - REPORT(YY_test_gen, YY_pred, None , NCELL+2, "gen.csv", True, "multitype_%d_gentest"%nbSample) + REPORT(YY_test_gen, YY_pred, None , NCELL+2, "gen_multitype_gentest_%d.csv"%nbSample, True, "multitype_%d_gentest"%nbSample) print "_"*50 print "\t- results exploiting constraints (using ad3+)" ssvm.model.inference_method = "ad3+" t0 = time.time() YY_pred = ssvm.predict( XX_test , l_constraints ) - REPORT(YY_test, YY_pred, time.time() - t0 , NCELL+2, "gen.csv", True, "multitype_constraints_%d"%nbSample) + REPORT(YY_test, YY_pred, time.time() - t0 , NCELL+2, "gen_multitype_constraints_%d.csv"%nbSample, True, "multitype_constraints_%d"%nbSample) YY_pred = ssvm.predict( XX_test_gen , l_constraints_gen ) - REPORT(YY_test_gen, YY_pred, None , NCELL+2, "gen.csv", True, "multitype_constraints_%d_gentest"%nbSample) + REPORT(YY_test_gen, YY_pred, None , NCELL+2, "gen_multitype_constraints_gentest_%d.csv"%nbSample, True, "multitype_constraints_%d_gentest"%nbSample) print "_"*50 From a7b90dd3e0cda82c6ae438f25daf200ffa3208f4 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 15 Sep 2017 10:59:54 +0200 Subject: [PATCH 092/155] TypeError fixed --- pystruct/tests/test_learners/test_latent_node_crf_learning.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pystruct/tests/test_learners/test_latent_node_crf_learning.py b/pystruct/tests/test_learners/test_latent_node_crf_learning.py index 64c7e3d7..3c01ac9a 100644 --- a/pystruct/tests/test_learners/test_latent_node_crf_learning.py +++ b/pystruct/tests/test_learners/test_latent_node_crf_learning.py @@ -55,7 +55,7 @@ def test_binary_blocks_cutting_plane_latent_node(): check_constraints=True, break_on_bad=False, n_jobs=1), latent_iter=3) - X_latent = list(zip(X_, G, np.zeros(len(X_)))) + X_latent = list(zip(X_, G, np.zeros(len(X_), dtype=np.int))) latent_svm.fit(X_latent, Y, H_init=Y) Y_pred = latent_svm.predict(X_latent) for y, y_pred in zip(Y, Y_pred): From 62f55b308312832e9151ed46072bd17ff1db870d Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 15 Sep 2017 11:00:28 +0200 Subject: [PATCH 093/155] sklearn API change --- pystruct/tests/test_learners/test_graph_svm.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pystruct/tests/test_learners/test_graph_svm.py b/pystruct/tests/test_learners/test_graph_svm.py index 6093d40e..65aceaac 100644 --- a/pystruct/tests/test_learners/test_graph_svm.py +++ b/pystruct/tests/test_learners/test_graph_svm.py @@ -86,5 +86,5 @@ def test_standard_svm_blobs_2d_class_weight(): break_on_bad=False) svm_class_weight.fit(X_graphs, Y[:, np.newaxis]) - assert_greater(f1_score(Y, np.hstack(svm_class_weight.predict(X_graphs))), - f1_score(Y, np.hstack(svm.predict(X_graphs)))) + assert_greater(f1_score(Y, np.hstack(svm_class_weight.predict(X_graphs)), average='micro'), + f1_score(Y, np.hstack(svm.predict(X_graphs)) , average='micro')) From 88a05360e73b916e4a492a9bfabdb5375c718c2a Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 15 Sep 2017 11:01:06 +0200 Subject: [PATCH 094/155] sklearn API change minor fix in test case --- .../tests/test_learners/test_crammer_singer_svm.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/pystruct/tests/test_learners/test_crammer_singer_svm.py b/pystruct/tests/test_learners/test_crammer_singer_svm.py index aa61bed0..6b2a5d60 100644 --- a/pystruct/tests/test_learners/test_crammer_singer_svm.py +++ b/pystruct/tests/test_learners/test_crammer_singer_svm.py @@ -180,8 +180,8 @@ def test_class_weights(): svm_class_weight = OneSlackSSVM(pbl_class_weight, C=10) svm_class_weight.fit(X, Y) - assert_greater(f1_score(Y, svm_class_weight.predict(X)), - f1_score(Y, svm.predict(X))) + assert_greater(f1_score(Y, svm_class_weight.predict(X) , average='micro'), + f1_score(Y, svm.predict(X) , average='micro')) def test_class_weights_rescale_C(): @@ -191,7 +191,7 @@ def test_class_weights_rescale_C(): X, Y = make_blobs(n_samples=210, centers=3, random_state=1, cluster_std=3, shuffle=False) X = np.hstack([X, np.ones((X.shape[0], 1))]) - X, Y = X[:170], Y[:170] + #X, Y = X[:170], Y[:170] weights = 1. / np.bincount(Y) weights *= len(weights) / np.sum(weights) @@ -202,11 +202,11 @@ def test_class_weights_rescale_C(): try: linearsvm = LinearSVC(multi_class='crammer_singer', - fit_intercept=False, class_weight='auto', C=10) + fit_intercept=False, class_weight='balanced', C=10) linearsvm.fit(X, Y) assert_array_almost_equal(svm_class_weight.w, linearsvm.coef_.ravel(), - 3) + 2) #3 --> fail :-/ except TypeError: # travis has a really old sklearn version that doesn't support # class_weight in LinearSVC From 5f4b2345af17e6d11e3bb62527e36a64c8da9bc6 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 15 Sep 2017 11:01:44 +0200 Subject: [PATCH 095/155] bug fix (ZeroDivision error due to 'verbose' set to -1) --- pystruct/learners/subgradient_latent_ssvm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pystruct/learners/subgradient_latent_ssvm.py b/pystruct/learners/subgradient_latent_ssvm.py index 45b91841..97ef51ac 100644 --- a/pystruct/learners/subgradient_latent_ssvm.py +++ b/pystruct/learners/subgradient_latent_ssvm.py @@ -274,7 +274,7 @@ def score(self, X, Y): def _objective(self, X, Y): constraints = Parallel( n_jobs=self.n_jobs, - verbose=self.verbose - 1)(delayed(find_constraint_latent)( + verbose=self.verbose)(delayed(find_constraint_latent)( self.model, x, y, self.w) for x, y in zip(X, Y)) slacks = list(zip(*constraints))[2] From ab247e1c757d5a59c33acea01ea8b22b9c54a32f Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 15 Sep 2017 11:11:38 +0200 Subject: [PATCH 096/155] RC 0.3.5 --- CHANGELOG | 5 +++++ README.md | 4 ++-- setup.py | 2 +- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index c02066ba..43e964d0 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,8 @@ +0.3.5 +=== +- Few fixes +- all tests are passing + 0.3.4 === - MIT license diff --git a/README.md b/README.md index cb91b7ef..8928c4cf 100644 --- a/README.md +++ b/README.md @@ -35,8 +35,8 @@ What is different in pystruct+? Currently, the offered extensions rely on the __*AD3+*__ solver. For learning I mostly used the __*OneSlackSSVM*__ learner, which requires to install cvxopt as well. ### For AD3+: - * get the source code from https://github.com/jlmeunier/AD3 - * compile and install: + * get it from https://github.com/jlmeunier/AD3 + * install: python setup.py install > python setup.py install diff --git a/setup.py b/setup.py index 0a9c74f3..3ecc1255 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ include_dirs = [np.get_include()] setup(name="pystruct", - version="0.3.4", + version="0.3.5", install_requires=["ad3>=2.1.2"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', From 8df4238049d6afe2412d2458764646fe4b2c0757 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 15 Sep 2017 11:11:54 +0200 Subject: [PATCH 097/155] RC 0.3.5 --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 29a24a97..26125190 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,4 +3,4 @@ scipy cvxopt Cython>=0.19.1 scikit-learn>=0.11 -ad3 +ad3>=2.1.2 From 570b16a953ab3a2676f6d7eb361dc00acc8d6166 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 11 Oct 2017 09:57:33 +0200 Subject: [PATCH 098/155] fix in prepare_data function, of the edge features for Snake example --- .../logs/plot_hidden_short_snakes_typed.log | 169 ++++++++++++++++++ examples/logs/plot_snakes.log | 42 +++++ examples/plot_snakes.py | 24 +-- 3 files changed, 225 insertions(+), 10 deletions(-) diff --git a/examples/logs/plot_hidden_short_snakes_typed.log b/examples/logs/plot_hidden_short_snakes_typed.log index 89b36227..acddde7c 100644 --- a/examples/logs/plot_hidden_short_snakes_typed.log +++ b/examples/logs/plot_hidden_short_snakes_typed.log @@ -156,3 +156,172 @@ DONE == EASY= False == MAX_ITER= 750 == MODEL FILE= model.pkl + + + ================================================================================= + After fixing prepare_data: + Oct 9 2017 + + edge_features[:len(right), :, 0] = features[right[:, 0]] + edge_features[:len(right), :, 1] = features[right[:, 1]] +#ORIG +# edge_features[len(right):, :, 0] = features[down[:, 0]] +# edge_features[len(right):, :, 1] = features[down[:, 1]] + edge_features[len(right):, :, 2] = features[down[:, 0]] + edge_features[len(right):, :, 3] = features[down[:, 1]] + + +== NCELL= 10 +== FIXED_SEED= True +== INFERENCE = ad3 +== N_JOBS = 8 +== SWAP= 0 +== EASY= False +== MAX_ITER= 750 +== MODEL FILE= model.pkl +Please be patient... +TRAIN SET 200 200 +ADDING PICTURE WIHOUT SNAKES!!! 200 elements in train + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! +TRAIN SET 376 376 +ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! + - DISCARDING a shuffled snake which is still a snake!!!! +TEST SET 187 187 +====================================================================================================== +ONE TYPE TRAINING AND TESTING: PIXELS + train label histogram : (array([12198, 200, 200, 200, 200, 200, 200, 200, 200, + 200, 200], dtype=int64), array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])) +FIT DONE IN 1340.7s + ( predict DONE IN 14.0s) +[[5605 37 37 37 33 32 35 38 49 56 56] + [ 14 86 0 0 0 0 0 0 0 0 0] + [ 13 0 85 2 0 0 0 0 0 0 0] + [ 11 0 2 85 2 0 0 0 0 0 0] + [ 11 0 0 2 85 2 0 0 0 0 0] + [ 10 0 0 0 2 85 2 1 0 0 0] + [ 10 0 1 0 0 2 85 2 0 0 0] + [ 9 0 0 1 0 0 2 86 2 0 0] + [ 7 0 0 0 1 0 0 2 87 2 1] + [ 8 1 0 0 0 1 0 0 1 87 2] + [ 10 0 1 0 0 0 1 0 0 0 88]] + trace = 6464 + Accuracy= 0.921 +__________________________________________________ +ONE TYPE TRAINING AND TESTING: PICTURES + train label histogram : (array([176, 200], dtype=int64), array([0, 1, 2])) +FIT DONE IN 0.1s +[[30 57] + [47 53]] + trace = 83 + Accuracy= 0.444 +====================================================================================================== + TRAINING MULTI-TYPE MODEL +NodeTypeEdgeFeatureGraphCRF(n_states: [11, 2], inference_method: ad3, n_features: [45, 7], n_edge_features: [[180 45] + [ 45 0]]) +====================================================================================================== +YY[0].shape (6L, 6L) + label histogram : (array([12198, 200, 200, 200, 200, 200, 200, 200, 200, + 200, 200, 176, 200], dtype=int64), array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])) +YY[0].shape (37L,) +FIT DONE IN 1878.1s +Saving model in: model.pkl +INFERENCE WITH ad3 + label histogram (PIXELs and PICTUREs): (array([6015, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, + 87, 100], dtype=int64), array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])) + - results without constraints (using ad3) + ( predict DONE IN 16.6s) +[[5760 23 26 28 28 26 23 22 23 28 28 0 0] + [ 6 93 1 0 0 0 0 0 0 0 0 0 0] + [ 6 0 92 2 0 0 0 0 0 0 0 0 0] + [ 6 0 0 92 2 0 0 0 0 0 0 0 0] + [ 5 0 0 0 92 3 0 0 0 0 0 0 0] + [ 5 0 0 0 0 92 3 0 0 0 0 0 0] + [ 5 0 1 0 0 0 91 3 0 0 0 0 0] + [ 5 0 0 1 0 0 0 91 3 0 0 0 0] + [ 6 0 0 0 1 1 0 0 91 1 0 0 0] + [ 6 0 0 0 0 1 1 0 0 91 1 0 0] + [ 5 0 0 0 0 0 1 2 0 0 92 0 0] + [ 0 0 0 0 0 0 0 0 0 0 0 62 25] + [ 0 0 0 0 0 0 0 0 0 0 0 5 95]] + trace = 6834 + Accuracy= 0.949 +__________________________________________________ + - results exploiting constraints (using ad3+) + ( predict DONE IN 182.0s) +[[5749 21 25 27 28 28 27 28 27 28 27 0 0] + [ 5 94 1 0 0 0 0 0 0 0 0 0 0] + [ 4 1 94 1 0 0 0 0 0 0 0 0 0] + [ 4 0 1 94 1 0 0 0 0 0 0 0 0] + [ 4 0 0 1 94 1 0 0 0 0 0 0 0] + [ 4 0 0 0 1 94 1 0 0 0 0 0 0] + [ 4 0 0 0 0 1 94 1 0 0 0 0 0] + [ 5 0 0 0 0 0 1 93 1 0 0 0 0] + [ 5 0 0 0 0 1 0 1 93 0 0 0 0] + [ 5 0 0 0 0 0 1 0 1 93 0 0 0] + [ 4 0 0 0 0 0 0 1 0 1 94 0 0] + [ 0 0 0 0 0 0 0 0 0 0 0 60 27] + [ 0 0 0 0 0 0 0 0 0 0 0 4 96]] + trace = 6842 + Accuracy= 0.950 +__________________________________________________ + - results without constraints (using ad3+) + ( predict DONE IN 88.4s) +[[5736 25 28 30 28 27 28 26 27 30 30 0 0] + [ 4 95 1 0 0 0 0 0 0 0 0 0 0] + [ 3 1 94 2 0 0 0 0 0 0 0 0 0] + [ 3 0 1 94 2 0 0 0 0 0 0 0 0] + [ 3 0 0 1 94 2 0 0 0 0 0 0 0] + [ 3 0 0 0 1 94 2 0 0 0 0 0 0] + [ 3 0 1 0 0 1 93 2 0 0 0 0 0] + [ 3 0 0 1 0 0 1 93 2 0 0 0 0] + [ 3 0 0 0 1 1 0 1 93 1 0 0 0] + [ 3 0 0 0 0 1 1 0 1 93 1 0 0] + [ 3 0 0 0 0 0 1 1 0 1 94 0 0] + [ 0 0 0 0 0 0 0 0 0 0 0 59 28] + [ 0 0 0 0 0 0 0 0 0 0 0 3 97]] + trace = 6829 + Accuracy= 0.948 +DONE +== NCELL= 10 +== FIXED_SEED= True +== INFERENCE = ad3 +== N_JOBS = 8 +== SWAP= 0 +== EASY= False +== MAX_ITER= 750 +== MODEL FILE= model.pkl diff --git a/examples/logs/plot_snakes.log b/examples/logs/plot_snakes.log index ab590b97..64e5fc80 100644 --- a/examples/logs/plot_snakes.log +++ b/examples/logs/plot_snakes.log @@ -25,3 +25,45 @@ Test accuracy: 0.996 [ 0 0 1 0 0 0 1 0 98 0 0] [ 0 0 0 1 0 0 0 0 0 99 0] [ 0 0 0 0 1 0 0 0 0 0 99]] + + + ================================================================================= + After fixing prepare_data: + Oct 9 2017 + + edge_features[:len(right), :, 0] = features[right[:, 0]] + edge_features[:len(right), :, 1] = features[right[:, 1]] +#ORIG +# edge_features[len(right):, :, 0] = features[down[:, 0]] +# edge_features[len(right):, :, 1] = features[down[:, 1]] + edge_features[len(right):, :, 2] = features[down[:, 0]] + edge_features[len(right):, :, 3] = features[down[:, 1]] + + + Please be patient. Learning will take 5-20 minutes. +Results using only directional features for edges +Test accuracy: 0.847 +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 99 0 0 1 0 0 0 0 0 0] + [ 0 2 68 3 9 4 6 4 3 1 0] + [ 0 4 11 45 8 14 5 6 0 6 1] + [ 0 1 22 18 31 2 14 4 3 5 0] + [ 0 3 7 38 12 22 5 4 2 7 0] + [ 0 2 19 16 26 8 16 2 9 2 0] + [ 0 6 14 26 10 15 5 12 2 10 0] + [ 0 0 12 15 16 4 16 2 18 4 13] + [ 0 2 5 18 6 8 5 3 2 50 1] + [ 0 1 11 4 13 1 2 0 2 2 64]] +Results using also input features for edges +Test accuracy: 0.999 +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 1 0 99 0 0 0 0 0 0 0] + [ 0 0 1 0 99 0 0 0 0 0 0] + [ 0 0 0 1 0 99 0 0 0 0 0] + [ 0 0 0 0 1 0 99 0 0 0 0] + [ 0 0 0 0 0 1 0 99 0 0 0] + [ 0 0 0 0 0 0 0 0 100 0 0] + [ 0 0 0 0 0 0 0 0 0 100 0] + [ 0 0 0 0 0 0 0 0 0 0 100]] \ No newline at end of file diff --git a/examples/plot_snakes.py b/examples/plot_snakes.py index bc251899..1acd5f9f 100644 --- a/examples/plot_snakes.py +++ b/examples/plot_snakes.py @@ -84,8 +84,12 @@ def prepare_data(X): edge_features = np.zeros((edges.shape[0], features.shape[1], 4)) edge_features[:len(right), :, 0] = features[right[:, 0]] edge_features[:len(right), :, 1] = features[right[:, 1]] - edge_features[len(right):, :, 0] = features[down[:, 0]] - edge_features[len(right):, :, 1] = features[down[:, 1]] +#---ORIGINAL CODE +# edge_features[len(right):, :, 0] = features[down[:, 0]] +# edge_features[len(right):, :, 1] = features[down[:, 1]] + edge_features[len(right):, :, 2] = features[down[:, 0]] + edge_features[len(right):, :, 3] = features[down[:, 1]] +#---END OF FIX edge_features = edge_features.reshape(edges.shape[0], -1) X_directions.append((features, edges, edge_features_directions)) X_edge_features.append((features, edges, edge_features)) @@ -104,8 +108,8 @@ def prepare_data(X): inference = 'qpbo' # first, train on X with directions only: crf = EdgeFeatureGraphCRF(inference_method=inference) - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, - n_jobs=1) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, + n_jobs=1) ssvm.fit(X_train_directions, Y_train_flat) # Evaluate using confusion matrix. @@ -118,12 +122,12 @@ def prepare_data(X): print("Results using only directional features for edges") print("Test accuracy: %.3f" % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) - print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) - - # now, use more informative edge features: - crf = EdgeFeatureGraphCRF(inference_method=inference) - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', - n_jobs=-1) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) + + # now, use more informative edge features: + crf = EdgeFeatureGraphCRF(inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', + n_jobs=-1) ssvm.fit(X_train_edge_features, Y_train_flat) Y_pred2 = ssvm.predict(X_test_edge_features) print("Results using also input features for edges") From 0dd281ad55c5681c4e198edb0878ff2e23755388 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 17 Oct 2017 14:07:23 +0200 Subject: [PATCH 099/155] do not store the model by default --- examples/plot_hidden_short_snakes_typed.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/plot_hidden_short_snakes_typed.py b/examples/plot_hidden_short_snakes_typed.py index b80fe02d..ed209730 100644 --- a/examples/plot_hidden_short_snakes_typed.py +++ b/examples/plot_hidden_short_snakes_typed.py @@ -90,7 +90,7 @@ MAXITER=750 sMODELFILE = None -sMODELFILE = "model.pkl" #we save the model in a file and do not re-trian if the file exists +#sMODELFILE = "model.pkl" #we save the model in a file and do not re-trian if the file exists #============================================================================================== From 4ccb7a74601d3368c0c3391b029f3a9a07c5682b Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 17 Oct 2017 14:47:35 +0200 Subject: [PATCH 100/155] authorship+email --- setup.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 3ecc1255..fdde7eac 100644 --- a/setup.py +++ b/setup.py @@ -19,9 +19,9 @@ 'pystruct.tests.test_utils'], include_package_data=True, description="Structured Learning and Prediction in Python", - author="Andreas Mueller, Jean-Luc Meunier", - author_email="jean-luc.meunier@xrce.xerox.com", - url="https://github.com/jlmeunier/pystruct", + author="Andreas Mueller", + author_email="t3kcit@gmail.com", + url="http://pystruct.github.io", license="BSD 2-clause", use_2to3=True, ext_modules=[Extension("pystruct.models.utils", ["src/utils.c"], From ba7c162c95ec47574385ad01787ed037e7101e45 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 17 Oct 2017 15:24:23 +0200 Subject: [PATCH 101/155] 0.3.6 plot_snakes.py fixed --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index fdde7eac..71ccf060 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ include_dirs = [np.get_include()] setup(name="pystruct", - version="0.3.5", + version="0.3.6", install_requires=["ad3>=2.1.2"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', From 77e144872a5c2f20698451d95c059a3946bd9fd6 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 3 Jan 2018 15:12:17 +0100 Subject: [PATCH 102/155] removed unused code --- pystruct/learners/one_slack_ssvm.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/pystruct/learners/one_slack_ssvm.py b/pystruct/learners/one_slack_ssvm.py index 1dcfe9a2..cbbcb538 100644 --- a/pystruct/learners/one_slack_ssvm.py +++ b/pystruct/learners/one_slack_ssvm.py @@ -309,11 +309,6 @@ def _update_cache(self, X, Y, Y_hat): or self.inference_cache_ is None): self.inference_cache_ = [[] for y in Y_hat] -# def constraint_equal(y_1, y_2): -# if isinstance(y_1, tuple): -# return np.all(y_1[0] == y_2[0]) and np.all(y_1[1] == y_2[1]) -# return np.all(y_1 == y_2) - for sample, x, y, y_hat in zip(self.inference_cache_, X, Y, Y_hat): already_there = [self.constraint_equal(y_hat, cache[2]) for cache in sample] From bfb062b09ca2730881b500a9c9b6a2fdf2db9bf8 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 3 Jan 2018 15:13:11 +0100 Subject: [PATCH 103/155] removed unused code --- pystruct/tests/test_learners/test_crammer_singer_svm.py | 1 - 1 file changed, 1 deletion(-) diff --git a/pystruct/tests/test_learners/test_crammer_singer_svm.py b/pystruct/tests/test_learners/test_crammer_singer_svm.py index 6b2a5d60..141b3c45 100644 --- a/pystruct/tests/test_learners/test_crammer_singer_svm.py +++ b/pystruct/tests/test_learners/test_crammer_singer_svm.py @@ -191,7 +191,6 @@ def test_class_weights_rescale_C(): X, Y = make_blobs(n_samples=210, centers=3, random_state=1, cluster_std=3, shuffle=False) X = np.hstack([X, np.ones((X.shape[0], 1))]) - #X, Y = X[:170], Y[:170] weights = 1. / np.bincount(Y) weights *= len(weights) / np.sum(weights) From 878e6f69d45c786883531f9c22d7dfe96ccdea5f Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 3 Jan 2018 15:29:53 +0100 Subject: [PATCH 104/155] PEP8 almost compliant (I do not want to modify original code) --- pystruct/learners/one_slack_ssvm.py | 31 +++++++++++++++++------------ 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/pystruct/learners/one_slack_ssvm.py b/pystruct/learners/one_slack_ssvm.py index cbbcb538..65dd43da 100644 --- a/pystruct/learners/one_slack_ssvm.py +++ b/pystruct/learners/one_slack_ssvm.py @@ -171,7 +171,7 @@ def _solve_1_slack_qp(self, constraints, n_samples): tmp1 = np.zeros(n_constraints) # positivity constraints: if self.negativity_constraint is None: - #empty constraints + # empty constraints zero_constr = np.zeros(0) joint_features_constr = np.zeros((0, n_constraints)) else: @@ -280,27 +280,32 @@ def _check_bad_constraint(self, violation, djoint_feature_mean, loss, @classmethod def constraint_equal(cls, y_1, y_2): """ - This now more complex. y_1 and/or y_2 (I think) can be: array, pair of arrays, pair of list of arrays (multitype) - We need to compare those! + This now more complex. y_1 and/or y_2 (I think) can be: array, pair of + arrays, pair of list of arrays (multitype) + We need to compare those! """ if isinstance(y_1, tuple): - #y_1 is relaxed Y - #y_1 and y_2 might be lists of ndarray (multitype) instead of ndarray (single type) + # y_1 is relaxed Y + # y_1 and y_2 might be lists of ndarray (multitype) instead of + # ndarray (single type) u_m_1, pw_m_1 = y_1 - if isinstance(y_2, tuple): #we then compare two relaxed Ys + if isinstance(y_2, tuple): # we then compare two relaxed Ys u_m_2, pw_m_2 = y_2 - #now, do we multitype or single type relaxed marginals?? + # now, do we multitype or single type relaxed marginals?? if isinstance(u_m_1, list): - return all( np.all(_um1 == _um2) for _um1, _um2 in zip( u_m_1, u_m_2) ) \ - and all( np.all(_pw1 == _pw2) for _pw1, _pw2 in zip(pw_m_1, pw_m_2)) + return all(np.all(_um1 == _um2) for _um1, _um2 + in zip( u_m_1, u_m_2)) \ + and all(np.all(_pw1 == _pw2) for _pw1, _pw2 + in zip(pw_m_1, pw_m_2)) else: return np.all(u_m_1 == u_m_2) and np.all(pw_m_1, pw_m_2) else: - #NOTE original code was possibly comparing array and scalar - #return np.all(y_1[0] == y_2[0]) and np.all(y_1[1] == y_2[1]) + # NOTE original code was possibly comparing array and scalar + # return np.all(y_1[0] == y_2[0]) and np.all(y_1[1] == y_2[1]) return False - return np.all(y_1 == y_2) #might compare array and tuple... :-/ Was like that, Ikeep - + # might compare array and tuple... :-/ Was like that, I keep + return np.all(y_1 == y_2) + def _update_cache(self, X, Y, Y_hat): """Updated cached constraints.""" if self.inference_cache == 0: From 7e3a1fef82c8d3610d6edd86de8a126cf882a9bc Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 3 Jan 2018 16:15:51 +0100 Subject: [PATCH 105/155] PEP8 --- .../node_type_edge_feature_graph_crf.py | 418 +++++++++++------- 1 file changed, 249 insertions(+), 169 deletions(-) diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index 09380900..b842425a 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -1,32 +1,33 @@ # -*- coding: utf-8 -*- """ - Pairwise CRF with features/strength associated to each edge and different types of nodes - - Copyright Xerox(C) 2017 JL. Meunier - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - - Developed for the EU project READ. The READ project has received funding - from the European Union's Horizon 2020 research and innovation programme + Pairwise CRF with features/strength associated to each edge and different + types of nodes + + JL. Meunier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. - + """ import numpy as np import random @@ -39,7 +40,8 @@ class NodeTypeEdgeFeatureGraphCRF(TypedCRF): """ - Pairwise CRF with features/strength associated to each edge and different types of nodes + Pairwise CRF with features/strength associated to each edge and different + types of nodes Pairwise potentials are asymmetric and shared over all edges of same type. They are weighted by an edge-specific features, though. @@ -52,85 +54,114 @@ class NodeTypeEdgeFeatureGraphCRF(TypedCRF): Parameters ---------- n_types : number of node types - + l_n_states : list of int, default=None - Number of states per type of variables. + Number of states per type of variables. l_n_features : list of int, default=None - Number of features per type of node. + Number of features per type of node. + + a_n_edge_features: an array of shape (n_types, n_types) giving the number + of features per pair of types + + NOTE: there should always be at least 1 feature for any pairs of types + which has some edge in the graph. + To mimic GraphCRF, pass 1 and make a constant feature of 1.0 for all + those edges. - a_n_edge_features: an array of shape (n_types, n_types) giving the number of features per pair of types - - NOTE: there should always be at least 1 feature for any pairs of types which has some edge in the graph. - To mimic GraphCRF, pass 1 and make a constant feature of 1.0 for all those edges. - class_weight : None, or list of array-like (ndim=1) - Class weights. If a list of array-like is passed, the Ith one must have length equal to l_n_states[i] + Class weights. If a list of array-like is passed, the Ith one must have + length equal to l_n_states[i] None means equal class weights (across node types) X and Y ------- - Node features are given as a list of n_types arrays of shape (n_type_nodes, n_type_features): + Node features are given as a list of n_types arrays of shape + (n_type_nodes, n_type_features): - n_type_nodes is the number of nodes of that type - n_type_features is the number of features for this type of node - - Edges are given as a list of n_types x n_types arrays of shape (n_type_edges, 2). - Columns are resp.: node index (in corresponding node type), node index (in corresponding node type) - - Edge features are given as a list of n_types x n_types arrays of shape (n_type_type_edge, n_type_type_edge_features) + + Edges are given as a list of n_types x n_types arrays of shape + (n_type_edges, 2). + Columns are resp.: node index (in corresponding node type), node index + (in corresponding node type) + + Edge features are given as a list of n_types x n_types arrays of shape + (n_type_type_edge, n_type_type_edge_features) - n_type_type_edge is the number of edges of type type_type - - n_type_type_edge_features is the number of features for edge of type type_type - - An instance ``X`` is represented as a tuple ``([node_features, ..], [edges, ..], [edge_features, ..])`` + - n_type_type_edge_features is the number of features for edge of type + type_type + + An instance ``X`` is represented as a tuple ``([node_features, ..] + , [edges, ..], [edge_features, ..])`` - Labels ``Y`` are given as one array of shape (n_nodes) - Labels are numbered from 0 so that each label across types is encoded by a unique integer. - - Look at flattenY and unflattentY if you want to pass/obtain list of labels per type, with first label of each type being encoded by 0 + Labels ``Y`` are given as one array of shape (n_nodes) + Labels are numbered from 0 so that each label across types is encoded + by a unique integer. + + Look at flattenY and unflattentY if you want to pass/obtain list of + labels per type, with first label of each type being encoded by 0 """ - def __init__(self - , n_types #how many node type? - , l_n_states #how many labels per node type? - , l_n_features #how many features per node type? - , a_n_edge_features #how many features per edge type? - , inference_method="ad3" - , l_class_weight=None): #class_weight per node type or None or None - - #internal stuff - #how many features per node type X node type? (MUST be symmetric!) + def __init__(self, + n_types, # how many node type? + l_n_states, # how many labels per node type? + l_n_features, # how many features per node type? + a_n_edge_features, # how many features per edge type? + inference_method="ad3", + l_class_weight=None): # class_weight per node type or None + # or None + + # how many features per node type X node type? + # (MUST be symmetric!) self.a_n_edge_features = np.array(a_n_edge_features) - if self.a_n_edge_features.shape != (n_types, n_types): - raise ValueError("Expected a feature number matrix for edges of shape (%d, %d), got %s."%(n_types, n_types, self.a_n_edge_features.shape)) - self.a_n_edge_features = self.a_n_edge_features.reshape(n_types, n_types) + if self.a_n_edge_features.shape != (n_types, n_types): + raise ValueError("Expected a feature number matrix for edges of " + "shape (%d, %d), got " + "%s." % (n_types, n_types, + self.a_n_edge_features.shape)) + self.a_n_edge_features = self.a_n_edge_features.reshape(n_types, + n_types) if not (self.a_n_edge_features == self.a_n_edge_features.T).all(): - raise ValueError("Expected a symmetric array of edge feature numbers") - - self.l_n_edge_features = self.a_n_edge_features.ravel() #number of (edge) features per edge type - self._n_edge_features = self.a_n_edge_features.sum(axis=None) #total number of (edge) features + raise ValueError("Expected a symmetric array of edge feature " + "numbers") + + # number of (edge) features per edge type + self.l_n_edge_features = self.a_n_edge_features.ravel() + # total number of (edge) features + self._n_edge_features = self.a_n_edge_features.sum(axis=None) + + TypedCRF.__init__(self, n_types, l_n_states, l_n_features, + inference_method=inference_method, + l_class_weight=l_class_weight) - TypedCRF.__init__(self, n_types, l_n_states, l_n_features, inference_method=inference_method, l_class_weight=l_class_weight) - self._get_pairwise_potentials_initialize() def _set_size_joint_feature(self): """ We have: - 1 weight per node feature per label per node type - - 1 weight per edge feature per label of node1 type, per label of node2 type - - NOTE: for now, a typ1, typ2 type of edge with 0 features is simply ignored. While it could get a state x state matrix of weights + - 1 weight per edge feature per label of node1 type, per label of node2 + type + + NOTE: for now, a typ1, typ2 type of edge with 0 features is simply + ignored. While it could get a state x state matrix of weights """ if self.l_n_features: - self.size_unaries = sum( n_states * n_features for n_states, n_features in zip(self.l_n_states, self.l_n_features) ) - - self.size_pairwise = 0 #detailed non-optimized computation to make things clear - for typ1,typ2 in self._iter_type_pairs(): - self.size_pairwise += self.a_n_edge_features[typ1,typ2] * self.l_n_states[typ1] * self.l_n_states[typ2] + self.size_unaries = sum(n_states * n_features for n_states, + n_features in zip(self.l_n_states, + self.l_n_features)) + + # detailed non-optimized computation to make things clear + self.size_pairwise = 0 + for typ1, typ2 in self._iter_type_pairs(): + self.size_pairwise += self.a_n_edge_features[typ1, typ2]\ + * self.l_n_states[typ1]\ + * self.l_n_states[typ2] self.size_joint_feature = self.size_unaries + self.size_pairwise - + def __repr__(self): return ("%s(n_states: %s, inference_method: %s, n_features: %s, " "n_edge_features: %s)" @@ -140,64 +171,84 @@ def __repr__(self): def _check_size_x(self, x): l_edges = self._get_edges(x) if len(l_edges) != self.n_types**2: - raise ValueError("Expected %d edge arrays or None"%(self.n_types**2)) - l_edge_features = self._get_edge_features(x) + raise ValueError("Expected %d edge arrays " + "or None" % (self.n_types**2)) + l_edge_features = self._get_edge_features(x) if len(l_edge_features) != self.n_types**2: - raise ValueError("Expected %d edge feature arrays or None"%(self.n_types**2)) + raise ValueError("Expected %d edge feature arrays " + "or None" % (self.n_types**2)) TypedCRF._check_size_x(self, x) - - #check that we have in total 1 feature vector per edge + + # check that we have in total 1 feature vector per edge for edges, edge_features in zip(l_edges, l_edge_features): - if edges is None or edge_features is None: - if edges is None and edge_features is None: continue + if edges is None or edge_features is None: + if edges is None and edge_features is None: + continue if edges is None: - raise ValueError("Empty edge array but non empty edge-feature array, for same type of edge") + raise ValueError("Empty edge array but non empty " + "edge-feature array, for same type of " + "edge") else: - raise ValueError("Empty edge-feature array but non empty edge array, for same type of edge") + raise ValueError("Empty edge-feature array but non empty " + "edge array, for same type of edge") if edge_features.ndim != 2: raise ValueError("Expected a 2 dimensions edge feature arrays") if len(edges) != len(edge_features): - raise ValueError("Edge and edge feature matrices must have same size in 1st dimension") - - #check edge feature size - for typ1,typ2 in self._iter_type_pairs(): - edge_features = l_edge_features[typ1*self.n_types+typ2] - if edge_features is None: continue - if edge_features.shape[1] != self.a_n_edge_features[typ1,typ2]: - raise ValueError("Types %d x %d: bad number of edge features. expected %d got %d"%(typ1,typ2, self.a_n_edge_features[typ1,typ2], edge_features.shape[1])) + raise ValueError("Edge and edge feature matrices must have " + "same size in 1st dimension") + + # check edge feature size + for typ1, typ2 in self._iter_type_pairs(): + edge_features = l_edge_features[typ1*self.n_types+typ2] + if edge_features is None: + continue + if edge_features.shape[1] != self.a_n_edge_features[typ1, typ2]: + raise ValueError("Types %d x %d: bad number of edge features. " + "expected %d " + "got %d" % (typ1, typ2, + self.a_n_edge_features[typ1, + typ2], + edge_features.shape[1])) return True def _get_edge_features(self, x): - #we replace None by empty array with proper shape - return [ np.empty((0,_n_feat)) if _ef is None else _ef + # we replace None by empty array with proper shape + return [np.empty((0, _n_feat)) + if _ef is None + else _ef for _ef, _n_feat in zip(x[2], self.l_n_edge_features)] def _get_pairwise_potentials_initialize(self): """ - Putting in cache the params required to build the pairwise potentials given x and w + Putting in cache the params required to build the pairwise potentials + given x and w """ self._cache_pairwise_potentials = list() i_w, n_states1, i_states1 = 0, 0, 0 for typ1 in xrange(self.n_types): - n_states1 = self.l_n_states[typ1] - i_states1_stop = i_states1 + n_states1 + n_states1 = self.l_n_states[typ1] + i_states1_stop = i_states1 + n_states1 n_states2, i_states2 = 0, 0 for typ2 in xrange(self.n_types): - n_features = self.a_n_edge_features[typ1, typ2] - n_states2 = self.l_n_states[typ2] - i_w_stop = i_w + n_features * n_states1 * n_states2 - i_states2_stop = i_states2 + n_states2 - - self._cache_pairwise_potentials.append( (n_features - , n_states1, n_states2, i_states1, i_states1_stop, i_states2, i_states2_stop - , i_w, i_w_stop) ) - - i_w, i_states2 = i_w_stop, i_states2_stop + n_features = self.a_n_edge_features[typ1, typ2] + n_states2 = self.l_n_states[typ2] + i_w_stop = i_w + n_features * n_states1 * n_states2 + i_states2_stop = i_states2 + n_states2 + + self._cache_pairwise_potentials.append((n_features, + n_states1, n_states2, + i_states1, + i_states1_stop, + i_states2, + i_states2_stop, + i_w, i_w_stop)) + + i_w, i_states2 = i_w_stop, i_states2_stop i_states1 = i_states1_stop - + def _get_pairwise_potentials(self, x, w): """Computes pairwise potentials for x and w. @@ -211,36 +262,46 @@ def _get_pairwise_potentials(self, x, w): Returns ------- - pairwise : list of ndarray, shape=(n_edges, n_states_typ1, n_states_typ2) - Pairwise weights. + pairwise: list of pairwise weights of shape: + (n_edges, n_states_typA, n_states_typB) + """ self._check_size_w(w) - - l_edge_features = self._get_edge_features(x) + + l_edge_features = self._get_edge_features(x) wpw = w[self.size_unaries:] l_pairwise_potentials = [] - + i_w = 0 - for (typ1, typ2), edge_features in zip(self._iter_type_pairs(), l_edge_features): + for (typ1, typ2), edge_features in zip(self._iter_type_pairs(), + l_edge_features): n_edges, n_features = edge_features.shape n_states1 = self.l_n_states[typ1] n_states2 = self.l_n_states[typ2] n_w = n_features * n_states1 * n_states2 if n_w: - pw_typ_typ = wpw[i_w:i_w + n_w].reshape(n_features, -1) # n_states1*n_states2 x nb_feat - l_pairwise_potentials.append( np.dot(edge_features, pw_typ_typ).reshape(n_edges, n_states1, n_states2) ) + # n_states1*n_states2 x nb_feat + pw_typ_typ = wpw[i_w:i_w + n_w].reshape(n_features, -1) + l_pairwise_potentials.append(np.dot(edge_features, + pw_typ_typ + ).reshape(n_edges, + n_states1, + n_states2)) else: - l_pairwise_potentials.append( np.array([]) ) #first reshaping above complains: "ValueError: total size of new array must be unchanged" + # first reshaping above complains: "ValueError: total size of + # new array must be unchanged" + l_pairwise_potentials.append(np.array([])) i_w += n_w - + return l_pairwise_potentials - + def joint_feature(self, x, y): """Feature vector associated with instance (x, y). - Feature representation joint_feature, such that the energy of the configuration - (x, y) and a weight vector w is given by np.dot(w, joint_feature(x, y)). + Feature representation joint_feature, such that the energy of the + configuration + (x, y) and a weight vector w is given by np.dot(w,joint_feature(x, y)). Parameters ---------- @@ -248,7 +309,8 @@ def joint_feature(self, x, y): Input representation. y : list of ndarrays or some tuple (internal use!) - Either y is a list of a integral ndarrays, giving a complete labeling for x. + Either y is a list of a integral ndarrays, giving a complete + labeling for x. Or it is the result of a linear programming relaxation. In this case, ``y=(unary_marginals, pariwise_marginals)``. @@ -258,89 +320,107 @@ def joint_feature(self, x, y): Feature vector associated with state (x, y). """ - self._check_size_x(x) #call initialize once! + self._check_size_x(x) # call initialize once! l_node_features = self._get_node_features(x) - l_edges, l_edge_features = self._get_edges(x), self._get_edge_features(x) + l_edges, l_edge_features = (self._get_edges(x), + self._get_edge_features(x)) l_n_nodes = [len(nf) for nf in self._get_node_features(x)] - l_n_edges = [len(ef) for ef in self._get_edges (x)] - n_nodes = sum(l_n_nodes) - n_edges = sum(l_n_edges) + l_n_edges = [len(ef) for ef in self._get_edges(x)] if isinstance(y, tuple): # y is result of relaxation, tuple of unary and pairwise marginals unary_marginals, pw = y - + if isinstance(unary_marginals, list): - #ad3+ returns a list of unaries, nothing to do here!! :) + # ad3+ returns a list of unaries, nothing to do here!! :) l_unary_marginals = unary_marginals else: - #in case we use someother method (not supported for now actually) + # in case we use someother method (not supported for now + # actually) l_unary_marginals = [] - i,j = 0,0 - for (_n_nodes, _n_states) in zip(l_n_nodes, self.l_n_states): #iteration by type + i, j = 0, 0 + # iteration by type + for (_n_nodes, _n_states) in zip(l_n_nodes, self.l_n_states): _n_binaries = _n_nodes * _n_states - _unary_marginals = unary_marginals[ i:i+_n_nodes , j:j+_n_states ] + _unary_marginals = unary_marginals[i:i+_n_nodes, + j:j+_n_states] i += _n_nodes j += _n_states l_unary_marginals.append(_unary_marginals) - + if isinstance(pw, list): - #ad3+ returns a list of pairwise + # ad3+ returns a list of pairwise l_pw = pw else: - #until we do better in ad3+ inference, but we cannot I think without touching the learners... + # until we do better in ad3+ inference, but we cannot I think + # without touching the learners... l_pw = [] i_start = 0 - for _n_edges, (typ1, typ2) in zip(l_n_edges, self._iter_type_pairs()): + for _n_edges, (typ1, typ2) in zip(l_n_edges, + self._iter_type_pairs()): n = self.l_n_states[typ1] * self.l_n_states[typ2] i_stop = i_start + _n_edges - i_state_start = self.a_startindex_by_typ_typ[typ1,typ2] - _edge_marginals = pw[i_start:i_stop, i_state_start:i_state_start+n] + i_state_start = self.a_startindex_by_typ_typ[typ1, typ2] + _edge_marginals = pw[i_start:i_stop, + i_state_start:i_state_start+n] i_start = i_stop l_pw.append(_edge_marginals) else: self._check_size_xy(x, y) - #make one hot encoding per type + # make one hot encoding per type l_unary_marginals = [] i_start = 0 - #PBY for _n_nodes, _n_states in zip(l_n_nodes, self.l_n_states): - for _n_nodes, _n_states, typ_start_index in zip(l_n_nodes, self.l_n_states, self._l_type_startindex): + for (_n_nodes, + _n_states, + typ_start_index) in zip(l_n_nodes, + self.l_n_states, + self._l_type_startindex): i_stop = i_start + _n_nodes - _unary_marginals = np.zeros((_n_nodes, _n_states), dtype=np.int) + _unary_marginals = np.zeros((_n_nodes, _n_states), + dtype=np.int) gx = np.ogrid[:_n_nodes] _unary_marginals[gx, y[i_start:i_stop]-typ_start_index] = 1 l_unary_marginals.append(_unary_marginals) i_start = i_stop - - ## pairwise - #same thing, but the type of an edge is a pair of node types + + # pairwise + # same thing, but the type of an edge is a pair of node types l_pw = [] - node_offset_by_typ = np.cumsum([0]+[0 if n is None else n.shape[0] for n in x[0]]) - for _n_edges, (typ1, typ2), edges in zip(l_n_edges, self._iter_type_pairs(), l_edges): + node_offset_by_typ = np.cumsum([0]+[0 if n is None + else n.shape[0] for n in x[0]]) + for _n_edges, (typ1, typ2), edges in zip(l_n_edges, + self._iter_type_pairs(), + l_edges): _n_states_typ1 = self.l_n_states[typ1] _n_states_typ2 = self.l_n_states[typ2] _pw = np.zeros((_n_edges, _n_states_typ1 * _n_states_typ2)) if _n_edges: - y1 = y[node_offset_by_typ[typ1] + edges[:,0]] - self._l_type_startindex[typ1] - y2 = y[node_offset_by_typ[typ2] + edges[:,1]] - self._l_type_startindex[typ2] - assert (0<=y1).all() and (y1 <= self.l_n_states[typ1]).all() - assert (0<=y2).all() and (y2 <= self.l_n_states[typ2]).all() - #set the 1s where they should + y1 = y[node_offset_by_typ[typ1] + edges[:, 0]]\ + - self._l_type_startindex[typ1] + y2 = y[node_offset_by_typ[typ2] + edges[:, 1]]\ + - self._l_type_startindex[typ2] + assert (0 <= y1).all() and (y1 <= + self.l_n_states[typ1]).all() + assert (0 <= y2).all() and (y2 <= + self.l_n_states[typ2]).all() + # set the 1s where they should class_pair_ind = (y2 + _n_states_typ2 * y1) _pw[np.arange(_n_edges), class_pair_ind] = 1 - l_pw.append(_pw) - - #UNARY - l_unary_acc_ravelled = [np.dot(unary_marginals.T, features).ravel() for (unary_marginals, features) in zip(l_unary_marginals, l_node_features)] + l_pw.append(_pw) + + # UNARY + l_unary_acc_ravelled = [np.dot(unary_marginals.T, features).ravel() + for (unary_marginals, features) + in zip(l_unary_marginals, l_node_features)] unaries_acc_ravelled = np.hstack(l_unary_acc_ravelled) - - #PW - l_pw_ravelled = [np.dot(ef.T, pw).ravel() for (ef, pw) in zip(l_edge_features, l_pw)] + + # PW + l_pw_ravelled = [np.dot(ef.T, pw).ravel() for (ef, pw) + in zip(l_edge_features, l_pw)] pairwise_acc_ravelled = np.hstack(l_pw_ravelled) - - joint_feature_vector = np.hstack([unaries_acc_ravelled, pairwise_acc_ravelled]) - - #assert joint_feature_vector.shape[0] == self.size_joint_feature, (joint_feature_vector.shape[0], self.size_joint_feature) + + joint_feature_vector = np.hstack([unaries_acc_ravelled, + pairwise_acc_ravelled]) return joint_feature_vector @@ -351,10 +431,10 @@ def loss_augment_unaries(self, l_unary_potentials, y): i_start = 0 a_y = np.asarray(y) - for typ, (unary_potentials, class_weight) in enumerate(zip(l_unary_potentials, self.l_class_weight)): + for typ, (unary_potentials, class_weight) in enumerate( + zip(l_unary_potentials, self.l_class_weight)): n_y = unary_potentials.shape[0] - y_typ = a_y[i_start:i_start+n_y] - self._l_type_startindex[typ] #label 0 must correspond to 1st weight + # label 0 must correspond to 1st weight + y_typ = a_y[i_start:i_start+n_y] - self._l_type_startindex[typ] loss_augment_unaries(unary_potentials, y_typ, class_weight) i_start += n_y - - From b496b0ae549c9860078daff9f2cf42900e528bc0 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 3 Jan 2018 16:41:08 +0100 Subject: [PATCH 106/155] PEP8 --- pystruct/models/base.py | 7 +- pystruct/models/crf.py | 31 ++-- pystruct/models/typed_crf.py | 293 ++++++++++++++++++++--------------- 3 files changed, 189 insertions(+), 142 deletions(-) diff --git a/pystruct/models/base.py b/pystruct/models/base.py index 76483bec..8e3fa44a 100644 --- a/pystruct/models/base.py +++ b/pystruct/models/base.py @@ -13,8 +13,8 @@ def __repr__(self): def __init__(self): """Initialize the model. - Needs to set self.size_joint_feature, the dimensionalty of the joint features for - an instance with labeling (x, y). + Needs to set self.size_joint_feature, the dimensionality of the joint + features for an instance with labeling (x, y). """ self.size_joint_feature = None @@ -52,7 +52,8 @@ def inference(self, x, w, relaxed=None, constraints=None): def batch_inference(self, X, w, relaxed=None, constraints=None): # default implementation of batch inference if constraints: - return [self.inference(x, w, relaxed=relaxed, constraints=c) for x,c in zip(X, constraints)] + return [self.inference(x, w, relaxed=relaxed, constraints=c) + for x, c in zip(X, constraints)] return [self.inference(x, w, relaxed=relaxed) for x in X] diff --git a/pystruct/models/crf.py b/pystruct/models/crf.py index 855bdf93..ba466829 100644 --- a/pystruct/models/crf.py +++ b/pystruct/models/crf.py @@ -56,8 +56,8 @@ def loss_augment_unaries(self, unary_potentials, y): """ we define it as a method so that subclasses can specialize it. """ - loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) - + loss_augment_unaries(unary_potentials, np.asarray(y), + self.class_weight) def loss_augmented_inference(self, x, y, w, relaxed=False, return_energy=False): @@ -110,15 +110,15 @@ def loss_augmented_inference(self, x, y, w, relaxed=False, unary_potentials = self._get_unary_potentials(x, w) pairwise_potentials = self._get_pairwise_potentials(x, w) edges = self._get_edges(x) - - #loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) + self.loss_augment_unaries(unary_potentials, y) - + return inference_dispatch(unary_potentials, pairwise_potentials, edges, self.inference_method, relaxed=relaxed, return_energy=return_energy) - def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): + def inference(self, x, w, relaxed=False, return_energy=False, + constraints=None): """Inference for x using parameters w. Finds (approximately) @@ -148,7 +148,7 @@ def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): constraints : None or list, default=False hard logic constraints, if any - + Returns ------- y_pred : ndarray or tuple @@ -169,10 +169,15 @@ def inference(self, x, w, relaxed=False, return_energy=False, constraints=None): edges = self._get_edges(x) if constraints: - return inference_dispatch(unary_potentials, pairwise_potentials, edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy, constraints=constraints) + return inference_dispatch(unary_potentials, pairwise_potentials, + edges, + self.inference_method, + relaxed=relaxed, + return_energy=return_energy, + constraints=constraints) else: - return inference_dispatch(unary_potentials, pairwise_potentials, edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy) \ No newline at end of file + return inference_dispatch(unary_potentials, pairwise_potentials, + edges, + self.inference_method, + relaxed=relaxed, + return_energy=return_energy) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index fc217228..5c3e87ce 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -2,33 +2,33 @@ """ CRF with different types of nodes - + NOTE: this is an abstract class. Do not use directly. - Copyright Xerox(C) 2017 JL. Meunier - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. - - Developed for the EU project READ. The READ project has received funding - from the European Union's Horizon 2020 research and innovation programme + JL. Meunier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. - + """ import numpy as np @@ -39,64 +39,76 @@ class InconsistentLabel(Exception): pass + class TypedCRF(CRF): """Abstract base class""" - def __init__(self - , n_types #how many node type? - , l_n_states #how many labels per node type? - , l_n_features #how many features per node type? - , inference_method="ad3" - , l_class_weight=None): #class_weight per node type or None or None - + def __init__(self, + n_types, # how many node type? + l_n_states, # how many labels per node type? + l_n_features, # how many features per node type? + inference_method="ad3", + l_class_weight=None): # class_weight per node type or None + # or None + if inference_method is None: # get first in list that is installed inference_method = get_installed(['ad3+', 'ad3'])[0] self.setInferenceMethod(inference_method) - + self.inference_calls = 0 - self.inference_exception = False #if inference cannot be done, raises an exception - - if len(l_n_states) != n_types: + # if inference cannot be done, raises an exception + self.inference_exception = False + + if len(l_n_states) != n_types: raise ValueError("Expected 1 number of states per node type.") - if l_n_features != None and len(l_n_features) != n_types: + if l_n_features is not None and len(l_n_features) != n_types: raise ValueError("Expected 1 number pf features per node type.") - self.n_types = n_types - self.l_n_states = l_n_states - self._n_states = sum(l_n_states) #total number of states + self.n_types = n_types + self.l_n_states = l_n_states + self._n_states = sum(l_n_states) # total number of states self.l_n_features = l_n_features - self._n_features = sum(self.l_n_features) #total number of (node) features + self._n_features = sum(self.l_n_features) # total number of node feat. - #number of typextype states, or number of states per type of edge - self.l_n_edge_states = [ n1 * n2 for n1 in self.l_n_states for n2 in self.l_n_states ] + # number of typextype states, or number of states per type of edge + self.l_n_edge_states = [n1 * n2 + for n1 in self.l_n_states + for n2 in self.l_n_states] - #class weights: - # either we get class weights for all types of nodes, or for none of them! + # class weights: + # either we get class weights for all types of nodes + # , or for none of them! if l_class_weight: if len(l_class_weight) != self.n_types: raise ValueError("Expected 1 class weight list per node type.") for i, n_states in enumerate(self.l_n_states): if len(l_class_weight[i]) != n_states: - raise ValueError("Expected 1 class weight per state per node type. Wrong for type %d"%i) - - #class weights are computed by type and simply concatenated - self.l_class_weight = [np.asarray(class_weight) for class_weight in l_class_weight] + raise ValueError("Expected 1 class weight per state" + " per node type. Wrong for type %d" % i) + + # class weights are computed by type and simply concatenated + self.l_class_weight = [np.asarray(class_weight) + for class_weight in l_class_weight] else: self.l_class_weight = [np.ones(n) for n in self.l_n_states] self.class_weight = np.hstack(self.l_class_weight) self._set_size_joint_feature() - #internal stuff - #when putting node states in a single sequence, index of 1st state for type i - self._l_type_startindex = [ sum(self.l_n_states[:i]) for i in range(self.n_types+1)] - - #when putting edge states in a single sequence, index of 1st state of an edge of type (typ1, typ2) - self.a_startindex_by_typ_typ = np.zeros((self.n_types, self.n_types), dtype=np.uint32) + # internal stuff + # when putting node states in a single sequence, index of 1st state + # for type i + self._l_type_startindex = [sum(self.l_n_states[:i]) + for i in range(self.n_types+1)] + + # when putting edge states in a single sequence, index of 1st state of + # an edge of type (typ1, typ2) + self.a_startindex_by_typ_typ = np.zeros((self.n_types, self.n_types), + dtype=np.uint32) i_state_start = 0 for typ1, typ1_n_states in enumerate(self.l_n_states): for typ2, typ2_n_states in enumerate(self.l_n_states): - self.a_startindex_by_typ_typ[typ1,typ2] = i_state_start - i_state_start += typ1_n_states*typ2_n_states + self.a_startindex_by_typ_typ[typ1, typ2] = i_state_start + i_state_start += typ1_n_states*typ2_n_states # -------------- CONVENIENCE -------------------------- def setInferenceMethod(self, inference_method): @@ -104,60 +116,68 @@ def setInferenceMethod(self, inference_method): self.inference_method = inference_method else: raise Exception("You must use ad3 or ad3+ as inference method") - + def flattenY(self, lY_by_typ): """ - It is more convenient to have the Ys grouped by type, as the Xs are, and to have the first label of each type encoded as 0. - - This method does the job. It returns a flat Y array, with unique code per class label, which can be passed to 'fit' + It is more convenient to have the Ys grouped by type, as the Xs are, + and to have the first label of each type encoded as 0. + + This method does the job. It returns a flat Y array, with unique code + per class label, which can be passed to 'fit' """ lY = list() for n_start_state, Y_typ in zip(self._l_type_startindex, lY_by_typ): - lY.append( np.asarray(Y_typ) + n_start_state ) + lY.append(np.asarray(Y_typ) + n_start_state) return np.hstack(lY) - + def unflattenY(self, X, flatY): """ predict returns a flat array of Y (same structure as for 'fit') - This method structures the Y as a list of Y_per_type, where the first label of any type is 0 + This method structures the Y as a list of Y_per_type, where the first + label of any type is 0 """ lY = list() i_start_node = 0 (l_node_features, l_edges, l_edge_features) = X for n_start_state, nf in zip(self._l_type_startindex, l_node_features): n_nodes = nf.shape[0] - Y = flatY[i_start_node : i_start_node+n_nodes] - n_start_state + Y = flatY[i_start_node: i_start_node+n_nodes] - n_start_state lY.append(Y) i_start_node += n_nodes - if flatY.shape != (i_start_node,): - raise ValueError("The total number of label does not match the total number of nodes: %d != %d"%(flatY.shape[0], i_start_node)) + if flatY.shape != (i_start_node,): + raise ValueError("The total number of label does not match the" + " total number of nodes:" + " %d != %d" % (flatY.shape[0], i_start_node)) return lY - + def initialize(self, X, Y=None): """ It is optional to call it. Does data checking only! """ if isinstance(X, list): map(self._check_size_x, X) - if not (Y is None): map(self._check_size_xy, X, Y) + if not (Y is None): + map(self._check_size_xy, X, Y) else: self._check_size_x(X) self._check_size_xy(X, Y) - + def setInferenceException(self, bRaiseExceptionWhenInferenceNotSuccessful): """ set exception on or off when inference canoot be done. """ self.inference_exception = bRaiseExceptionWhenInferenceNotSuccessful return self.inference_exception - + # -------------- INTERNAL STUFF -------------------------- def _set_size_joint_feature(self): """ We have: - 1 weight per node feature per label per node type """ - self.size_unaries = sum( n_states * n_features for n_states, n_features in zip(self.l_n_states, self.l_n_features) ) + self.size_unaries = sum(n_states * n_features for n_states, n_features + in zip(self.l_n_states, self.l_n_features) + ) self.size_joint_feature = self.size_unaries def __repr__(self): @@ -166,71 +186,93 @@ def __repr__(self): self.inference_method)) def _check_size_x(self, x): - #node_features are [ i_in_typ -> features ] + # node_features are [ i_in_typ -> features ] l_node_features = self._get_node_features(x) if len(l_node_features) != self.n_types: raise ValueError("Expected one node feature array per node type.") - + for typ, typ_features in enumerate(l_node_features): if typ_features.shape[1] != self.l_n_features[typ]: - raise ValueError("Expected %d features for type %d"%(self.l_n_features[typ], typ)) + raise ValueError("Expected %d features for type" + " %d" % (self.l_n_features[typ], typ)) - #edges + # edges l_edges = self._get_edges(x) for edges in l_edges: - if edges is None: continue + if edges is None: + continue if edges.ndim != 2: raise ValueError("Expected a 2 dimensions edge arrays") if edges.shape[1] != 2: raise ValueError("Expected 2 columns in edge arrays") - for typ1,typ2 in self._iter_type_pairs(): - edges = self._get_edges_by_type(x, typ1, typ2) - - if edges is None or len(edges) == 0: continue - #edges should point to valid node indices - nodes1, nodes2 = edges[:,0], edges[:,1] + for typ1, typ2 in self._iter_type_pairs(): + edges = self._get_edges_by_type(x, typ1, typ2) + + if edges is None or len(edges) == 0: + continue + # edges should point to valid node indices + nodes1, nodes2 = edges[:, 0], edges[:, 1] if min(nodes1) < 0 or min(nodes2) < 0: - raise ValueError("At least one edge points to negative and therefore invalid node index: type %d to type %d"%(typ1,typ2)) + raise ValueError("At least one edge points to negative and" + " therefore invalid node index:" + " type %d to type %d" % (typ1, typ2)) if max(nodes1) >= l_node_features[typ1].shape[0]: - raise ValueError("At least one edge starts from a non-existing node index: type %d to type %d"%(typ1,typ2)) + raise ValueError("At least one edge starts from a non-existing" + " node index:" + " type %d to type %d" % (typ1, typ2)) if max(nodes2) >= l_node_features[typ2].shape[0]: - raise ValueError("At least one edge points to a non-existing node index: type %d to type %d"%(typ1,typ2)) + raise ValueError("At least one edge points to a non-existing" + " node index:" + " type %d to type %d" % (typ1, typ2)) return True - + def _check_size_xy(self, X, Y): - if Y is None: return - - #make sure Y has the proper length and acceptable labels + if Y is None: + return + + # make sure Y has the proper length and acceptable labels l_node_features = self._get_node_features(X) - + nb_nodes = sum(nf.shape[0] for nf in l_node_features) if Y.shape[0] != nb_nodes: - raise ValueError("Expected 1 label for each of the %d nodes. Gopt %d labels."%(nb_nodes, Y.shape[0])) - - i_start = 0 - for typ, nf, n_states in zip(range(self.n_types), l_node_features, self.l_n_states): + raise ValueError("Expected 1 label for each of the %d nodes. Got" + " %d labels." % (nb_nodes, Y.shape[0])) + + i_start = 0 + for typ, nf, n_states in zip(range(self.n_types), + l_node_features, + self.l_n_states): nb_nodes = nf.shape[0] - if nb_nodes == 0: continue + if nb_nodes == 0: + continue Y_typ = Y[i_start:i_start+nb_nodes] - if np.min(Y_typ) < 0: - raise ValueError("Got a negative label for type %d"%typ) - if np.min(Y_typ) < self._l_type_startindex[typ] : raise InconsistentLabel("labels of type %d start at %d"%(typ, self._l_type_startindex[typ])) - if np.max(Y_typ) >= self._l_type_startindex[typ+1]: raise InconsistentLabel("labels of type %d end at %d"%(typ, self._l_type_startindex[typ+1]-1)) + if np.min(Y_typ) < 0: + raise ValueError("Got a negative label for type %d" % typ) + if np.min(Y_typ) < self._l_type_startindex[typ]: + raise InconsistentLabel("labels of type %d start at %d" + "" % (typ, + self._l_type_startindex[typ])) + if np.max(Y_typ) >= self._l_type_startindex[typ+1]: + raise InconsistentLabel("labels of type %d end at %d" + "" % (typ, + self._l_type_startindex[typ+1]-1) + ) i_start = i_start + nb_nodes return True - - + def _get_node_features(self, x): - #we replace None by empty array with proper shape - return [ np.empty((0,_n_feat)) if node_features is None else node_features + # we replace None by empty array with proper shape + return [np.empty((0, _n_feat)) if node_features is None + else node_features for (node_features, _n_feat) in zip(x[0], self.l_n_features)] - + def _get_edges(self, x): - return [ np.empty((0,2)) if edges is None or len(edges)==0 else edges for edges in x[1]] - + return [np.empty((0, 2)) if edges is None or len(edges) == 0 + else edges for edges in x[1]] + def _get_edges_by_type(self, x, typ1, typ2): - return x[1][typ1*self.n_types+typ2] + return x[1][typ1 * self.n_types+typ2] def _iter_type_pairs(self): for typ1 in range(self.n_types): @@ -238,18 +280,17 @@ def _iter_type_pairs(self): yield (typ1, typ2) raise StopIteration - def _get_unary_potentials(self, x, w): """Computes unary potentials for x and w. - + Parameters ---------- x : tuple Instance Representation. - + w : ndarray, shape=(size_joint_feature,) Weight vector for CRF instance. - + Returns ------- unaries : list of ndarray, shape=( n_nodes_typ, n_states_typ ) @@ -257,37 +298,38 @@ def _get_unary_potentials(self, x, w): """ self._check_size_w(w) l_node_features = self._get_node_features(x) - + l_unary_potentials = [] - + i_w = 0 - for (features, n_states, n_features) in zip(l_node_features, self.l_n_states, self.l_n_features): + for (features, n_states, n_features) in zip(l_node_features, + self.l_n_states, + self.l_n_features): n_w = n_states*n_features - l_unary_potentials.append( np.dot(features, w[i_w:i_w+n_w].reshape(n_states, n_features).T) ) + l_unary_potentials.append( + np.dot(features, + w[i_w:i_w+n_w].reshape(n_states, + n_features).T + ) + ) i_w += n_w assert i_w == self.size_unaries - + # nodes x features . features x states --> nodes x states return l_unary_potentials - def continuous_loss(self, y, l_y_hat): # continuous version of the loss # y is the result of linear programming - #BUT, in multitype mode, y_hat is a list of unaries - if y.ndim == 2: - raise ValueError("FIXME!") -# gx = np.indices(y.shape) -# # all entries minus correct ones -# result = 1 - y_hat[gx, y] - + # BUT, in multitype mode, y_hat is a list of unaries l_result = list() cum_n_node = 0 cum_n_state = 0 for y_hat in l_y_hat: n_node, n_state = y_hat.shape # all entries minus correct ones - y_type = y[cum_n_node:cum_n_node+n_node] - cum_n_state #select the correct range of labels and make the labels start at 0 + # select the correct range of labels and make the labels start at 0 + y_type = y[cum_n_node:cum_n_node+n_node] - cum_n_state gx = np.indices(y_type.shape) result = 1 - y_hat[gx, y_type] l_result.append(result) @@ -298,4 +340,3 @@ def continuous_loss(self, y, l_y_hat): if hasattr(self, 'class_weight'): return np.sum(self.class_weight[y] * result) return np.sum(result) - From cbdc5d5b7c8bda0a200445bec2a29ff574d6eb69 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 3 Jan 2018 16:49:41 +0100 Subject: [PATCH 107/155] PEP8 --- pystruct/inference/inference_methods.py | 131 ++++++++++++++++-------- pystruct/learners/ssvm.py | 13 ++- 2 files changed, 94 insertions(+), 50 deletions(-) diff --git a/pystruct/inference/inference_methods.py b/pystruct/inference/inference_methods.py index ae6c7331..26bc19df 100644 --- a/pystruct/inference/inference_methods.py +++ b/pystruct/inference/inference_methods.py @@ -17,7 +17,9 @@ def get_installed(method_filter=None): if method != 'ad3+': inference_dispatch(unary, pw, edges, inference_method=method) else: - inference_dispatch(unary, np.zeros((0,1,1)), np.zeros((0,2), dtype=np.int), inference_method=method) + inference_dispatch(unary, np.zeros((0,1,1)) + , np.zeros((0,2), dtype=np.int) + , inference_method=method) installed.append(method) except ImportError: pass @@ -25,15 +27,18 @@ def get_installed(method_filter=None): class InferenceException(Exception): """ - When inference status is fractional or unsolved, this exception can be raised. - (If relaxed is not True and if an inference exception is requested by the calling code) + When inference status is fractional or unsolved, this exception can be + raised. + (If relaxed is not True and if an inference exception is requested by the + calling code) The exception message is the solver status. """ pass def inference_dispatch(unary_potentials, pairwise_potentials, edges, inference_method, return_energy=False, **kwargs): - """Computes the maximizing assignment of a pairwise discrete energy function. + """ + Computes the maximizing assignment of a pairwise discrete energy function. Wrapper function to dispatch between inference method by string. @@ -42,9 +47,11 @@ def inference_dispatch(unary_potentials, pairwise_potentials, edges, unary_potentials : nd-array, shape (n_nodes, n_states) Unary potentials of energy function. - pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). Pairwise potentials of energy function. - If the first case, edge potentials are assumed to be the same for all edges. + If the first case, edge potentials are assumed to be the same for all + edges. In the second case, the sequence needs to correspond to the edges. edges : nd-array, shape (n_edges, 2) @@ -125,9 +132,11 @@ def inference_ogm(unary_potentials, pairwise_potentials, edges, unary_potentials : nd-array, shape (n_nodes, n_states) Unary potentials of energy function. - pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). Pairwise potentials of energy function. - If the first case, edge potentials are assumed to be the same for all edges. + If the first case, edge potentials are assumed to be the same for all + edges. In the second case, the sequence needs to correspond to the edges. edges : nd-array, shape (n_edges, 2) @@ -240,9 +249,11 @@ def inference_qpbo(unary_potentials, pairwise_potentials, edges, **kwargs): unary_potentials : nd-array, shape (n_nodes, n_states) Unary potentials of energy function. - pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). Pairwise potentials of energy function. - If the first case, edge potentials are assumed to be the same for all edges. + If the first case, edge potentials are assumed to be the same for all + edges. In the second case, the sequence needs to correspond to the edges. edges : nd-array, shape (n_edges, 2) @@ -279,9 +290,11 @@ def inference_lp(unary_potentials, pairwise_potentials, edges, relaxed=False, unary_potentials : nd-array, shape (n_nodes, n_states) Unary potentials of energy function. - pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). Pairwise potentials of energy function. - If the first case, edge potentials are assumed to be the same for all edges. + If the first case, edge potentials are assumed to be the same for all + edges. In the second case, the sequence needs to correspond to the edges. edges : nd-array, shape (n_edges, 2) @@ -332,9 +345,11 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, unary_potentials : nd-array, shape (n_nodes, n_states) Unary potentials of energy function. - pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). Pairwise potentials of energy function. - If the first case, edge potentials are assumed to be the same for all edges. + If the first case, edge potentials are assumed to be the same for all + edges. In the second case, the sequence needs to correspond to the edges. edges : nd-array, shape (n_edges, 2) @@ -364,21 +379,24 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, Approximate (usually) MAP variable assignment. If relaxed=False, this is a tuple of unary and edge 'marginals'. - Code updated on Feb 2017 to deal with multiple node types, by JL Meunier, for the EU READ project (grant agreement No 674943) - Copyright JL Meunier, Xerox 2017 + Code updated on Feb 2017 to deal with multiple node types, by JL Meunier + , for the EU READ project (grant agreement No 674943) + """ import ad3 bMultiType = isinstance(unary_potentials, list) if bMultiType: - res = ad3.general_graph(unary_potentials, edges, pairwise_potentials, verbose=verbose, - n_iterations=4000, exact=branch_and_bound) + res = ad3.general_graph(unary_potentials, edges, pairwise_potentials + , verbose=verbose + , n_iterations=4000, exact=branch_and_bound) else: #usual code n_states, pairwise_potentials = \ _validate_params(unary_potentials, pairwise_potentials, edges) unaries = unary_potentials.reshape(-1, n_states) - res = ad3.general_graph(unaries, edges, pairwise_potentials, verbose=verbose, - n_iterations=4000, exact=branch_and_bound) + res = ad3.general_graph(unaries, edges, pairwise_potentials + , verbose=verbose, n_iterations=4000 + , exact=branch_and_bound) unary_marginals, pairwise_marginals, energy, solver_status = res if verbose: @@ -395,13 +413,15 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, else: if bMultiType: #we now get a list of unary marginals - if inference_exception and solver_status in ["fractional", "unsolved"]: + if inference_exception and solver_status in ["fractional" + , "unsolved"]: raise InferenceException(solver_status) ly = list() _cum_n_states = 0 for unary_marg in unary_marginals: ly.append( _cum_n_states + np.argmax(unary_marg, axis=-1) ) - _cum_n_states += unary_marg.shape[1] #number of states for that type + # number of states for that type + _cum_n_states += unary_marg.shape[1] y = np.hstack(ly) else: #usual code @@ -411,20 +431,24 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, return y, -energy return y -def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges, relaxed=False, - verbose=0, return_energy=False, branch_and_bound=False, - constraints=None, - inference_exception=None): - """Inference with AD3 dual decomposition subgradient solver. + +def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges + , relaxed=False + , verbose=0, return_energy=False, branch_and_bound=False + , constraints=None, inference_exception=None): + """ + Inference with AD3 dual decomposition subgradient solver. Parameters ---------- unary_potentials : nd-array, shape (n_nodes, n_states) Unary potentials of energy function. - pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). Pairwise potentials of energy function. - If the first case, edge potentials are assumed to be the same for all edges. + If the first case, edge potentials are assumed to be the same for all + edges. In the second case, the sequence needs to correspond to the edges. edges : nd-array, shape (n_edges, 2) @@ -449,15 +473,23 @@ def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges, relaxe branch-and-bound. constraints : list of logical constraints or None (default:=None) - A logical constraint is tuple like ( , , , ) + A logical constraint is tuple like + ( , , , ) where: - - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' - - unaries is a list of the index of each unary involved in this constraint - - states is a list of unary states (class), 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. - - negated is a list of boolean indicating if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list + - operator is one of: + 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - unaries is a list of the index of each unary involved in this + constraint + - states is a list of unary states (class), 1 per involved unary. If the + states are all the same, you can pass it directly as a scalar value. + - negated is a list of boolean indicating if the unary must be negated. + Again, if all values are the same, pass a single boolean value instead + of a list - NOTE: this hard logic constraint mechanism has been developed for the EU project READ, by JL Meunier (Xerox), in November 2016. - The READ project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. + NOTE: this hard logic constraint mechanism has been developed for the + EU project READ, by JL Meunier (Xerox), in November 2016. + The READ project has received funding from the European Union's Horizon + 2020 research and innovation programme under grant agreement No 674943. Returns ------- @@ -465,8 +497,10 @@ def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges, relaxe Approximate (usually) MAP variable assignment. If relaxed=False, this is a tuple of unary and edge 'marginals'. - Code written on Feb 2017 to deal with multiple node types, by JL Meunier, for the EU READ project (grant agreement No 674943) - Copyright JL Meunier, Xerox 2017 + Code written on Feb 2017 to deal with multiple node types, by JL Meunier, + for the EU READ project (grant agreement No 674943) + + JL Meunier """ import ad3 @@ -475,8 +509,11 @@ def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges, relaxe # unaries = unary_potentials.reshape(-1, n_states) bMultiType = isinstance(l_unary_potentials, list) - res = ad3.general_constrained_graph(l_unary_potentials, l_edges, l_pairwise_potentials, constraints, verbose=verbose, - n_iterations=4000, exact=branch_and_bound) + res = ad3.general_constrained_graph(l_unary_potentials, l_edges + , l_pairwise_potentials, constraints + , verbose=verbose + , n_iterations=4000 + , exact=branch_and_bound) l_unary_marginals, l_pairwise_marginals, energy, solver_status = res if verbose: @@ -493,9 +530,12 @@ def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges, relaxe _cum_n_states = 0 for unary_marg in l_unary_marginals: ly.append( _cum_n_states + np.argmax(unary_marg, axis=-1) ) - _cum_n_states += unary_marg.shape[1] #number of states for that type + #number of states for that type + _cum_n_states += unary_marg.shape[1] y = np.hstack(ly) - # when we will simplify y: y = [_cum_n_statesnp.argmax(unary_marg, axis=-1) for unary_marg in l_unary_marginals] + # when we will simplify y: + #y = [_cum_n_statesnp.argmax(unary_marg, axis=-1) for unary_marg + # in l_unary_marginals] else: y = np.argmax(l_unary_marginals, axis=-1) @@ -505,8 +545,8 @@ def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges, relaxe -def inference_unaries(unary_potentials, pairwise_potentials, edges, verbose=0, - **kwargs): +def inference_unaries(unary_potentials, pairwise_potentials, edges, verbose=0 + , **kwargs): """Inference that only uses unary potentials. This methods can be used as a sanity check, as acceleration if no @@ -517,7 +557,8 @@ def inference_unaries(unary_potentials, pairwise_potentials, edges, verbose=0, unary_potentials : nd-array, shape (n_nodes, n_states) Unary potentials of energy function. - pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). Pairwise potentials of energy function. These will be ignored. diff --git a/pystruct/learners/ssvm.py b/pystruct/learners/ssvm.py index d6c7c5e9..308ecdb8 100644 --- a/pystruct/learners/ssvm.py +++ b/pystruct/learners/ssvm.py @@ -25,7 +25,7 @@ def predict(self, X, constraints=None): ---------- X : iterable Traing instances. Contains the structured input objects. - + constraints : None or a list of hard logic constraints Returns @@ -38,19 +38,22 @@ def predict(self, X, constraints=None): if self.n_jobs != 1: if constraints: prediction = Parallel(n_jobs=self.n_jobs, verbose=verbose)( - delayed(inference)(self.model, x, self.w, constraints=c) for x,c in zip(X, constraints)) + delayed(inference)(self.model, x, self.w, constraints=c) + for x, c in zip(X, constraints)) else: prediction = Parallel(n_jobs=self.n_jobs, verbose=verbose)( delayed(inference)(self.model, x, self.w) for x in X) return prediction else: if hasattr(self.model, 'batch_inference'): - if constraints: - return self.model.batch_inference(X, self.w, constraints=constraints) + if constraints: + return self.model.batch_inference(X, self.w, + constraints=constraints) else: return self.model.batch_inference(X, self.w) if constraints: - return [self.model.inference(x, self.w, constraints=c) for x,c in zip(X, constraints)] + return [self.model.inference(x, self.w, constraints=c) + for x, c in zip(X, constraints)] return [self.model.inference(x, self.w) for x in X] def score(self, X, Y): From f9f22e8728f340654eec7e6af185180306e82067 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 3 Jan 2018 17:05:42 +0100 Subject: [PATCH 108/155] 0.3.6 --- CHANGELOG | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 43e964d0..92bc182f 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,7 @@ +0.3.6 +=== +- Taking into account Andreas feedback on the PR + 0.3.5 === - Few fixes From b0f0bc694f1759bba1758c1a43824817d06b1762 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Wed, 3 Jan 2018 17:16:00 +0100 Subject: [PATCH 109/155] install_requires=["ad3", "numpy"] --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 71ccf060..c5b6fc78 100644 --- a/setup.py +++ b/setup.py @@ -11,7 +11,7 @@ setup(name="pystruct", version="0.3.6", - install_requires=["ad3>=2.1.2"], + install_requires=["ad3", "numpy"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', 'pystruct.tests', 'pystruct.tests.test_learners', From a94e55b59951069aadbe377e84ba52a5b6115414 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 10:25:10 +0100 Subject: [PATCH 110/155] Update README.md point to Transkribus/AD3 instead of jlmeunier/AD3 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8928c4cf..0d334558 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ This is a fork from Andreas Mueller's [pystruct](https://github.com/pystruct/pys and prediction library. In particular, pystruct provides a well-documented tool for researchers as well as non-experts to make use of structured prediction algorithms. And the design tries to stay as close as possible to the interface and conventions of [scikit-learn](http://scikit-learn.org). -The goal of the [pystruct+](https://github.com/jlmeunier/pystruct) project and of its companion project [AD3+](https://github.com/jlmeunier/AD3) is to extend pystruct along two directions: +The goal of the [pystruct+](https://github.com/jlmeunier/pystruct) project and of its companion project [AD3+](https://github.com/Transkribus/AD3) is to extend pystruct along two directions: * **supporting hard-logic constraints when predicting** * **supporting nodes of different nature in CRF graphs** @@ -35,7 +35,7 @@ What is different in pystruct+? Currently, the offered extensions rely on the __*AD3+*__ solver. For learning I mostly used the __*OneSlackSSVM*__ learner, which requires to install cvxopt as well. ### For AD3+: - * get it from https://github.com/jlmeunier/AD3 + * get it from https://github.com/Transkribus/AD3 * install: python setup.py install > python setup.py install From 4ee0753e057ffb4ab9cac83af0790ebccbdc036d Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 11:06:35 +0100 Subject: [PATCH 111/155] Try CI on conda --- .travis.yml | 10 +++++----- continuous_integration/install.sh | 15 +++++++++++---- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/.travis.yml b/.travis.yml index db449a85..3f840c2f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,15 +22,15 @@ virtualenv: system_site_packages: true env: matrix: - - DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="true" + #- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="true" ## ubuntu without opengm - - DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" + #- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" ## This environment tests the newest supported anaconda env - DISTRIB="conda" PYTHON_VERSION="2.7" - NUMPY_VERSION="1.10.4" SCIPY_VERSION="0.17.0" + NUMPY_VERSION="1.13.3 SCIPY_VERSION="0.19.1" # python3 only on ubuntu because of cvxopt - - DISTRIB="conda" PYTHON_VERSION="3.4" OPENGM="false" - NUMPY_VERSION="1.10.4" SCIPY_VERSION="0.17.0" + #- DISTRIB="conda" PYTHON_VERSION="3.4" OPENGM="false" + # NUMPY_VERSION="1.10.4" SCIPY_VERSION="0.17.0" install: source continuous_integration/install.sh script: bash continuous_integration/test_script.sh after_success: diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index 7a21e435..17796f5c 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -34,7 +34,7 @@ if [[ "$DISTRIB" == "conda" ]]; then # Use the miniconda installer for faster download / install of conda # itself - wget http://repo.continuum.io/miniconda/Miniconda-3.6.0-Linux-x86_64.sh \ + wget https://repo.continuum.io/miniconda/Miniconda2-4.3.31-Linux-x86_64.sh \ -O miniconda.sh chmod +x miniconda.sh && ./miniconda.sh -b export PATH=/home/travis/miniconda/bin:$PATH @@ -43,10 +43,10 @@ if [[ "$DISTRIB" == "conda" ]]; then # Configure the conda environment and put it in the path using the # provided versions - conda create -n testenv --yes python=$PYTHON_VERSION pip nose cython scikit-learn cvxopt\ + conda create -n testenv --yes python=$PYTHON_VERSION pip nose cython\ + scikit-learn cvxopt pytest future \ numpy=$NUMPY_VERSION scipy=$SCIPY_VERSION - source activate testenv elif [[ "$DISTRIB" == "ubuntu" ]]; then @@ -63,7 +63,14 @@ python --version python -c "import numpy; print('numpy %s' % numpy.__version__)" python -c "import scipy; print('scipy %s' % scipy.__version__)" # install our favorite inference packages -$PIP install pyqpbo ad3 scikit-learn +#$PIP install pyqpbo ad3 scikit-learn +$PIP install pyqpbo scikit-learn + +#get Transkribus/AD3 +#after the PR is validated, use normal AD3 instead! (written Jan 2018) +git clone https://github.com/Transkribus/AD3.git +cd AD3 +python setup.py install # Build scikit-learn in the install.sh script to collapse the verbose # build output in the travis output when it succeeds. From 3cb43e0f4924bb0781e1211469e8a6620c2e9df6 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 11:21:34 +0100 Subject: [PATCH 112/155] CI work --- continuous_integration/install.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index 17796f5c..78012993 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -37,7 +37,8 @@ if [[ "$DISTRIB" == "conda" ]]; then wget https://repo.continuum.io/miniconda/Miniconda2-4.3.31-Linux-x86_64.sh \ -O miniconda.sh chmod +x miniconda.sh && ./miniconda.sh -b - export PATH=/home/travis/miniconda/bin:$PATH + # export PATH=/home/travis/miniconda2/bin:$PATH + source miniconda2/bin/activate conda update --yes conda # Configure the conda environment and put it in the path using the From c7cac12f39c85c5aad9032d2bf83c105f17f55f1 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 14:20:12 +0100 Subject: [PATCH 113/155] ls --- continuous_integration/install.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index 78012993..542cd8a8 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -38,6 +38,7 @@ if [[ "$DISTRIB" == "conda" ]]; then -O miniconda.sh chmod +x miniconda.sh && ./miniconda.sh -b # export PATH=/home/travis/miniconda2/bin:$PATH + ls source miniconda2/bin/activate conda update --yes conda From 6a257f72865a1b7c6b267812a7214c89604e075a Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 14:29:12 +0100 Subject: [PATCH 114/155] -p --- continuous_integration/install.sh | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index 542cd8a8..b0a1c125 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -36,10 +36,8 @@ if [[ "$DISTRIB" == "conda" ]]; then # itself wget https://repo.continuum.io/miniconda/Miniconda2-4.3.31-Linux-x86_64.sh \ -O miniconda.sh - chmod +x miniconda.sh && ./miniconda.sh -b - # export PATH=/home/travis/miniconda2/bin:$PATH - ls - source miniconda2/bin/activate + chmod +x miniconda.sh && ./miniconda.sh -b -p $HOME/miniconda2 + export PATH=$HOME/miniconda2/bin:$PATH conda update --yes conda # Configure the conda environment and put it in the path using the From f854794b2111d6235028f80396fd03599c4dae3d Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 14:34:54 +0100 Subject: [PATCH 115/155] syntax error fix --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 3f840c2f..611acd59 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,7 +27,7 @@ env: #- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" ## This environment tests the newest supported anaconda env - DISTRIB="conda" PYTHON_VERSION="2.7" - NUMPY_VERSION="1.13.3 SCIPY_VERSION="0.19.1" + NUMPY_VERSION="1.13.3" SCIPY_VERSION="0.19.1" # python3 only on ubuntu because of cvxopt #- DISTRIB="conda" PYTHON_VERSION="3.4" OPENGM="false" # NUMPY_VERSION="1.10.4" SCIPY_VERSION="0.17.0" From c8dcb369e4431c20a0136f1482294d095a2ef0e5 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 14:43:48 +0100 Subject: [PATCH 116/155] pushd/popd --- continuous_integration/install.sh | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index b0a1c125..6b5983d4 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -69,8 +69,9 @@ $PIP install pyqpbo scikit-learn #get Transkribus/AD3 #after the PR is validated, use normal AD3 instead! (written Jan 2018) git clone https://github.com/Transkribus/AD3.git -cd AD3 +pushd AD3 python setup.py install +popd # Build scikit-learn in the install.sh script to collapse the verbose # build output in the travis output when it succeeds. From eed0fc50bc33c5ca7074ced6d0118a89df88478d Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 15:44:49 +0100 Subject: [PATCH 117/155] DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" --- .travis.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 611acd59..18e33fe9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,10 +24,10 @@ env: matrix: #- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="true" ## ubuntu without opengm - #- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" + - DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" ## This environment tests the newest supported anaconda env - - DISTRIB="conda" PYTHON_VERSION="2.7" - NUMPY_VERSION="1.13.3" SCIPY_VERSION="0.19.1" + #- DISTRIB="conda" PYTHON_VERSION="2.7" + # NUMPY_VERSION="1.13.3" SCIPY_VERSION="0.19.1" # python3 only on ubuntu because of cvxopt #- DISTRIB="conda" PYTHON_VERSION="3.4" OPENGM="false" # NUMPY_VERSION="1.10.4" SCIPY_VERSION="0.17.0" From eb13d9c35884094c66a0ce4036bb338176f916d0 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 16:09:48 +0100 Subject: [PATCH 118/155] DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="true" --- .travis.yml | 6 +++--- continuous_integration/install.sh | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 18e33fe9..3db91a18 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,11 +22,11 @@ virtualenv: system_site_packages: true env: matrix: - #- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="true" + - DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="true" ## ubuntu without opengm - - DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" + #OK- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" ## This environment tests the newest supported anaconda env - #- DISTRIB="conda" PYTHON_VERSION="2.7" + #OK- DISTRIB="conda" PYTHON_VERSION="2.7" # NUMPY_VERSION="1.13.3" SCIPY_VERSION="0.19.1" # python3 only on ubuntu because of cvxopt #- DISTRIB="conda" PYTHON_VERSION="3.4" OPENGM="false" diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index 6b5983d4..7d84c902 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -21,8 +21,10 @@ export PIP=pip if [[ "$OPENGM" == "true" ]]; then git clone https://github.com/opengm/opengm.git cd opengm - cmake . -DCMAKE_INSTALL_PREFIX=/home/travis/.local -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_EXAMPLES=FALSE -DBUILD_TESTING=FALSE - make -j2 --quiet + # old cmake . -DCMAKE_INSTALL_PREFIX=/home/travis/.local -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_EXAMPLES=FALSE -DBUILD_TESTING=FALSE + # old make -j2 --quiet + cmake . -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DWITH_AD3=FALSE -DWITH_TRWS=FALSE -DWITH_QPBO=FALSE -DWITH_MRF=FALSE -DWITH_GCO=FALSE -DWITH_CONICBUNDLE=FALSE -DWITH_MAXFLOW=FALSE -DWITH_MAXFLOW_IBFS=FALSE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_COMMANDLINE=FALSE -DCI=TRUE + make -j4 --quiet make install cd .. fi From fb61eedbb89dd08cee63a8cd6110697df746003c Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 16:15:16 +0100 Subject: [PATCH 119/155] removed all prints --- .../test_node_type_edge_feature_graph_crf.py | 138 +++++++++--------- 1 file changed, 69 insertions(+), 69 deletions(-) diff --git a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py index d7bee7e0..7919817a 100644 --- a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py +++ b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py @@ -70,7 +70,7 @@ def test_checks(): def debug_joint_feature(): # ------------------------------------------------------------------------------------------- - print "---MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" + #print "---MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" g = NodeTypeEdgeFeatureGraphCRF( 2 #how many node type? , [2, 3] #how many possible labels per node type? @@ -94,15 +94,15 @@ def debug_joint_feature(): ] x = (l_node_f, l_edges, l_edge_f) - print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([ np.array([0, 1]), np.array([0, 1, 2]) ]) - print y + #print y g.initialize(x, y) jf = g.joint_feature(x,y) - print "joint_feature = \n", `jf` - print + #print "joint_feature = \n", `jf` + #print assert_array_equal(jf, jf) assert_array_almost_equal(jf , np.array( @@ -174,7 +174,7 @@ def test_flatten_unflattenY(): l_nf = [ np.zeros( (2,3) ), np.zeros( (3, 4) )] #2 node with 3 features, 3 node with 4 features X = (l_nf, None, None) #we give no edge assert (g.flattenY(Y) == y).all() - print g.unflattenY(X, y) + #print g.unflattenY(X, y) assert all( [ (y_typ1 == y_typ2).all() for y_typ1, y_typ2 in zip(g.unflattenY(X, y), Y) ]) l_nf = [ np.zeros( (1,3) ), np.zeros( (3, 4) )] #2 node with 3 features, 3 node with 4 features @@ -183,19 +183,19 @@ def test_flatten_unflattenY(): def test_joint_feature(): - print "---SIMPLE---------------------------------------------------------------------" + #print "---SIMPLE---------------------------------------------------------------------" g, (node_f, edges, edge_f) = get_simple_graph_structure(), get_simple_graph() x = (node_f, edges, edge_f) - print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.array([1,2]) # y = np.array([1,0]) - print y + #print y g.initialize(x, y) jf = g.joint_feature(x,y) - print "joint_feature = \n", `jf` - print + #print "joint_feature = \n", `jf` + #print assert_array_equal(g.joint_feature(x,y) , np.array([ 0., 0., 0., 1., 1., 1., 2., 2., 2., 0., 0., 0. , 0., @@ -205,13 +205,13 @@ def test_joint_feature(): 0., 0., 0., 0., 0., 0., 0., 0.]) ) - print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.array([0,0]) - print y + #print y g.initialize(x, y) jf = g.joint_feature(x,y) - print "joint_feature = \n", `jf` - print + #print "joint_feature = \n", `jf` + #print assert_array_equal(g.joint_feature(x,y) , np.array([ 3., 3., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., @@ -220,14 +220,14 @@ def test_joint_feature(): 0., 0., 0., 0., 0., 0., 0., 0.]) ) - print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.array([0,1]) node_f = [ np.array([[1.1,1.2,1.3], [2.1,2.2,2.3]]) ] edge_f = [ np.array([[3.1,3.2,3.3]]) ] x = (node_f, edges, edge_f) g.initialize(x, y) jf = g.joint_feature(x,y) - print "joint_feature = \n", `jf` + #print "joint_feature = \n", `jf` assert_array_equal(g.joint_feature(x,y) , np.array([ 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 0. , 0. , 0. , 0. , 0. , @@ -237,17 +237,17 @@ def test_joint_feature(): 0. , 3.3, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]) ) - print "---SIMPLE + 2nd EDGE--------------------------------------------------------" + #print "---SIMPLE + 2nd EDGE--------------------------------------------------------" node_f, edges, edge_f = get_simple_graph2() x = (node_f, edges, edge_f) - print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.array([1,2]) - print y + #print y g.initialize(x, y) jf = g.joint_feature(x,y) - print "joint_feature = \n", `jf` - print + #print "joint_feature = \n", `jf` + #print assert_array_equal(jf , np.array([ 0., 0., 0., 1., 1., 1., 2., 2., 2., 0., 0., 0., 0., 0., 0., 0., 0., 4., 3., 0., 0., 0., 0., 0., 0., 0., @@ -255,12 +255,12 @@ def test_joint_feature(): 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 4., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) ) - print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.array([0,0]) - print y + #print y g.initialize(x, y) - print "joint_feature = \n", `g.joint_feature(x,y)` - print + #print "joint_feature = \n", `g.joint_feature(x,y)` + #print assert_array_equal(g.joint_feature(x,y) , np.array([ 3., 3., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 7., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., @@ -305,15 +305,15 @@ def more_complex_graph(): def test_joint_feature2(): # ------------------------------------------------------------------------------------------- - print "---MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" + #print "---MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" g, x, y = more_complex_graph() - print y + #print y g.initialize(x, y) jf = g.joint_feature(x,y) - print "joint_feature = \n", `jf` - print + #print "joint_feature = \n", `jf` + #print assert_array_equal(jf, jf) assert_array_almost_equal(jf , np.array([ 3. , 3. , 3. , 0. , 0. , 0. , 0.63 , 0.66 , @@ -326,7 +326,7 @@ def test_joint_feature2(): 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ])) - print "---MORE COMPLEX GRAPH :) -- BIS -------------------------------------------------------------------" + #print "---MORE COMPLEX GRAPH :) -- BIS -------------------------------------------------------------------" g = NodeTypeEdgeFeatureGraphCRF( 2 #how many node type? , [2, 3] #how many labels per node type? @@ -349,14 +349,14 @@ def test_joint_feature2(): ] x = ( node_f, edges, edge_f) - print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([np.array([0, 1]), 2+np.array([0, 1, 2])]) - print y + #print y g.initialize(x, y) jf = g.joint_feature(x,y) - print "joint_feature = \n", `jf` - print + #print "joint_feature = \n", `jf` + #print assert_array_equal(jf, jf) assert_array_almost_equal(jf , np.array([ 1. , 1. , 1. , 2. , 2. , 2. , 0.11 , 0.12 , @@ -369,8 +369,8 @@ def test_joint_feature2(): 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ])) - print "MORE COMPLEX GRAPH :) -- BIS OK" - print "--- REORDERED MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" + #print "MORE COMPLEX GRAPH :) -- BIS OK" + #print "--- REORDERED MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" node_f = [ np.array([ [2,2,2], [1,1,1] ]) , np.array([ [.31, .32, .33, .34], [.11, .12, .13, .14], [.21, .22, .23, .24]]) ] @@ -385,14 +385,14 @@ def test_joint_feature2(): ] x = ( node_f, edges, edge_f) - print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([np.array([1, 0]), 2+np.array([2, 0, 1])]) - print y + #print y g.initialize(x, y) jf = g.joint_feature(x,y) - print "joint_feature = \n", `jf` - print + #print "joint_feature = \n", `jf` + #print assert_array_equal(jf, jf) assert_array_almost_equal(jf , np.array([ 1. , 1. , 1. , 2. , 2. , 2. , 0.11 , 0.12 , @@ -408,7 +408,7 @@ def test_joint_feature2(): def test_joint_feature3(): # ------------------------------------------------------------------------------------------- - print "---MORE COMPLEX GRAPH AGAIN :) ---------------------------------------------------------------------" + #print "---MORE COMPLEX GRAPH AGAIN :) ---------------------------------------------------------------------" g = NodeTypeEdgeFeatureGraphCRF( 2 #how many node type? , [2, 3] #how many labels per node type? @@ -439,17 +439,17 @@ def test_joint_feature3(): ] x = (node_f, edges, edge_f) - print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([ np.array([0, 0]) , 2+np.array([0, 0, 0]) ]) - print y + #print y g.initialize(x, y) - print g.size_unaries - print g.size_pairwise + #print g.size_unaries + #print g.size_pairwise jf = g.joint_feature(x,y) - print "joint_feature = \n", `jf` - print + #print "joint_feature = \n", `jf` + #print assert_array_equal(jf, jf) assert_array_almost_equal(jf , np.array([ 3. , 3. , 3. , 0. , 0. , 0. , @@ -469,15 +469,15 @@ def test_joint_feature3(): ]) ) - print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([ np.array([0, 1]) , 2+np.array([1, 1, 0]) ]) - print y + #print y g.initialize(x, y) jf = g.joint_feature(x,y) - print "joint_feature = \n", `jf` - print + #print "joint_feature = \n", `jf` + #print assert_array_equal(jf, jf) assert_array_almost_equal(jf , np.array([ 1. , 1. , 1. , 2. , 2. , 2. , @@ -500,9 +500,9 @@ def test_joint_feature3(): w = np.array([ 1,1,1, 2,2,2, 10,10,10,10, 20,20,20,20, 30,30,30,30 ] +[1.0]*51, dtype=np.float64 ) - print `w` + #print `w` ret_u = g._get_unary_potentials(x, w) - print `ret_u` + #print `ret_u` assert len(ret_u) == 2 assert_array_almost_equal(ret_u[0], np.array([ #n_nodes x n_states [3, 6], @@ -515,8 +515,8 @@ def test_joint_feature3(): assert len(w) == g.size_joint_feature ret_pw = g._get_pairwise_potentials(x, w) - for _pw in ret_pw: - print "_pw ", `_pw` + # for _pw in ret_pw: + # print "_pw ", `_pw` pw00, pw01, pw10, pw11 = ret_pw assert len(pw00) == 0 assert_array_almost_equal(pw01,np.array([ #n_edges, n_states, n_states @@ -538,7 +538,7 @@ def test_joint_feature3(): def test_unary_potentials(): - print "---SIMPLE---------------------------------------------------------------------" + #print "---SIMPLE---------------------------------------------------------------------" #g, (node_f, edges, edge_f) = get_simple_graph_structure(), get_simple_graph() g = NodeTypeEdgeFeatureGraphCRF( @@ -555,27 +555,27 @@ def test_unary_potentials(): edge_f = [ np.array([[3,3,3]]) ] x = (node_f, edges, edge_f) - print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " y = np.hstack([ np.array([1,2])]) # y = np.array([1,0]) - print y + #print y g.initialize(x, y) gref = EdgeFeatureGraphCRF(4,3,3) xref = (node_f[0], edges[0], edge_f[0]) wref = np.arange(gref.size_joint_feature) potref = gref._get_unary_potentials(xref, wref) - print `potref` + #print `potref` w = np.arange(g.size_joint_feature) pot = g._get_unary_potentials(x, w) - print `pot` + #print `pot` assert_array_equal(pot, [potref]) pwpotref = gref._get_pairwise_potentials(xref, wref) - print `pwpotref` + #print `pwpotref` pwpot = g._get_pairwise_potentials(x, w) - print `pwpot` + #print `pwpot` assert_array_equal(pwpot, [pwpotref]) # def test_inference_util(): @@ -613,11 +613,11 @@ def test_unary_potentials(): # [6,1]])) # -def report_model_config(crf): - print crf.n_states - print crf.n_features - print crf.n_edge_features - +# def report_model_config(crf): +# print crf.n_states +# print crf.n_features +# print crf.n_edge_features + def inference_data(): """ Testing with a single type of nodes. Must do as well as EdgeFeatureGraphCRF @@ -869,4 +869,4 @@ def test_energy_discrete(): if 1: test_energy_continuous() if 1: test_energy_discrete() - print "OK" + #print "OK" From 783f7e4eb58d22363ff14ed3d2ce87c298b92dc1 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 16:26:58 +0100 Subject: [PATCH 120/155] Update install.sh --- continuous_integration/install.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index 7d84c902..03e6a253 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -23,7 +23,7 @@ if [[ "$OPENGM" == "true" ]]; then cd opengm # old cmake . -DCMAKE_INSTALL_PREFIX=/home/travis/.local -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_EXAMPLES=FALSE -DBUILD_TESTING=FALSE # old make -j2 --quiet - cmake . -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DWITH_AD3=FALSE -DWITH_TRWS=FALSE -DWITH_QPBO=FALSE -DWITH_MRF=FALSE -DWITH_GCO=FALSE -DWITH_CONICBUNDLE=FALSE -DWITH_MAXFLOW=FALSE -DWITH_MAXFLOW_IBFS=FALSE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_COMMANDLINE=FALSE -DCI=TRUE + cmake . -DCMAKE_INSTALL_PREFIX=/home/travis/.local -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DWITH_AD3=FALSE -DWITH_TRWS=FALSE -DWITH_QPBO=FALSE -DWITH_MRF=FALSE -DWITH_GCO=FALSE -DWITH_CONICBUNDLE=FALSE -DWITH_MAXFLOW=FALSE -DWITH_MAXFLOW_IBFS=FALSE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_COMMANDLINE=FALSE -DCI=TRUE make -j4 --quiet make install cd .. From 2ade10a7e31b58a4f942aa0c52882aa3cfe77823 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 16:56:17 +0100 Subject: [PATCH 121/155] python3.5 --- .travis.yml | 8 ++++---- continuous_integration/install.sh | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 3db91a18..36040444 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,15 +22,15 @@ virtualenv: system_site_packages: true env: matrix: - - DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="true" + #- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="true" ## ubuntu without opengm #OK- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" ## This environment tests the newest supported anaconda env #OK- DISTRIB="conda" PYTHON_VERSION="2.7" # NUMPY_VERSION="1.13.3" SCIPY_VERSION="0.19.1" - # python3 only on ubuntu because of cvxopt - #- DISTRIB="conda" PYTHON_VERSION="3.4" OPENGM="false" - # NUMPY_VERSION="1.10.4" SCIPY_VERSION="0.17.0" + # python3.5 only because of cvxopt? + - DISTRIB="conda3" PYTHON_VERSION="3.5" OPENGM="false" + NUMPY_VERSION="1.13" SCIPY_VERSION="1.0" install: source continuous_integration/install.sh script: bash continuous_integration/test_script.sh after_success: diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index 03e6a253..628b1821 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -51,6 +51,28 @@ if [[ "$DISTRIB" == "conda" ]]; then source activate testenv +elif [[ "$DISTRIB" == "conda3" ]]; then + # Deactivate the travis-provided virtual environment and setup a + # conda-based environment instead + deactivate + + # Use the miniconda installer for faster download / install of conda + # itself + wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh \ + -O miniconda.sh + chmod +x miniconda.sh && ./miniconda.sh -b -p $HOME/miniconda3 + export PATH=$HOME/miniconda3/bin:$PATH + conda update --yes conda + + # Configure the conda environment and put it in the path using the + # provided versions + + conda create -n testenv --yes python=$PYTHON_VERSION pip nose cython\ + scikit-learn cvxopt pytest future \ + numpy=$NUMPY_VERSION scipy=$SCIPY_VERSION + + source activate testenv + elif [[ "$DISTRIB" == "ubuntu" ]]; then # Use standard ubuntu packages in their default version # except for cython :-/ From e4c2c09dac49c2064a46434c2e0b9ea68069dc7d Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 17:28:57 +0100 Subject: [PATCH 122/155] OK for Python2.7 on Ubuntu (OpenGM or not) and on conda2 Python3 requires some code adaptation. --- .travis.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 611acd59..d8ab9d16 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,13 +22,18 @@ virtualenv: system_site_packages: true env: matrix: + ##Ubuntu with OpenGM can work. I've seen it working (build #12) + # But I'm getting into a random g++ bug: + # g++: internal compiler error: Killed (program cc1plus) + # Please submit a full bug report, #- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="true" ## ubuntu without opengm - #- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" + - DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" ## This environment tests the newest supported anaconda env - DISTRIB="conda" PYTHON_VERSION="2.7" NUMPY_VERSION="1.13.3" SCIPY_VERSION="0.19.1" # python3 only on ubuntu because of cvxopt + # Python3 need upgrade of Python code... Work ongoing! (JLM) #- DISTRIB="conda" PYTHON_VERSION="3.4" OPENGM="false" # NUMPY_VERSION="1.10.4" SCIPY_VERSION="0.17.0" install: source continuous_integration/install.sh From 349f3c97afc69f01da58af53c0af24c55b7e1e0f Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Fri, 5 Jan 2018 17:32:03 +0100 Subject: [PATCH 123/155] fixed YAML syntax --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d8ab9d16..a0c860e5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -25,7 +25,7 @@ env: ##Ubuntu with OpenGM can work. I've seen it working (build #12) # But I'm getting into a random g++ bug: # g++: internal compiler error: Killed (program cc1plus) - # Please submit a full bug report, + # Please submit a full bug report, #- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="true" ## ubuntu without opengm - DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" From dcb5c3a0a3023d4dc35eacfbaf148020474e71b5 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 8 Jan 2018 09:06:56 +0100 Subject: [PATCH 124/155] point to the correct travis build --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0d334558..64f6b7f0 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ -[![Build Status](https://travis-ci.org/pystruct/pystruct.png)](https://travis-ci.org/pystruct/pystruct) +[![Build Status](https://travis-ci.org/jlmeunier/pystruct.png)](https://travis-ci.org/jlmeunier/pystruct) [![pypi version](http://img.shields.io/pypi/v/pystruct.svg?style=flat)](https://pypi.python.org/pypi/pystruct/) [![licence](http://img.shields.io/badge/licence-BSD-blue.svg?style=flat)](https://github.com/pystruct/pystruct/blob/master/LICENSE) [![DOI](https://zenodo.org/badge/21369/pystruct/pystruct.svg)](https://zenodo.org/badge/latestdoi/21369/pystruct/pystruct) From 6d8ab3202ef8e32eaf3ffa00248b6065c6d91349 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 8 Jan 2018 16:23:44 +0100 Subject: [PATCH 125/155] examples ok with Python3 --- examples/plot_hidden_short_snakes_typed.py | 117 ++++++++++++--------- examples/plot_hidden_snakes.py | 30 +++--- examples/plot_snakes.py | 38 +++---- examples/plot_snakes_typed.py | 43 ++++---- 4 files changed, 125 insertions(+), 103 deletions(-) diff --git a/examples/plot_hidden_short_snakes_typed.py b/examples/plot_hidden_short_snakes_typed.py index ed209730..b78a936a 100644 --- a/examples/plot_hidden_short_snakes_typed.py +++ b/examples/plot_hidden_short_snakes_typed.py @@ -51,9 +51,14 @@ Copyright Xerox """ +from __future__ import (absolute_import, division, print_function) import sys, os, time -import random, cPickle +import random +try: + import cPickle as pickle +except: + import pickle import numpy as np import matplotlib.pyplot as plt @@ -95,16 +100,17 @@ #============================================================================================== def printConfig(): - print "== NCELL=", NCELL - print "== FIXED_SEED=", bFIXED_RANDOM_SEED - print "== INFERENCE =", INFERENCE - print "== N_JOBS =", N_JOBS - print "== SWAP=", nbSWAP_Pixel_Pict_TYPES - print "== EASY=", bMAKE_PICT_EASY - print "== MAX_ITER=", MAXITER - print "== MODEL FILE=", sMODELFILE - -if __name__ == '__main__': printConfig() + print("== NCELL=", NCELL) + print("== FIXED_SEED=", bFIXED_RANDOM_SEED) + print("== INFERENCE =", INFERENCE) + print("== N_JOBS =", N_JOBS) + print("== SWAP=", nbSWAP_Pixel_Pict_TYPES) + print("== EASY=", bMAKE_PICT_EASY) + print("== MAX_ITER=", MAXITER) + print("== MODEL FILE=", sMODELFILE) + +if __name__ == '__main__': + printConfig() def plot_snake(picture): @@ -127,7 +133,7 @@ def prepare_picture_data(X): [[45 55] [45 55]] """ - for i in xrange(5): + for i in range(5): ai, aj = np.where(a_hot_picture[...,i] == 1) feat[0,i] = len(ai) @@ -252,7 +258,8 @@ def swap_node_types(l_perm, l_n_state, lX, lY, constraints=None): _lY.append(_Y) if constraints: - print "WARNING: some constraints are not properly swapped because the node order has a meaning." + print("WARNING: some constraints are not properly swapped because the " + "node order has a meaning.") _constraints = list() for _lConstraints in constraints: for (op, l_l_unary, l_l_state, l_lnegated) in _lConstraints: @@ -325,15 +332,16 @@ def appendIntVectorToCsv(fd, name, aV): fd.flush() def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, name=""): - if t: print "\t( predict DONE IN %.1fs)"%t + if t: + print("\t( predict DONE IN %.1fs)"%t) _flat_GT, _flat_P = (np.hstack([y.ravel() for y in l_Y_GT]), np.hstack([y.ravel() for y in lY_Pred])) confmat = confusion_matrix(_flat_GT, _flat_P) - print confmat - print "\ttrace =", confmat.trace() + print(confmat) + print("\ttrace =", confmat.trace()) score = accuracy_score(_flat_GT, _flat_P) - print "\tAccuracy= %.3f"%score + print("\tAccuracy= %.3f"%score) #CSV out? if filename: @@ -358,12 +366,12 @@ def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, na #-------------------------------------------------------------------------------------------------- X_train, Y_train = snakes['X_train'], snakes['Y_train'] #X_train, Y_train = X_train[:3], Y_train[:3] - print "TRAIN SET ", len(X_train), len(Y_train) + print("TRAIN SET ", len(X_train), len(Y_train)) if NCELL <10: X_train, Y_train = shorten_snakes(X_train, Y_train, NCELL) nb_hidden, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False, nCell=NCELL) - print "TRAIN SET ",len(X_train), len(Y_train) + print("TRAIN SET ",len(X_train), len(Y_train)) Y_train_pict = np.array([1]*(len(X_train)-nb_hidden) + [0]*nb_hidden) X_train = [one_hot_colors(x) for x in X_train] @@ -373,7 +381,7 @@ def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, na X_train_pict_feat = prepare_picture_data(X_train) if bMAKE_PICT_EASY: - print "Making the train picture task easy" + print("Making the train picture task easy") makeItEasy(X_train_pict_feat, Y_train_pict) X_train_directions, X_train_edge_features = prepare_data(X_train) @@ -384,7 +392,7 @@ def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, na nb_hidden, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", False, nCell=NCELL) Y_test_pict = np.array([1]*(len(X_test)-nb_hidden) + [0]*nb_hidden) - print "TEST SET ", len(X_test), len(Y_test) + print("TEST SET ", len(X_test), len(Y_test)) X_test = [one_hot_colors(x) for x in X_test] @@ -392,16 +400,17 @@ def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, na X_test_pict_feat = prepare_picture_data(X_test) if bMAKE_PICT_EASY: - print "Making the test picture task easy" + print("Making the test picture task easy") makeItEasy(X_test_pict_feat, Y_test_pict) X_test_directions, X_test_edge_features = prepare_data(X_test) #-------------------------------------------------------------------------------------------------- - print "======================================================================================================" + print("===================================================================" + "===================================") if True: from pystruct.models.edge_feature_graph_crf import EdgeFeatureGraphCRF - print "ONE TYPE TRAINING AND TESTING: PIXELS" + print("ONE TYPE TRAINING AND TESTING: PIXELS") # inference = 'ad3+' # inference = 'qpbo' @@ -416,11 +425,12 @@ def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, na ) Y_train_flat = [y_.ravel() for y_ in Y_train] - print "\ttrain label histogram : ", np.histogram(np.hstack(Y_train_flat), bins=range(NCELL+2)) + print( "\ttrain label histogram : ", + np.histogram(np.hstack(Y_train_flat), bins=range(NCELL+2))) t0 = time.time() ssvm.fit(X_train_edge_features, Y_train_flat) - print "FIT DONE IN %.1fs"%(time.time() - t0) + print("FIT DONE IN %.1fs"%(time.time() - t0)) sys.stdout.flush() t0 = time.time() @@ -429,10 +439,11 @@ def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, na #-------------------------------------------------------------------------------------------------- if True: - print "_"*50 - print "ONE TYPE TRAINING AND TESTING: PICTURES" + print("_"*50) + print("ONE TYPE TRAINING AND TESTING: PICTURES") - print "\ttrain label histogram : ", np.histogram(Y_train_pict, bins=range(3)) + print( "\ttrain label histogram : ", + np.histogram(Y_train_pict, bins=range(3))) lr = LogisticRegression(class_weight='balanced') @@ -442,14 +453,15 @@ def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, na t0 = time.time() mdl.fit(XX, Y_train_pict) - print "FIT DONE IN %.1fs"%(time.time() - t0) + print("FIT DONE IN %.1fs"%(time.time() - t0)) t0 = time.time() _Y_pred = mdl.predict( np.vstack(X_test_pict_feat) ) REPORT([Y_test_pict], _Y_pred, time.time() - t0) #-------------------------------------------------------------------------------------------------- - print "======================================================================================================" + print("===================================================================" + "===================================") # first, train on X with directions only: @@ -459,7 +471,7 @@ def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, na # [10.0/200] + [10.0/200]*10, # [10.0/20 , 10.0/20] # ] -# print "WEIGHTS:", l_weights +# print("WEIGHTS:", l_weights if nbSWAP_Pixel_Pict_TYPES %2 == 0: l_n_states = [NCELL+1, 2] # 11 states for pixel nodes, 2 states for pictures l_n_feat = [45, 7] # 45 features for pixels, 7 for pictures @@ -471,7 +483,7 @@ def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, na ll_n_feat = [[0, 45], [45 , 180]] if not sMODELFILE or not os.path.exists(sMODELFILE): - print " TRAINING MULTI-TYPE MODEL " + print(" TRAINING MULTI-TYPE MODEL ") #TRAINING crf = NodeTypeEdgeFeatureGraphCRF(2, # How many node types? l_n_states, # How many states per type? @@ -480,7 +492,7 @@ def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, na inference_method=INFERENCE # , l_class_weight = l_weights ) - print crf + print(crf) ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=0, max_iter=MAXITER, @@ -489,8 +501,9 @@ def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, na #, switch_to='ad3' ) - print "======================================================================================================" - print "YY[0].shape", Y_train[0].shape + print("===============================================================" + "=======================================") + print("YY[0].shape", Y_train[0].shape) XX, YY = convertToTwoType(X_train, X_train_edge_features, # list of node_feat , edges, edge_feat for pixel nodes Y_train, @@ -506,41 +519,45 @@ def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, na XX, YY = swap_node_types([1,0], [NCELL+1, 2], XX, YY) - print "\tlabel histogram : ", np.histogram( np.hstack([y.ravel() for y in YY]), bins=range(14)) + print( "\tlabel histogram : ", + np.histogram(np.hstack([y.ravel() for y in YY]), + bins=range(14))) - print "YY[0].shape", YY[0].shape + print("YY[0].shape", YY[0].shape) crf.initialize(XX, YY)# check if the data is properly built sys.stdout.flush() t0 = time.time() ssvm.fit(XX, YY) - print "FIT DONE IN %.1fs"%(time.time() - t0) + print("FIT DONE IN %.1fs"%(time.time() - t0)) sys.stdout.flush() ssvm.alphas = None ssvm.constraints_ = None ssvm.inference_cache_ = None if sMODELFILE: - print "Saving model in: ", sMODELFILE + print("Saving model in: ", sMODELFILE) with open(sMODELFILE, "wb") as fd: cPickle.dump(ssvm, fd) else: #REUSE PREVIOUSLY TRAINED MODEL - print " RUSING PREVIOULSLY TRAINED MULTI-TYPE MODEL: ", sMODELFILE + print(" RUSING PREVIOULSLY TRAINED MULTI-TYPE MODEL: ", sMODELFILE) with open(sMODELFILE, "rb") as fd: - ssvm = cPickle.load(fd) + ssvm = pickle.load(fd) - print "INFERENCE WITH ", INFERENCE + print("INFERENCE WITH ", INFERENCE) XX_test, YY_test =convertToTwoType(X_test, X_test_edge_features, # list of node_feat , edges, edge_feat for pixel nodes Y_test, X_test_pict_feat, #a list of picture_node_features Y_test_pict, #a list of integers [0,1] nCell=NCELL) - print "\tlabel histogram (PIXELs and PICTUREs): ", np.histogram( np.hstack([y.ravel() for y in YY_test]), bins=range(14)) + print( "\tlabel histogram (PIXELs and PICTUREs): ", + np.histogram(np.hstack([y.ravel() for y in YY_test]), + bins=range(14))) # l_constraints = listConstraints(XX_test) @@ -549,32 +566,32 @@ def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, na if nbSWAP_Pixel_Pict_TYPES %2 == 1: XX_test, YY_test, l_constraints = swap_node_types([1,0], [NCELL+1, 2], XX_test, YY_test, l_constraints) - print "\t- results without constraints (using %s)"%INFERENCE + print("\t- results without constraints (using %s)"%INFERENCE) t0 = time.time() YY_pred = ssvm.predict( XX_test ) REPORT(YY_test, YY_pred, time.time() - t0) - print "_"*50 - print "\t- results exploiting constraints (using ad3+)" + print("_"*50) + print("\t- results exploiting constraints (using ad3+)") ssvm.model.inference_method = "ad3+" t0 = time.time() YY_pred = ssvm.predict( XX_test, l_constraints ) REPORT(YY_test, YY_pred, time.time() - t0) - print "_"*50 + print("_"*50) if INFERENCE == "ad3": ssvm.model.inference_method = "ad3+" else: ssvm.model.inference_method = "ad3" - print "\t- results without constraints (using %s)"%ssvm.model.inference_method + print("\t- results without constraints (using %s)"%ssvm.model.inference_method) t0 = time.time() YY_pred = ssvm.predict( XX_test ) REPORT(YY_test, YY_pred, time.time() - t0) - print "DONE" + print("DONE") printConfig() diff --git a/examples/plot_hidden_snakes.py b/examples/plot_hidden_snakes.py index b83aa3d1..0e533038 100644 --- a/examples/plot_hidden_snakes.py +++ b/examples/plot_hidden_snakes.py @@ -43,6 +43,8 @@ PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). But it does work as well as Decision Tree Fields ;) """ +from __future__ import (absolute_import, division, print_function) + import numpy as np import matplotlib.pyplot as plt import random @@ -76,11 +78,12 @@ def isSnakePresent(a_hot_picture, nCell=10): break return bSnake -def walkThruSnake(a_hot_picture, (i,j), nCell=10): +def walkThruSnake(a_hot_picture, tIJ, nCell=10): """ Walk thru the snake from I,J Return the list of visited cells (excluding start cell) """ + (i,j) = tIJ lij = list() color_index = np.where(a_hot_picture[i,j,:]==1)[0][0] while len(lij) < nCell -1: @@ -154,8 +157,8 @@ def augmentWithNoSnakeImages(X,Y, name, bOneHot=True, iMult=1, nCell=10): """ return the number of added picture (ADDED AT THE END OF INPUT LISTS) """ - print "ADDING PICTURE WIHOUT SNAKES!!! %d elements in %s"%(len(X), name) - + print("ADDING PICTURE WIHOUT SNAKES!!! %d elements in %s"%(len(X), name)) + X_NoSnake = [] Y_NoSnake = [] for i in range(int(iMult)): @@ -173,7 +176,7 @@ def augmentWithNoSnakeImages(X,Y, name, bOneHot=True, iMult=1, nCell=10): for x,y in zip(X_NoSnake, Y_NoSnake): _x = x if bOneHot else one_hot_colors(x) if isSnakePresent(_x): - print "\t- DISCARDING a shuffled snake which is still a snake!!!!" + print("\t- DISCARDING a shuffled snake which is still a snake!!!!") # if True and not bOneHot: plot_snake(x) else: newX.append(x) @@ -182,7 +185,7 @@ def augmentWithNoSnakeImages(X,Y, name, bOneHot=True, iMult=1, nCell=10): return len(newX), X+newX, Y+newY def shuffle_in_unison(*args): - lTuple = zip(*args) + lTuple = list(zip(*args)) random.shuffle(lTuple) return zip(*lTuple) @@ -215,7 +218,7 @@ def shorten_snakes(lX,lY, N): #if you want to shorten all the snakes #NCELL = 3 NCELL = 10 - print "NCELL=", NCELL + print("NCELL=", NCELL) snakes = load_snakes() @@ -231,7 +234,7 @@ def shorten_snakes(lX,lY, N): X_train_directions, X_train_edge_features = prepare_data(X_train) Y_train_flat = [y_.ravel() for y_ in Y_train] - print "%d picture for training"%len(X_train) + print("%d picture for training"%len(X_train)) # --- TEST X_test, Y_test = snakes['X_test'], snakes['Y_test'] @@ -242,7 +245,7 @@ def shorten_snakes(lX,lY, N): X_test_directions, X_test_edge_features = prepare_data(X_test) Y_test_flat = [y_.ravel() for y_ in Y_test] - print "%d picture for test"%len(X_test) + print("%d picture for test"%len(X_test)) # ------------------------------------------------------------------------------------- @@ -252,7 +255,7 @@ def shorten_snakes(lX,lY, N): # now, use more informative edge features: t0 = time.time() if bClassic: - print "EdgeFeatureGraphCRF" + print("EdgeFeatureGraphCRF") crf = EdgeFeatureGraphCRF(inference_method=inference) ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, #WHY THIS??? max_iter=100, @@ -263,7 +266,7 @@ def shorten_snakes(lX,lY, N): ) ssvm.fit( X_train_edge_features , Y_train_flat) else: - print "NodeTypeEdgeFeatureGraphCRF" + print("NodeTypeEdgeFeatureGraphCRF") crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]], inference_method=inference) ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', @@ -271,7 +274,7 @@ def shorten_snakes(lX,lY, N): #max_iter=100, n_jobs=1) ssvm.fit( convertToSingleTypeX(X_train_edge_features) , Y_train_flat) - print "Training time = %.1fs"%(time.time()-t0) + print("Training time = %.1fs"%(time.time()-t0)) if bClassic: Y_pred2 = ssvm.predict( X_test_edge_features ) @@ -311,11 +314,8 @@ def buildConstraintsFromSingleTyped(X, bOne=True): lC = buildConstraintsFromSingleTyped(X_3, False) Y_pred2 = ssvm.predict( X_3, lC ) print("Results using also input features for edges") - print "Inference with an ATMOST constraint per snake label" + print("Inference with an ATMOST constraint per snake label") print("Test accuracy: %.3f" % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) -""" - -""" \ No newline at end of file diff --git a/examples/plot_snakes.py b/examples/plot_snakes.py index 1acd5f9f..f56f42d5 100644 --- a/examples/plot_snakes.py +++ b/examples/plot_snakes.py @@ -30,8 +30,10 @@ PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). But it does work as well as Decision Tree Fields ;) """ +from __future__ import (absolute_import, division, print_function) + import numpy as np -import matplotlib.pyplot as plt +# import matplotlib.pyplot as plt from sklearn.preprocessing import label_binarize from sklearn.metrics import confusion_matrix, accuracy_score @@ -135,20 +137,20 @@ def prepare_data(X): % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) - if True: - # plot stuff - fig, axes = plt.subplots(2, 2) - axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') - axes[0, 0].set_title('Input') - y = Y_test[0].astype(np.int) - bg = 2 * (y != 0) # enhance contrast - axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) - axes[0, 1].set_title("Ground Truth") - axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 0].set_title("Prediction w/o edge features") - axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 1].set_title("Prediction with edge features") - for a in axes.ravel(): - a.set_xticks(()) - a.set_yticks(()) - plt.show() +# if True: +# # plot stuff +# fig, axes = plt.subplots(2, 2) +# axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') +# axes[0, 0].set_title('Input') +# y = Y_test[0].astype(np.int) +# bg = 2 * (y != 0) # enhance contrast +# axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) +# axes[0, 1].set_title("Ground Truth") +# axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) +# axes[1, 0].set_title("Prediction w/o edge features") +# axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) +# axes[1, 1].set_title("Prediction with edge features") +# for a in axes.ravel(): +# a.set_xticks(()) +# a.set_yticks(()) +# plt.show() diff --git a/examples/plot_snakes_typed.py b/examples/plot_snakes_typed.py index 8d1e0add..92d37189 100644 --- a/examples/plot_snakes_typed.py +++ b/examples/plot_snakes_typed.py @@ -45,8 +45,10 @@ class instead of EdgeFeatureGraphCRF, despite there is only 1 type of nodes. Copyright Xerox """ +from __future__ import (absolute_import, division, print_function) + import numpy as np -import matplotlib.pyplot as plt +# import matplotlib.pyplot as plt from sklearn.preprocessing import label_binarize from sklearn.metrics import confusion_matrix, accuracy_score @@ -77,7 +79,7 @@ def convertToSingleTypeX(X): X_train_directions, X_train_edge_features = prepare_data(X_train) - inference = 'qpbo' + inference = 'ad3+' # first, train on X with directions only: crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[2]], inference_method=inference) ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, @@ -98,7 +100,8 @@ def convertToSingleTypeX(X): # now, use more informative edge features: crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]], inference_method=inference) - ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + # switch_to='ad3', #verbose=1, n_jobs=8) ssvm.fit( convertToSingleTypeX(X_train_edge_features), Y_train_flat) @@ -108,23 +111,23 @@ def convertToSingleTypeX(X): % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) - if False: - # plot stuff - fig, axes = plt.subplots(2, 2) - axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') - axes[0, 0].set_title('Input') - y = Y_test[0].astype(np.int) - bg = 2 * (y != 0) # enhance contrast - axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) - axes[0, 1].set_title("Ground Truth") - axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 0].set_title("Prediction w/o edge features") - axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 1].set_title("Prediction with edge features") - for a in axes.ravel(): - a.set_xticks(()) - a.set_yticks(()) - plt.show() +# if False: +# # plot stuff +# fig, axes = plt.subplots(2, 2) +# axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') +# axes[0, 0].set_title('Input') +# y = Y_test[0].astype(np.int) +# bg = 2 * (y != 0) # enhance contrast +# axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) +# axes[0, 1].set_title("Ground Truth") +# axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) +# axes[1, 0].set_title("Prediction w/o edge features") +# axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) +# axes[1, 1].set_title("Prediction with edge features") +# for a in axes.ravel(): +# a.set_xticks(()) +# a.set_yticks(()) +# plt.show() """ Please be patient. Learning will take 5-20 minutes. From 920afd95a71c37dc91a1551498d72964892c4ef8 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 8 Jan 2018 16:24:08 +0100 Subject: [PATCH 126/155] code ok for Python3 --- pystruct/models/graph_crf.py | 2 +- pystruct/models/latent_graph_crf.py | 2 +- pystruct/models/latent_node_crf.py | 2 +- pystruct/models/node_type_edge_feature_graph_crf.py | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pystruct/models/graph_crf.py b/pystruct/models/graph_crf.py index 81860e90..2bcd4ea2 100644 --- a/pystruct/models/graph_crf.py +++ b/pystruct/models/graph_crf.py @@ -99,7 +99,7 @@ def _set_size_joint_feature(self): self.size_joint_feature = (self.n_states * self.n_features + self.n_states ** 2) else: - self.size_joint_feature = ( + self.size_joint_feature = int( self.n_states * self.n_features + self.n_states * (self.n_states + 1) / 2) diff --git a/pystruct/models/latent_graph_crf.py b/pystruct/models/latent_graph_crf.py index c62788e7..c77e5b69 100644 --- a/pystruct/models/latent_graph_crf.py +++ b/pystruct/models/latent_graph_crf.py @@ -114,7 +114,7 @@ def _set_size_joint_feature(self): "or array-like of length n_labels. Got %s" % str(n_states_per_label)) self.n_states_per_label = n_states_per_label - self.n_states = np.sum(n_states_per_label) + self.n_states = int(np.sum(n_states_per_label)) # compute mapping from latent states to labels ranges = np.cumsum(n_states_per_label) diff --git a/pystruct/models/latent_node_crf.py b/pystruct/models/latent_node_crf.py index 221f9549..94d61673 100644 --- a/pystruct/models/latent_node_crf.py +++ b/pystruct/models/latent_node_crf.py @@ -128,7 +128,7 @@ def _set_size_joint_feature(self): else: n_input_states = self.n_labels self.n_input_states = n_input_states - self.size_joint_feature = (n_input_states * self.n_features + + self.size_joint_feature = int(n_input_states * self.n_features + self.n_states * (self.n_states + 1) / 2) def initialize(self, X, Y): diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py index b842425a..de1e7709 100644 --- a/pystruct/models/node_type_edge_feature_graph_crf.py +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -228,11 +228,11 @@ def _get_pairwise_potentials_initialize(self): i_w, n_states1, i_states1 = 0, 0, 0 - for typ1 in xrange(self.n_types): + for typ1 in range(self.n_types): n_states1 = self.l_n_states[typ1] i_states1_stop = i_states1 + n_states1 n_states2, i_states2 = 0, 0 - for typ2 in xrange(self.n_types): + for typ2 in range(self.n_types): n_features = self.a_n_edge_features[typ1, typ2] n_states2 = self.l_n_states[typ2] i_w_stop = i_w + n_features * n_states1 * n_states2 From 281614b09716756d973f43442af0372ce621908e Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 8 Jan 2018 16:28:32 +0100 Subject: [PATCH 127/155] 0.3.7 --- CHANGELOG | 5 +++++ pystruct/__init__.py | 2 +- requirements.txt | 2 +- setup.py | 2 +- 4 files changed, 8 insertions(+), 3 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 92bc182f..9c601d54 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,8 @@ +0.3.7 +=== +- Making pystruct compatible with Python3 (3.5 actually) +- Making CI happy (but unstable??) + 0.3.6 === - Taking into account Andreas feedback on the PR diff --git a/pystruct/__init__.py b/pystruct/__init__.py index a8d4557d..8879c6c7 100644 --- a/pystruct/__init__.py +++ b/pystruct/__init__.py @@ -1 +1 @@ -__version__ = "0.3.5" +__version__ = "0.3.7" diff --git a/requirements.txt b/requirements.txt index 26125190..267849d0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,4 +3,4 @@ scipy cvxopt Cython>=0.19.1 scikit-learn>=0.11 -ad3>=2.1.2 +ad3>=2.2.2 diff --git a/setup.py b/setup.py index c5b6fc78..a485a3cb 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ include_dirs = [np.get_include()] setup(name="pystruct", - version="0.3.6", + version="0.3.7", install_requires=["ad3", "numpy"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', From f13a01bb70aaf904e0512faf3d8371f9ec50b487 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 8 Jan 2018 17:32:46 +0100 Subject: [PATCH 128/155] all config, now that Py3 works and that Py worked on both ubuntu config and conda2 --- .travis.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 36040444..b0d06ef8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,12 +22,12 @@ virtualenv: system_site_packages: true env: matrix: - #- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="true" + - DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="true" ## ubuntu without opengm - #OK- DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" + - DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" ## This environment tests the newest supported anaconda env - #OK- DISTRIB="conda" PYTHON_VERSION="2.7" - # NUMPY_VERSION="1.13.3" SCIPY_VERSION="0.19.1" + - DISTRIB="conda" PYTHON_VERSION="2.7" OPENGM="false" + NUMPY_VERSION="1.13.3" SCIPY_VERSION="0.19.1" # python3.5 only because of cvxopt? - DISTRIB="conda3" PYTHON_VERSION="3.5" OPENGM="false" NUMPY_VERSION="1.13" SCIPY_VERSION="1.0" From 2553733316beca53255c24e02817d36595158b43 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 9 Jan 2018 09:54:12 +0100 Subject: [PATCH 129/155] why AD3 is not importable?? --- continuous_integration/install.sh | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index 628b1821..418209fd 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -90,16 +90,17 @@ python -c "import scipy; print('scipy %s' % scipy.__version__)" #$PIP install pyqpbo ad3 scikit-learn $PIP install pyqpbo scikit-learn -#get Transkribus/AD3 -#after the PR is validated, use normal AD3 instead! (written Jan 2018) -git clone https://github.com/Transkribus/AD3.git -pushd AD3 -python setup.py install -popd - # Build scikit-learn in the install.sh script to collapse the verbose # build output in the travis output when it succeeds. python --version python -c "import numpy; print('numpy %s' % numpy.__version__)" python -c "import scipy; print('scipy %s' % scipy.__version__)" python setup.py build_ext --inplace + +#get Transkribus/AD3 +#after the PR is validated, use normal AD3 instead! (written Jan 2018) +git clone https://github.com/Transkribus/AD3.git +pushd AD3 +python setup.py install +popd +python -c "import ad3; print(ad3.__version__)" From f663ab86622409c9b540b0af320f9115116fbe9a Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 9 Jan 2018 09:56:04 +0100 Subject: [PATCH 130/155] show ad3 and pystruct versions --- continuous_integration/test_script.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/continuous_integration/test_script.sh b/continuous_integration/test_script.sh index 06246e1a..b6f3a377 100644 --- a/continuous_integration/test_script.sh +++ b/continuous_integration/test_script.sh @@ -11,6 +11,9 @@ set -e python --version python -c "import numpy; print('numpy %s' % numpy.__version__)" python -c "import scipy; print('scipy %s' % scipy.__version__)" +python -c "import ad3; print(ad3.__version__)" +python -c "import pystruct; print(pystruct.__version__)" + python -c "from pystruct.inference import get_installed; print('pystruct inference algorithms: %s' % get_installed())" From 6166a8e25f328b6ca28b626731a91b181e11fb6e Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 9 Jan 2018 11:35:55 +0100 Subject: [PATCH 131/155] AD3 now requires future --- continuous_integration/install.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index 418209fd..13c372e2 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -77,6 +77,7 @@ elif [[ "$DISTRIB" == "ubuntu" ]]; then # Use standard ubuntu packages in their default version # except for cython :-/ $PIP install --user cvxopt + $PIP install --user future # for AD3 fi if [[ "$COVERAGE" == "true" ]]; then From 0683217358796ed4734250fc680395da63687674 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 9 Jan 2018 11:56:03 +0100 Subject: [PATCH 132/155] opengm: make -j2 to try avoiding g++ intermittent bug --- continuous_integration/install.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index 13c372e2..195648ff 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -24,7 +24,7 @@ if [[ "$OPENGM" == "true" ]]; then # old cmake . -DCMAKE_INSTALL_PREFIX=/home/travis/.local -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_EXAMPLES=FALSE -DBUILD_TESTING=FALSE # old make -j2 --quiet cmake . -DCMAKE_INSTALL_PREFIX=/home/travis/.local -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DWITH_AD3=FALSE -DWITH_TRWS=FALSE -DWITH_QPBO=FALSE -DWITH_MRF=FALSE -DWITH_GCO=FALSE -DWITH_CONICBUNDLE=FALSE -DWITH_MAXFLOW=FALSE -DWITH_MAXFLOW_IBFS=FALSE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_COMMANDLINE=FALSE -DCI=TRUE - make -j4 --quiet + make -j1 --quiet make install cd .. fi From 1d01885913bc0b38950e67cf0c34e503535c0ddb Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 9 Jan 2018 12:26:39 +0100 Subject: [PATCH 133/155] OK --- CHANGELOG | 2 +- continuous_integration/install.sh | 2 +- requirements.txt | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 9c601d54..de423a14 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,7 +1,7 @@ 0.3.7 === - Making pystruct compatible with Python3 (3.5 actually) -- Making CI happy (but unstable??) +- Making CI happy 0.3.6 === diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index 195648ff..d74a5574 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -88,7 +88,7 @@ python --version python -c "import numpy; print('numpy %s' % numpy.__version__)" python -c "import scipy; print('scipy %s' % scipy.__version__)" # install our favorite inference packages -#$PIP install pyqpbo ad3 scikit-learn +# Need Transkribus/AD3 for now $PIP install pyqpbo ad3 scikit-learn $PIP install pyqpbo scikit-learn # Build scikit-learn in the install.sh script to collapse the verbose diff --git a/requirements.txt b/requirements.txt index 267849d0..b3ac4911 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ numpy scipy cvxopt +future Cython>=0.19.1 scikit-learn>=0.11 ad3>=2.2.2 From eef4f5aeffca95db9bb5ee78c21ebbf0550cee7f Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 15 Feb 2018 12:40:34 +0100 Subject: [PATCH 134/155] use master of Andre Martins AD3 --- continuous_integration/install.sh | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index d74a5574..83b853b3 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -99,8 +99,7 @@ python -c "import scipy; print('scipy %s' % scipy.__version__)" python setup.py build_ext --inplace #get Transkribus/AD3 -#after the PR is validated, use normal AD3 instead! (written Jan 2018) -git clone https://github.com/Transkribus/AD3.git +git clone https://github.com/andre-martins/AD3 pushd AD3 python setup.py install popd From 3e3bcd5cf08e4d025a52002b73b5a2a7b1ec225b Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 15 Feb 2018 13:28:56 +0100 Subject: [PATCH 135/155] 0.3.8 uses the standard ad3 (after PR merge!!) --- CHANGELOG | 5 +++++ README.md | 25 ++++++++++++++----------- pystruct/__init__.py | 2 +- setup.py | 4 ++-- 4 files changed, 22 insertions(+), 14 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index de423a14..16778e1b 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,8 @@ +0.3.8 +=== +- Use of standard latest ad3 code after PR merge +- update readme accordingly + 0.3.7 === - Making pystruct compatible with Python3 (3.5 actually) diff --git a/README.md b/README.md index 64f6b7f0..3ed5bd97 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ This is a fork from Andreas Mueller's [pystruct](https://github.com/pystruct/pys and prediction library. In particular, pystruct provides a well-documented tool for researchers as well as non-experts to make use of structured prediction algorithms. And the design tries to stay as close as possible to the interface and conventions of [scikit-learn](http://scikit-learn.org). -The goal of the [pystruct+](https://github.com/jlmeunier/pystruct) project and of its companion project [AD3+](https://github.com/Transkribus/AD3) is to extend pystruct along two directions: +The goal of the [pystruct+](https://github.com/jlmeunier/pystruct) project is to extend pystruct along two directions: * **supporting hard-logic constraints when predicting** * **supporting nodes of different nature in CRF graphs** @@ -26,22 +26,25 @@ What is different in pystruct+? You can contact the author on [github](https://github.com/jlmeunier/pystruct). Comments and contributions are welcome. - Developed for the EU project READ. The READ project has received funding - from the European Union's Horizon 2020 research and innovation programme - under grant agreement No 674943. +# Credit to EU READ Project +Developed for the EU project READ. The READ project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. ## Installation -Currently, the offered extensions rely on the __*AD3+*__ solver. For learning I mostly used the __*OneSlackSSVM*__ learner, which requires to install cvxopt as well. +This extension requires **ad3** version 2.2 (so for now, Feb 15th, 2018, you need to get it directly from https://github.com/andre-martins/AD3 ) -### For AD3+: - * get it from https://github.com/Transkribus/AD3 - * install: python setup.py install +The support of hard-logic constraint requires you to choose as solver "ad3+". This is still ad3 code, but working on a binarized graph. -> python setup.py install +For learning I mostly used the __*OneSlackSSVM*__ learner, which requires to install **cvxopt** as well. + +### Python libraries: +> pip install install numpy scipy cvxopt pyqpbo scikit-learn nose pytest -Note: on Windows10 I had trouble with compiling. One dirty workaround then consists in installing the standard AD3, overwritting the python modules with the AD3+ ones -, and changing the version number in the the lib/site-package python folder to 2.1.2. Told you, dirty trick... +### For AD3: + * get it from https://github.com/andre-martins/AD3 + * install it: + +> python setup.py install ### For Pystruct+: * get the source code from https://github.com/jlmeunier/pystruct diff --git a/pystruct/__init__.py b/pystruct/__init__.py index 8879c6c7..4ad67eb7 100644 --- a/pystruct/__init__.py +++ b/pystruct/__init__.py @@ -1 +1 @@ -__version__ = "0.3.7" +__version__ = "0.3.8" diff --git a/setup.py b/setup.py index a485a3cb..a385e076 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ include_dirs = [np.get_include()] setup(name="pystruct", - version="0.3.7", + version="0.3.8", install_requires=["ad3", "numpy"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', @@ -42,6 +42,6 @@ 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.5', ], ) From 661dae9f275f021b6ba38ceba7372b9b10e79cc6 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 20 Feb 2018 13:47:57 +0100 Subject: [PATCH 136/155] Update README.md --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3ed5bd97..116adfd4 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,11 @@ The goal of the [pystruct+](https://github.com/jlmeunier/pystruct) project is to * **supporting hard-logic constraints when predicting** * **supporting nodes of different nature in CRF graphs** -The extension of those 2 projects is 100% ascendant compatible with pystruct. Anything that you did with pystruct works the same way with pystruct+. + By-products of this fork are: + * Python 3 compatibility + * Unit tests passing again + +The extension is 100% ascendant compatible with pystruct. Anything that you did with pystruct works the same way with pystruct+. So you can refer to the pystruct documentation for the API, examples, etc. ( http://pystruct.github.io ) What is different in pystruct+? From ec3f1996ee4f10cd7464355b071dabd74dc6a0bc Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 15 Mar 2018 11:41:37 +0100 Subject: [PATCH 137/155] travis_wait 60 because unbuntu+opengm fails due to test duration --- continuous_integration/test_script.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/continuous_integration/test_script.sh b/continuous_integration/test_script.sh index b6f3a377..387764ee 100644 --- a/continuous_integration/test_script.sh +++ b/continuous_integration/test_script.sh @@ -20,9 +20,9 @@ python -c "from pystruct.inference import get_installed; print('pystruct inferen # Do not use "make test" or "make test-coverage" as they enable verbose mode # which renders travis output too slow to display in a browser. if [[ "$COVERAGE" == "true" ]]; then - nosetests -sv --with-coverage pystruct + travis_wait 60 nosetests -sv --with-coverage pystruct else - nosetests -sv pystruct + travis_wait 60 nosetests -sv pystruct fi make test-doc From 6a26472b645657083a2386040424b97d8ce051f1 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 15 Mar 2018 13:17:53 +0100 Subject: [PATCH 138/155] test_script.sh: line 25: travis_wait: command not found :-/ --- continuous_integration/test_script.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/continuous_integration/test_script.sh b/continuous_integration/test_script.sh index 387764ee..b6f3a377 100644 --- a/continuous_integration/test_script.sh +++ b/continuous_integration/test_script.sh @@ -20,9 +20,9 @@ python -c "from pystruct.inference import get_installed; print('pystruct inferen # Do not use "make test" or "make test-coverage" as they enable verbose mode # which renders travis output too slow to display in a browser. if [[ "$COVERAGE" == "true" ]]; then - travis_wait 60 nosetests -sv --with-coverage pystruct + nosetests -sv --with-coverage pystruct else - travis_wait 60 nosetests -sv pystruct + nosetests -sv pystruct fi make test-doc From b27b1c7cbb4307b7f544f39f116cd051a47b2d78 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 22 Mar 2018 17:44:43 +0100 Subject: [PATCH 139/155] wrond description of a_n_edge_features of NodeTypeEdgeFeatureGraphCRF (Thanks to Animesh) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 116adfd4..41a34647 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,7 @@ You need now to define the number of node types and the number of features per t , n_types #how many node type? , l_n_states #how many labels per node type? , l_n_features #how many features per node type? - , a_n_edge_features #how many features per edge type? (array-like) shape=(n_type, n_type, n_feature_per_type_pair) + , a_n_edge_features #how many features per edge type? (array-like) shape=(n_type, n_type) -> n_feature_per_type_pair , inference_method="ad3" , l_class_weight=None): #class_weight per node type or None or None From 0fbaeddd447683976f924df6a0c8b8b3e57147dd Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 9 Apr 2018 16:07:48 +0200 Subject: [PATCH 140/155] Update README.md --- README.md | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 41a34647..4dd6d09d 100644 --- a/README.md +++ b/README.md @@ -7,18 +7,15 @@ # PyStruct+ -This is a fork from Andreas Mueller's [pystruct](https://github.com/pystruct/pystruct) project, which is an easy-to-use structured learning - and prediction library. In particular, pystruct provides a well-documented tool for researchers as well as non-experts to make use of structured - prediction algorithms. And the design tries to stay as close as possible to the interface and conventions of [scikit-learn](http://scikit-learn.org). +This fork of Andreas Mueller's [pystruct](https://github.com/pystruct/pystruct) project aims at: +- supporting **Python3** +- doing **SW maintenance** (e.g. unit tests are passing) +- providing **2 extensions:** + - **supporting nodes of different nature in CRF graphs** + - **supporting hard-logic constraints when predicting** + +Pystruct is an easy-to-use structured learning and prediction library. In particular, pystruct provides a well-documented tool for researchers as well as non-experts to make use of structured prediction algorithms. And the design tries to stay as close as possible to the interface and conventions of [scikit-learn](http://scikit-learn.org). -The goal of the [pystruct+](https://github.com/jlmeunier/pystruct) project is to extend pystruct along two directions: - * **supporting hard-logic constraints when predicting** - * **supporting nodes of different nature in CRF graphs** - - By-products of this fork are: - * Python 3 compatibility - * Unit tests passing again - The extension is 100% ascendant compatible with pystruct. Anything that you did with pystruct works the same way with pystruct+. So you can refer to the pystruct documentation for the API, examples, etc. ( http://pystruct.github.io ) @@ -35,7 +32,7 @@ Developed for the EU project READ. The READ project has received funding from t ## Installation -This extension requires **ad3** version 2.2 (so for now, Feb 15th, 2018, you need to get it directly from https://github.com/andre-martins/AD3 ) +This extension requires **ad3** latest version (so for now, Feb 15th, 2018, you need to get it directly from https://github.com/andre-martins/AD3 ) The support of hard-logic constraint requires you to choose as solver "ad3+". This is still ad3 code, but working on a binarized graph. From 0092f37c74d1ff0cde64edadd41191bd2ae17cf6 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 9 Apr 2018 16:10:54 +0200 Subject: [PATCH 141/155] update --- setup.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index a385e076..7e61079f 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ 'pystruct.tests.test_models', 'pystruct.tests.test_inference', 'pystruct.tests.test_utils'], include_package_data=True, - description="Structured Learning and Prediction in Python", + description="https://github.com/jlmeunier/pystruct Structured Learning and Prediction in Python. ", author="Andreas Mueller", author_email="t3kcit@gmail.com", url="http://pystruct.github.io", @@ -39,9 +39,8 @@ 'Operating System :: Unix', 'Operating System :: MacOS', 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', ], ) From 8a8d34c61cf2fad2ecee0b72343e67b56d25f2a5 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 9 Apr 2018 16:31:23 +0200 Subject: [PATCH 142/155] cosmetic --- setup.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 7e61079f..8f5f1bb7 100644 --- a/setup.py +++ b/setup.py @@ -3,12 +3,19 @@ import numpy as np import os +from os import path +import io if os.path.exists('MANIFEST'): os.remove('MANIFEST') +here = path.abspath(path.dirname(__file__)) include_dirs = [np.get_include()] +# Get the long description from the README file +with io.open(path.join(here, 'README.md'), encoding='utf-8') as f: + long_description = f.read() + setup(name="pystruct", version="0.3.8", install_requires=["ad3", "numpy"], @@ -18,10 +25,12 @@ 'pystruct.tests.test_models', 'pystruct.tests.test_inference', 'pystruct.tests.test_utils'], include_package_data=True, - description="https://github.com/jlmeunier/pystruct Structured Learning and Prediction in Python. ", + description="Structured Learning and Prediction in Python", + long_description=long_description, + long_description_content_type='text/markdown', author="Andreas Mueller", author_email="t3kcit@gmail.com", - url="http://pystruct.github.io", + url="https://github.com/jlmeunier/pystruct", license="BSD 2-clause", use_2to3=True, ext_modules=[Extension("pystruct.models.utils", ["src/utils.c"], From d5d77ded4392e838fc24889816a50d1a1e36df35 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Mon, 9 Apr 2018 16:47:40 +0200 Subject: [PATCH 143/155] package renamed py3struct --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 8f5f1bb7..44edebfc 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ with io.open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() -setup(name="pystruct", +setup(name="py3struct", version="0.3.8", install_requires=["ad3", "numpy"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', From 2f0aaac61aed088dd072f748ea33d59763630de5 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 19 Jul 2018 14:32:09 +0200 Subject: [PATCH 144/155] 0.3RC1 --- CHANGELOG | 38 +- README.md | 166 +- READ_Contribution.md | 123 ++ .../logs/plot_hidden_short_snakes_typed.log | 327 ---- examples/logs/plot_hidden_snakes.log | 58 - examples/logs/plot_snakes.log | 69 - examples/logs/plot_snakes_constraints.log | 97 -- examples/logs/plot_snakes_typed.log | 1476 ----------------- pystruct/__init__.py | 2 +- setup.py | 2 +- 10 files changed, 149 insertions(+), 2209 deletions(-) create mode 100644 READ_Contribution.md delete mode 100644 examples/logs/plot_hidden_short_snakes_typed.log delete mode 100644 examples/logs/plot_hidden_snakes.log delete mode 100644 examples/logs/plot_snakes.log delete mode 100644 examples/logs/plot_snakes_constraints.log delete mode 100644 examples/logs/plot_snakes_typed.log diff --git a/CHANGELOG b/CHANGELOG index 16778e1b..1440dcf0 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,38 +1,8 @@ -0.3.8 -=== -- Use of standard latest ad3 code after PR merge -- update readme accordingly - -0.3.7 -=== -- Making pystruct compatible with Python3 (3.5 actually) -- Making CI happy - -0.3.6 -=== -- Taking into account Andreas feedback on the PR - -0.3.5 -=== -- Few fixes -- all tests are passing - -0.3.4 -=== -- MIT license -- all tests are passing except test_latent_node_crf_learning.py (as in 0.2.4) - - -0.3.3 -=== -- ad3 now supports the NodeTypeEdgeFeatureGraphCRF model -- ad3+ required only for hard logic constraints -- smaller memory footprint than 0.3 - -0.3 -=== +0.3.1 +===== - Added new model NodeTypeEdgeFeatureGraphCRF -- Added inference method ad3+ for new model and for supporting hard logic constraints in other CRF models +- all tests are passing, CIok +- Python3 compatibility 0.3 === diff --git a/README.md b/README.md index 4dd6d09d..49471dea 100644 --- a/README.md +++ b/README.md @@ -1,161 +1,35 @@ - -[![Build Status](https://travis-ci.org/jlmeunier/pystruct.png)](https://travis-ci.org/jlmeunier/pystruct) +[![Build Status](https://travis-ci.org/pystruct/pystruct.png)](https://travis-ci.org/pystruct/pystruct) [![pypi version](http://img.shields.io/pypi/v/pystruct.svg?style=flat)](https://pypi.python.org/pypi/pystruct/) [![licence](http://img.shields.io/badge/licence-BSD-blue.svg?style=flat)](https://github.com/pystruct/pystruct/blob/master/LICENSE) [![DOI](https://zenodo.org/badge/21369/pystruct/pystruct.svg)](https://zenodo.org/badge/latestdoi/21369/pystruct/pystruct) -# PyStruct+ -This fork of Andreas Mueller's [pystruct](https://github.com/pystruct/pystruct) project aims at: -- supporting **Python3** -- doing **SW maintenance** (e.g. unit tests are passing) -- providing **2 extensions:** - - **supporting nodes of different nature in CRF graphs** - - **supporting hard-logic constraints when predicting** - -Pystruct is an easy-to-use structured learning and prediction library. In particular, pystruct provides a well-documented tool for researchers as well as non-experts to make use of structured prediction algorithms. And the design tries to stay as close as possible to the interface and conventions of [scikit-learn](http://scikit-learn.org). - -The extension is 100% ascendant compatible with pystruct. Anything that you did with pystruct works the same way with pystruct+. -So you can refer to the pystruct documentation for the API, examples, etc. ( http://pystruct.github.io ) - -What is different in pystruct+? - * the __*predict*__ method accepts now an optional constraint parameter - * a new CRF model is proposed, __*NodeTypeEdgeFeatureGraphCRF*__ - - More details are given in next sections. - - You can contact the author on [github](https://github.com/jlmeunier/pystruct). Comments and contributions are welcome. - -# Credit to EU READ Project -Developed for the EU project READ. The READ project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. - - -## Installation -This extension requires **ad3** latest version (so for now, Feb 15th, 2018, you need to get it directly from https://github.com/andre-martins/AD3 ) - -The support of hard-logic constraint requires you to choose as solver "ad3+". This is still ad3 code, but working on a binarized graph. - -For learning I mostly used the __*OneSlackSSVM*__ learner, which requires to install **cvxopt** as well. - -### Python libraries: -> pip install install numpy scipy cvxopt pyqpbo scikit-learn nose pytest - -### For AD3: - * get it from https://github.com/andre-martins/AD3 - * install it: - -> python setup.py install - -### For Pystruct+: - * get the source code from https://github.com/jlmeunier/pystruct - * compile and install: - -> python setup.py install - -## Tests -To test your install, run the test of the new CRF model: -> python pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py - -(You should see a "OK" displayed at the end of the script execution.) - -## Example -Building on the [Snakes](https://pystruct.github.io/auto_examples/plot_snakes.html#sphx-glr-auto-examples-plot-snakes-py) example, there is now a new example called "HiddenSnakes". (Code in examples/plot_hidden_short_snakes_typed.py ) - -The idea is that some picture do not contain any snake despite 10 pixels have a Snake body colour. Why? Because they do not form a valid 10-long snake, as 1 pixel has a wrong colour destroying the continuity of the snake. - -The original task remains but is more difficult: some non-blue pixels are now labelled 'background'. An additional task consists in labeling the picture as Snake or NoSnake. - -This double task is solved by the use of an additional type of node that represents the picture itself, with 7 simplistic features. There are additional edges, from each pixel to the picture node. That's all. And it improves a lot from the results of the *EdgeFeatureGraphCRF*-based model. - -In addition, we injected some more domain knowledge to illustrate the use of the hard logic constraints. In this case we enforce *at most one pixel of label L per picture, for L in [1, 10]*. This gives an extra accuracy bonus. - -## Prediction with Hard-Logic Constraints - -You can now pass a __list of logical constraints__ to the predict method, with a *constraints=* named parameter. - - Each constraint is tuple like *( operator, nodes, labels, negated )* - where: - - *operator* is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' - - *nodes* is the list of the index of each node involved in this constraint - - *labels* is the list of node label. If the labels are the same for all nodes, you can pass it directly as a scalar value. - - *negated* is a list of boolean indicating if the corresponding argument must be negated. Again, if all values are the same, pass a single boolean value instead of a list. - -The operators whose name ends with 'OUT' impose that the operator applied on the all-but-last arguments yields the truth value of the last one. ->For instance XOROUT(a,b,c) <=> XOR(a,b) = c - -When used jointly with the new *NodeTypeEdgeFeatureGraphCRF* model, the structure of the constraints list slightly differs. See in next section. - - -## CRF Graph with Nodes of Different Nature -Pystruct CRF graphs assumes that the nodes of the graph all have the same nature. In consequence, all nodes share the same weights and the same set of possible labels. Similarly, all edges have the same nature and share the same edge weights. -This was a limitation with regards to our needs (for a Document Understanding task). So we propose a new CRF model called *NodeTypeEdgeFeatureGraphCRF*. - -*NodeTypeEdgeFeatureGraphCRF* supports multiple node of multiple nature, which we call **node types**. Each type has its own weights and own set of possible labels. Similarly, edges have different nature depending on the type of their sources and target-nodes. In a graph with N types, there are N^2 types of edges. - -*NodeTypeEdgeFeatureGraphCRF* generalizes *EdgeFeatureGraphCRF*, so edges have features. NOTE: I think that you can mimics the absence opf feature on edges (as in *GraphCRF* model) by specifying one feature per edge, whose value is 1 for all edges. - -**This extension has an impact on:** - * the constructor - * the structure of the label weights, if not uniform - * the structure of the Xs - * the values in Ys - * the structure of the optional constraint list at prediction - -### Class Constructor -You need now to define the number of node types and the number of features per type (of node, and of edge) when instantiating *NodeTypeEdgeFeatureGraphCRF*. - - def __init__(self - , n_types #how many node type? - , l_n_states #how many labels per node type? - , l_n_features #how many features per node type? - , a_n_edge_features #how many features per edge type? (array-like) shape=(n_type, n_type) -> n_feature_per_type_pair - , inference_method="ad3" - , l_class_weight=None): #class_weight per node type or None or None - - -### Xs and Ys -In single type CRF, like *EdgeFeatureGraphCRF*, an instance *X* is represented as a tuple - - (*node_features*, *edges*, *edge_features*) representing the graph. - -* *node_feature*s is of shape (*n_node*, *n_features*) -* *edges* is an array of shape (*n_edges*, 2) -* *edge_features* is of shape (*n_edges*, *n_edge_features*) - - Labels y are given as array of shape (*n_nodes*,) +PyStruct +======== -In multiple type graphs, with *_n_types* types, an instance *X* is represented as a tuple +PyStruct aims at being an easy-to-use structured learning and prediction library. +Currently it implements only max-margin methods and a perceptron, but other algorithms +might follow. - (*l_node_features*, *l_edges*, *l_edge_features*) representing the graph. -* *l_node_feature*s is a list of length *n_types* containing arrays of shape (*n_typ_node*, *n_typ_features*), where *n_typ_node* is the number of nodes of that type, while *n_typ_features* is the number of features for this type of nodes. -* *l_edges* is a list of length *n_types*^2 . Each of its elements contains an array of shape (*n_typ_edge, 2) defining the edges from nodes of type *i* to nodes of type *j*, with *i* and *j* in [0, *n_types*-1], *j* being the secondary index (inner loop). The index of the nodes in each type starts at 0. -* *l_edge_features* is a list of length *n_types*^2. It contains the features of the edges for each pair of types, in same order as in previous parameter. Each item is an array of shape (*n_typ_edges*, *n_typ_edge_features*). if *n_typ_edge_features* is 0, then *n_typ_edges* should be 0 as well for all instances of graph! If you want an edge without features, set *n_typ_edge_features* to 1 and pass 1.0 as feature for all edges (of that type). +The goal of PyStruct is to provide a well-documented tool for researchers as well as non-experts +to make use of structured prediction algorithms. +The design tries to stay as close as possible to the interface and conventions +of [scikit-learn](http://scikit-learn.org). -Each *Y* remains a vector array. While the label could start at 0 for all types, we have chosen not to do so. (Essentially,to make clear that types do not blend into each other, which is clear when you show a confusion matrix). So the labels of the first type start at 0, while labels of next type starts right after the value of the last label of previous type. -*NodeTypeEdgeFeatureGraphCRF* provides 2 convenience methods: -* *flattenY*( [ [2,0,0], [3,3,4] ] ) --> [ 2,0,0, 5,5,7] (assuming type 0 has 3 labels) -* *unflattenY*(Xs, [ 2,0,0, 5,5,7] ) --> [ [2,0,0], [3,3,4] ] (you'll also need to pass the Xs) +You can install pystruct using -### Constraints on Multitype Graphs -As for the Xs and Ys, the constraint must be partitioned by type. +> pip install pystruct - The constraints must be a list of tuples like: - -Either +Some of the functionality (namely OneSlackSSVM and NSlackSSVM) requires that cvxopt is installed. +See the [installation instructions](http://pystruct.github.io/intro.html) for more details. - ( *operator*, *l_nodes*, *l_labels*, *l_negated* ) - with operator being one 'XOR' 'ATMOSTONE' 'OR' +The full documentation and installation instructions can be found at the website: +http://pystruct.github.io -Or +You can contact the authors either via the [mailing list](https://groups.google.com/forum/#!forum/pystruct) +or on [github](https://github.com/pystruct/pystruct). - ( *operator*, *l_nodes*, *l_labels*, *l_negated* , (*type*, *node*, *label*, *negated*)) - with operator being one 'XOROUT' 'OROUT' 'ANDOUT' 'IMPLY' - -- *l_nodes* is a list of nodes per type. Each item is a list of the index of the node of that type involved in this constraint -- *l_labels* is a list of labels per type. Each item is a list of the label of the involved node. If the labels are all the same for a type, you can pass it directly as a scalar value. -- *l_negate*d is a list of "negated" per type. Each item is a list of booleans indicating if the node must be negated. Again, if all values are the same for a type, pass a single boolean value instead of a list +Currently the project is mostly maintained by Andreas Mueller, but contributions are very welcome. -- the last (*type*, *nod*e, *label*, *negated*) allows to refer to the outcome of an 'OUT' operator. - - +Jean-Luc Meunier (Naver Labs Europe) contributed a new model and did some maintenance, in the course of the EU READ project. See [READ_Contribution.md](https://github.com/pystruct/pystruct/blob/master/READ_Contribution.md) diff --git a/READ_Contribution.md b/READ_Contribution.md new file mode 100644 index 00000000..c7a4f537 --- /dev/null +++ b/READ_Contribution.md @@ -0,0 +1,123 @@ +# Contribution by EU READ Project +During the course of the EU READ project, Naver Labs Europe made two contributions to the pystruct and AD3 projects: + - **supporting nodes of different nature in CRF graphs** + - **supporting hard-logic constraints when predicting** + +In practice: + * a new CRF model is proposed, __*NodeTypeEdgeFeatureGraphCRF*__ + * the __*predict*__ method accepts now an optional constraint parameter + + More details are given in next sections. + + You can contact the author at jean-luc.meunier@naverlabs.com + + +## Credit +Developed for the EU project READ. The READ project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. + +## Tests +To test your install, run the test of the new CRF model: +> python pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py + +(You should see a "OK" displayed at the end of the script execution.) + +## Example +Building on the [Snakes](https://pystruct.github.io/auto_examples/plot_snakes.html#sphx-glr-auto-examples-plot-snakes-py) example, there is now a new example called "HiddenSnakes". (Code in examples/plot_hidden_short_snakes_typed.py ) + +The idea is that some picture do not contain any snake despite 10 pixels have a Snake body colour. Why? Because they do not form a valid 10-long snake, as 1 pixel has a wrong colour destroying the continuity of the snake. + +The original task remains but is more difficult: some non-blue pixels are now labelled 'background'. An additional task consists in labeling the picture as Snake or NoSnake. + +This double task is solved by the use of an additional type of node that represents the picture itself, with 7 simplistic features. There are additional edges, from each pixel to the picture node. That's all. And it improves a lot from the results of the *EdgeFeatureGraphCRF*-based model. + +In addition, we injected some more domain knowledge to illustrate the use of the hard logic constraints. In this case we enforce *at most one pixel of label L per picture, for L in [1, 10]*. This gives an extra accuracy bonus. + +## Prediction with Hard-Logic Constraints + +You can now pass a __list of logical constraints__ to the predict method, with a *constraints=* named parameter. + + Each constraint is tuple like *( operator, nodes, labels, negated )* + where: + - *operator* is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - *nodes* is the list of the index of each node involved in this constraint + - *labels* is the list of node label. If the labels are the same for all nodes, you can pass it directly as a scalar value. + - *negated* is a list of boolean indicating if the corresponding argument must be negated. Again, if all values are the same, pass a single boolean value instead of a list. + +The operators whose name ends with 'OUT' impose that the operator applied on the all-but-last arguments yields the truth value of the last one. +>For instance XOROUT(a,b,c) <=> XOR(a,b) = c + +When used jointly with the new *NodeTypeEdgeFeatureGraphCRF* model, the structure of the constraints list slightly differs. See in next section. + + +## CRF Graph with Nodes of Different Nature +Pystruct CRF graphs assumes that the nodes of the graph all have the same nature. In consequence, all nodes share the same weights and the same set of possible labels. Similarly, all edges have the same nature and share the same edge weights. +This was a limitation with regards to our needs (for a Document Understanding task). So we propose a new CRF model called *NodeTypeEdgeFeatureGraphCRF*. + +*NodeTypeEdgeFeatureGraphCRF* supports multiple node of multiple nature, which we call **node types**. Each type has its own weights and own set of possible labels. Similarly, edges have different nature depending on the type of their sources and target-nodes. In a graph with N types, there are N^2 types of edges. + +*NodeTypeEdgeFeatureGraphCRF* generalizes *EdgeFeatureGraphCRF*, so edges have features. NOTE: I think that you can mimics the absence opf feature on edges (as in *GraphCRF* model) by specifying one feature per edge, whose value is 1 for all edges. + +**This extension has an impact on:** + * the constructor + * the structure of the label weights, if not uniform + * the structure of the Xs + * the values in Ys + * the structure of the optional constraint list at prediction + +### Class Constructor +You need now to define the number of node types and the number of features per type (of node, and of edge) when instantiating *NodeTypeEdgeFeatureGraphCRF*. + + def __init__(self + , n_types #how many node type? + , l_n_states #how many labels per node type? + , l_n_features #how many features per node type? + , a_n_edge_features #how many features per edge type? (array-like) shape=(n_type, n_type) -> n_feature_per_type_pair + , inference_method="ad3" + , l_class_weight=None): #class_weight per node type or None or None + + +### Xs and Ys +In single type CRF, like *EdgeFeatureGraphCRF*, an instance *X* is represented as a tuple + + (*node_features*, *edges*, *edge_features*) representing the graph. + +* *node_feature*s is of shape (*n_node*, *n_features*) +* *edges* is an array of shape (*n_edges*, 2) +* *edge_features* is of shape (*n_edges*, *n_edge_features*) + + Labels y are given as array of shape (*n_nodes*,) + +In multiple type graphs, with *_n_types* types, an instance *X* is represented as a tuple + + (*l_node_features*, *l_edges*, *l_edge_features*) representing the graph. +* *l_node_feature*s is a list of length *n_types* containing arrays of shape (*n_typ_node*, *n_typ_features*), where *n_typ_node* is the number of nodes of that type, while *n_typ_features* is the number of features for this type of nodes. +* *l_edges* is a list of length *n_types*^2 . Each of its elements contains an array of shape (*n_typ_edge, 2) defining the edges from nodes of type *i* to nodes of type *j*, with *i* and *j* in [0, *n_types*-1], *j* being the secondary index (inner loop). The index of the nodes in each type starts at 0. +* *l_edge_features* is a list of length *n_types*^2. It contains the features of the edges for each pair of types, in same order as in previous parameter. Each item is an array of shape (*n_typ_edges*, *n_typ_edge_features*). if *n_typ_edge_features* is 0, then *n_typ_edges* should be 0 as well for all instances of graph! If you want an edge without features, set *n_typ_edge_features* to 1 and pass 1.0 as feature for all edges (of that type). + +Each *Y* remains a vector array. While the label could start at 0 for all types, we have chosen not to do so. (Essentially,to make clear that types do not blend into each other, which is clear when you show a confusion matrix). So the labels of the first type start at 0, while labels of next type starts right after the value of the last label of previous type. +*NodeTypeEdgeFeatureGraphCRF* provides 2 convenience methods: +* *flattenY*( [ [2,0,0], [3,3,4] ] ) --> [ 2,0,0, 5,5,7] (assuming type 0 has 3 labels) +* *unflattenY*(Xs, [ 2,0,0, 5,5,7] ) --> [ [2,0,0], [3,3,4] ] (you'll also need to pass the Xs) + +### Constraints on Multitype Graphs +As for the Xs and Ys, the constraint must be partitioned by type. + + The constraints must be a list of tuples like: + +Either + + ( *operator*, *l_nodes*, *l_labels*, *l_negated* ) + with operator being one 'XOR' 'ATMOSTONE' 'OR' + +Or + + ( *operator*, *l_nodes*, *l_labels*, *l_negated* , (*type*, *node*, *label*, *negated*)) + with operator being one 'XOROUT' 'OROUT' 'ANDOUT' 'IMPLY' + +- *l_nodes* is a list of nodes per type. Each item is a list of the index of the node of that type involved in this constraint +- *l_labels* is a list of labels per type. Each item is a list of the label of the involved node. If the labels are all the same for a type, you can pass it directly as a scalar value. +- *l_negate*d is a list of "negated" per type. Each item is a list of booleans indicating if the node must be negated. Again, if all values are the same for a type, pass a single boolean value instead of a list + +- the last (*type*, *nod*e, *label*, *negated*) allows to refer to the outcome of an 'OUT' operator. + + diff --git a/examples/logs/plot_hidden_short_snakes_typed.log b/examples/logs/plot_hidden_short_snakes_typed.log deleted file mode 100644 index acddde7c..00000000 --- a/examples/logs/plot_hidden_short_snakes_typed.log +++ /dev/null @@ -1,327 +0,0 @@ -== NCELL= 10 -== FIXED_SEED= True -== INFERENCE = ad3+ -== N_JOBS = 8 -== SWAP= 0 -== EASY= False -== MAX_ITER= 750 -== MODEL FILE= model.pkl -Please be patient... -TRAIN SET 200 200 -ADDING PICTURE WIHOUT SNAKES!!! 200 elements in train - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! -TRAIN SET 376 376 -ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! -TEST SET 187 187 -====================================================================================================== -ONE TYPE TRAINING AND TESTING: PIXELS - train label histogram : (array([12198, 200, 200, 200, 200, 200, 200, 200, 200, - 200, 200]), array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])) -FIT DONE IN 312.4s - ( predict DONE IN 1.4s) -[[5633 37 37 39 37 38 32 29 37 47 49] - [ 14 85 1 0 0 0 0 0 0 0 0] - [ 13 0 85 1 0 0 0 0 0 1 0] - [ 12 0 0 82 1 3 1 1 0 0 0] - [ 12 0 0 0 79 1 7 1 0 0 0] - [ 11 2 0 2 1 77 0 6 1 0 0] - [ 9 0 3 1 2 1 79 0 5 0 0] - [ 9 0 0 3 1 2 1 81 0 3 0] - [ 8 0 0 0 3 1 2 1 84 0 1] - [ 9 0 0 0 0 3 1 2 1 84 0] - [ 7 0 0 0 0 0 3 1 1 1 87]] - trace = 6456 - Accuracy= 0.920 -__________________________________________________ -ONE TYPE TRAINING AND TESTING: PICTURES - train label histogram : (array([176, 200]), array([0, 1, 2])) -FIT DONE IN 0.0s - ( predict DONE IN 0.0s) -[[30 57] - [47 53]] - trace = 83 - Accuracy= 0.444 -====================================================================================================== - TRAINING MULTI-TYPE MODEL -NodeTypeEdgeFeatureGraphCRF(n_states: [11, 2], inference_method: ad3+, n_features: [45, 7], n_edge_features: [[180 45] - [ 45 0]]) -====================================================================================================== -YY[0].shape (6, 6) - label histogram : (array([12198, 200, 200, 200, 200, 200, 200, 200, 200, - 200, 200, 176, 200]), array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])) -YY[0].shape (37,) -FIT DONE IN 1344.1s -Saving model in: model.pkl -INFERENCE WITH ad3+ - label histogram (PIXELs and PICTUREs): (array([6015, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, - 87, 100]), array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])) - - results without constraints - ( predict DONE IN 9.8s) -[[5739 30 33 32 24 23 23 20 28 31 32 0 0] - [ 5 93 2 0 0 0 0 0 0 0 0 0 0] - [ 3 0 91 2 0 0 2 0 1 1 0 0 0] - [ 4 0 0 89 2 0 0 3 1 1 0 0 0] - [ 4 0 2 0 86 3 3 0 2 0 0 0 0] - [ 4 2 0 3 0 82 2 5 1 1 0 0 0] - [ 4 0 4 1 3 0 82 2 3 0 1 0 0] - [ 4 0 0 4 1 3 1 84 1 2 0 0 0] - [ 3 0 0 0 4 1 2 1 88 1 0 0 0] - [ 3 0 0 0 0 4 1 4 1 86 1 0 0] - [ 3 0 0 1 0 0 5 1 1 1 88 0 0] - [ 0 0 0 0 0 0 0 0 0 0 0 60 27] - [ 0 0 0 0 0 0 0 0 0 0 0 3 97]] - trace = 6765 - Accuracy= 0.939 -__________________________________________________ - - results exploiting constraints - ( predict DONE IN 13.7s) -[[5735 29 30 30 27 29 28 26 24 29 28 0 0] - [ 9 91 0 0 0 0 0 0 0 0 0 0 0] - [ 9 0 91 0 0 0 0 0 0 0 0 0 0] - [ 9 0 0 91 0 0 0 0 0 0 0 0 0] - [ 9 0 0 0 91 0 0 0 0 0 0 0 0] - [ 9 0 0 0 0 91 0 0 0 0 0 0 0] - [ 9 0 0 0 0 0 91 0 0 0 0 0 0] - [ 9 0 0 0 0 0 0 91 0 0 0 0 0] - [ 9 0 0 0 0 0 0 0 91 0 0 0 0] - [ 9 0 0 0 0 0 0 0 0 91 0 0 0] - [ 9 0 0 0 0 0 0 0 0 0 91 0 0] - [ 0 0 0 0 0 0 0 0 0 0 0 57 30] - [ 0 0 0 0 0 0 0 0 0 0 0 9 91]] - trace = 6793 - Accuracy= 0.943 -__________________________________________________ -INFERENCE WITH ad3 - Y is BAD, FIXING IT AT RANDOM -array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11]) - ( predict DONE IN 3.1s) -[[5743 25 30 30 26 26 24 22 29 30 30 0 0] - [ 6 92 2 0 0 0 0 0 0 0 0 0 0] - [ 4 0 91 2 0 0 1 0 1 1 0 0 0] - [ 5 0 0 89 2 0 0 2 1 1 0 0 0] - [ 5 0 2 0 84 3 3 0 3 0 0 0 0] - [ 5 2 0 3 0 80 3 5 0 2 0 0 0] - [ 5 0 4 1 3 0 80 2 3 0 2 0 0] - [ 5 0 0 4 1 3 1 83 1 2 0 0 0] - [ 5 0 0 0 4 1 2 1 86 1 0 0 0] - [ 5 0 0 0 0 4 1 4 1 84 1 0 0] - [ 5 0 0 1 0 0 5 1 1 1 86 0 0] - [ 0 0 0 0 0 0 0 0 0 0 0 61 26] - [ 0 0 0 0 0 0 0 0 0 0 0 5 95]] - trace = 6754 - Accuracy= 0.938 -DONE -== NCELL= 10 -== FIXED_SEED= True -== INFERENCE = ad3+ -== N_JOBS = 8 -== SWAP= 0 -== EASY= False -== MAX_ITER= 750 -== MODEL FILE= model.pkl - - - ================================================================================= - After fixing prepare_data: - Oct 9 2017 - - edge_features[:len(right), :, 0] = features[right[:, 0]] - edge_features[:len(right), :, 1] = features[right[:, 1]] -#ORIG -# edge_features[len(right):, :, 0] = features[down[:, 0]] -# edge_features[len(right):, :, 1] = features[down[:, 1]] - edge_features[len(right):, :, 2] = features[down[:, 0]] - edge_features[len(right):, :, 3] = features[down[:, 1]] - - -== NCELL= 10 -== FIXED_SEED= True -== INFERENCE = ad3 -== N_JOBS = 8 -== SWAP= 0 -== EASY= False -== MAX_ITER= 750 -== MODEL FILE= model.pkl -Please be patient... -TRAIN SET 200 200 -ADDING PICTURE WIHOUT SNAKES!!! 200 elements in train - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! -TRAIN SET 376 376 -ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! -TEST SET 187 187 -====================================================================================================== -ONE TYPE TRAINING AND TESTING: PIXELS - train label histogram : (array([12198, 200, 200, 200, 200, 200, 200, 200, 200, - 200, 200], dtype=int64), array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])) -FIT DONE IN 1340.7s - ( predict DONE IN 14.0s) -[[5605 37 37 37 33 32 35 38 49 56 56] - [ 14 86 0 0 0 0 0 0 0 0 0] - [ 13 0 85 2 0 0 0 0 0 0 0] - [ 11 0 2 85 2 0 0 0 0 0 0] - [ 11 0 0 2 85 2 0 0 0 0 0] - [ 10 0 0 0 2 85 2 1 0 0 0] - [ 10 0 1 0 0 2 85 2 0 0 0] - [ 9 0 0 1 0 0 2 86 2 0 0] - [ 7 0 0 0 1 0 0 2 87 2 1] - [ 8 1 0 0 0 1 0 0 1 87 2] - [ 10 0 1 0 0 0 1 0 0 0 88]] - trace = 6464 - Accuracy= 0.921 -__________________________________________________ -ONE TYPE TRAINING AND TESTING: PICTURES - train label histogram : (array([176, 200], dtype=int64), array([0, 1, 2])) -FIT DONE IN 0.1s -[[30 57] - [47 53]] - trace = 83 - Accuracy= 0.444 -====================================================================================================== - TRAINING MULTI-TYPE MODEL -NodeTypeEdgeFeatureGraphCRF(n_states: [11, 2], inference_method: ad3, n_features: [45, 7], n_edge_features: [[180 45] - [ 45 0]]) -====================================================================================================== -YY[0].shape (6L, 6L) - label histogram : (array([12198, 200, 200, 200, 200, 200, 200, 200, 200, - 200, 200, 176, 200], dtype=int64), array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])) -YY[0].shape (37L,) -FIT DONE IN 1878.1s -Saving model in: model.pkl -INFERENCE WITH ad3 - label histogram (PIXELs and PICTUREs): (array([6015, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, - 87, 100], dtype=int64), array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])) - - results without constraints (using ad3) - ( predict DONE IN 16.6s) -[[5760 23 26 28 28 26 23 22 23 28 28 0 0] - [ 6 93 1 0 0 0 0 0 0 0 0 0 0] - [ 6 0 92 2 0 0 0 0 0 0 0 0 0] - [ 6 0 0 92 2 0 0 0 0 0 0 0 0] - [ 5 0 0 0 92 3 0 0 0 0 0 0 0] - [ 5 0 0 0 0 92 3 0 0 0 0 0 0] - [ 5 0 1 0 0 0 91 3 0 0 0 0 0] - [ 5 0 0 1 0 0 0 91 3 0 0 0 0] - [ 6 0 0 0 1 1 0 0 91 1 0 0 0] - [ 6 0 0 0 0 1 1 0 0 91 1 0 0] - [ 5 0 0 0 0 0 1 2 0 0 92 0 0] - [ 0 0 0 0 0 0 0 0 0 0 0 62 25] - [ 0 0 0 0 0 0 0 0 0 0 0 5 95]] - trace = 6834 - Accuracy= 0.949 -__________________________________________________ - - results exploiting constraints (using ad3+) - ( predict DONE IN 182.0s) -[[5749 21 25 27 28 28 27 28 27 28 27 0 0] - [ 5 94 1 0 0 0 0 0 0 0 0 0 0] - [ 4 1 94 1 0 0 0 0 0 0 0 0 0] - [ 4 0 1 94 1 0 0 0 0 0 0 0 0] - [ 4 0 0 1 94 1 0 0 0 0 0 0 0] - [ 4 0 0 0 1 94 1 0 0 0 0 0 0] - [ 4 0 0 0 0 1 94 1 0 0 0 0 0] - [ 5 0 0 0 0 0 1 93 1 0 0 0 0] - [ 5 0 0 0 0 1 0 1 93 0 0 0 0] - [ 5 0 0 0 0 0 1 0 1 93 0 0 0] - [ 4 0 0 0 0 0 0 1 0 1 94 0 0] - [ 0 0 0 0 0 0 0 0 0 0 0 60 27] - [ 0 0 0 0 0 0 0 0 0 0 0 4 96]] - trace = 6842 - Accuracy= 0.950 -__________________________________________________ - - results without constraints (using ad3+) - ( predict DONE IN 88.4s) -[[5736 25 28 30 28 27 28 26 27 30 30 0 0] - [ 4 95 1 0 0 0 0 0 0 0 0 0 0] - [ 3 1 94 2 0 0 0 0 0 0 0 0 0] - [ 3 0 1 94 2 0 0 0 0 0 0 0 0] - [ 3 0 0 1 94 2 0 0 0 0 0 0 0] - [ 3 0 0 0 1 94 2 0 0 0 0 0 0] - [ 3 0 1 0 0 1 93 2 0 0 0 0 0] - [ 3 0 0 1 0 0 1 93 2 0 0 0 0] - [ 3 0 0 0 1 1 0 1 93 1 0 0 0] - [ 3 0 0 0 0 1 1 0 1 93 1 0 0] - [ 3 0 0 0 0 0 1 1 0 1 94 0 0] - [ 0 0 0 0 0 0 0 0 0 0 0 59 28] - [ 0 0 0 0 0 0 0 0 0 0 0 3 97]] - trace = 6829 - Accuracy= 0.948 -DONE -== NCELL= 10 -== FIXED_SEED= True -== INFERENCE = ad3 -== N_JOBS = 8 -== SWAP= 0 -== EASY= False -== MAX_ITER= 750 -== MODEL FILE= model.pkl diff --git a/examples/logs/plot_hidden_snakes.log b/examples/logs/plot_hidden_snakes.log deleted file mode 100644 index 4a9eb1e0..00000000 --- a/examples/logs/plot_hidden_snakes.log +++ /dev/null @@ -1,58 +0,0 @@ -Please be patient. Learning will take 5-20 minutes. -NCELL= 10 -ADDING PICTURE WIHOUT SNAKES!!! 200 elements in train - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! -376 picture for training -ADDING PICTURE WIHOUT SNAKES!!! 100 elements in test - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! - - DISCARDING a shuffled snake which is still a snake!!!! -187 picture for test -EdgeFeatureGraphCRF -Training time = 605.9s -Results using input features for edges -Test accuracy: 0.920 -[[5633 37 37 39 37 38 32 29 37 47 49] - [ 14 85 1 0 0 0 0 0 0 0 0] - [ 13 0 85 1 0 0 0 0 0 1 0] - [ 12 0 0 82 1 3 1 1 0 0 0] - [ 12 0 0 0 79 1 7 1 0 0 0] - [ 11 2 0 2 1 77 0 6 1 0 0] - [ 9 0 3 1 2 1 79 0 5 0 0] - [ 9 0 0 3 1 2 1 81 0 3 0] - [ 8 0 0 0 3 1 2 1 84 0 1] - [ 9 0 0 0 0 3 1 2 1 84 0] - [ 7 0 0 0 0 0 3 1 1 1 87]] diff --git a/examples/logs/plot_snakes.log b/examples/logs/plot_snakes.log deleted file mode 100644 index 64e5fc80..00000000 --- a/examples/logs/plot_snakes.log +++ /dev/null @@ -1,69 +0,0 @@ -Please be patient. Learning will take 5-20 minutes. -Results using only directional features for edges -Test accuracy: 0.829 -[[2750 0 0 0 0 0 0 0 0 0 0] - [ 0 98 0 0 1 0 0 0 1 0 0] - [ 0 6 38 3 34 8 1 2 5 1 2] - [ 0 9 8 10 8 41 1 12 3 7 1] - [ 0 1 14 2 37 8 1 9 21 5 2] - [ 0 4 2 9 16 29 2 19 11 7 1] - [ 0 2 13 3 30 16 2 7 20 5 2] - [ 0 7 5 8 15 29 3 14 8 11 0] - [ 0 3 10 3 29 10 1 6 20 3 15] - [ 0 9 3 2 10 8 0 15 4 46 3] - [ 0 2 7 3 9 1 1 3 7 3 64]] -Results using also input features for edges -Test accuracy: 0.996 -[[2749 0 0 0 0 0 0 0 1 0 0] - [ 0 100 0 0 0 0 0 0 0 0 0] - [ 0 0 100 0 0 0 0 0 0 0 0] - [ 0 0 0 100 0 0 0 0 0 0 0] - [ 0 0 0 0 98 0 1 0 1 0 0] - [ 0 0 0 2 0 98 0 0 0 0 0] - [ 0 0 0 0 2 0 98 0 0 0 0] - [ 0 1 0 0 0 2 0 97 0 0 0] - [ 0 0 1 0 0 0 1 0 98 0 0] - [ 0 0 0 1 0 0 0 0 0 99 0] - [ 0 0 0 0 1 0 0 0 0 0 99]] - - - ================================================================================= - After fixing prepare_data: - Oct 9 2017 - - edge_features[:len(right), :, 0] = features[right[:, 0]] - edge_features[:len(right), :, 1] = features[right[:, 1]] -#ORIG -# edge_features[len(right):, :, 0] = features[down[:, 0]] -# edge_features[len(right):, :, 1] = features[down[:, 1]] - edge_features[len(right):, :, 2] = features[down[:, 0]] - edge_features[len(right):, :, 3] = features[down[:, 1]] - - - Please be patient. Learning will take 5-20 minutes. -Results using only directional features for edges -Test accuracy: 0.847 -[[2750 0 0 0 0 0 0 0 0 0 0] - [ 0 99 0 0 1 0 0 0 0 0 0] - [ 0 2 68 3 9 4 6 4 3 1 0] - [ 0 4 11 45 8 14 5 6 0 6 1] - [ 0 1 22 18 31 2 14 4 3 5 0] - [ 0 3 7 38 12 22 5 4 2 7 0] - [ 0 2 19 16 26 8 16 2 9 2 0] - [ 0 6 14 26 10 15 5 12 2 10 0] - [ 0 0 12 15 16 4 16 2 18 4 13] - [ 0 2 5 18 6 8 5 3 2 50 1] - [ 0 1 11 4 13 1 2 0 2 2 64]] -Results using also input features for edges -Test accuracy: 0.999 -[[2750 0 0 0 0 0 0 0 0 0 0] - [ 0 100 0 0 0 0 0 0 0 0 0] - [ 0 0 100 0 0 0 0 0 0 0 0] - [ 0 1 0 99 0 0 0 0 0 0 0] - [ 0 0 1 0 99 0 0 0 0 0 0] - [ 0 0 0 1 0 99 0 0 0 0 0] - [ 0 0 0 0 1 0 99 0 0 0 0] - [ 0 0 0 0 0 1 0 99 0 0 0] - [ 0 0 0 0 0 0 0 0 100 0 0] - [ 0 0 0 0 0 0 0 0 0 100 0] - [ 0 0 0 0 0 0 0 0 0 0 100]] \ No newline at end of file diff --git a/examples/logs/plot_snakes_constraints.log b/examples/logs/plot_snakes_constraints.log deleted file mode 100644 index 3e4e144d..00000000 --- a/examples/logs/plot_snakes_constraints.log +++ /dev/null @@ -1,97 +0,0 @@ -Please be patient. Learning will take 5-20 minutes. -200 picture for training -100 picture for test -- TRAINING ONLY WITH DIRECTIONAL EDGE FEATURES ----- -Model EdgeFeatureGraphCRF fitted. 131.3s -- Results using only directional features for edges. 131.3s - ( predict DONE IN 0.8s) -[[2750 0 0 0 0 0 0 0 0 0 0] - [ 0 100 0 0 0 0 0 0 0 0 0] - [ 0 0 59 0 22 4 6 1 7 1 0] - [ 0 3 1 29 5 31 8 18 1 3 1] - [ 0 1 13 2 30 11 25 1 13 3 1] - [ 0 1 1 9 4 46 11 15 3 9 1] - [ 0 1 7 2 24 10 21 7 23 2 3] - [ 0 0 1 6 7 35 10 17 3 21 0] - [ 0 0 7 2 14 10 16 4 25 0 22] - [ 0 0 0 3 7 14 4 12 2 58 0] - [ 0 0 5 3 11 3 7 0 5 0 66]] - trace = 3201 - Accuracy= 0.854 -- Result with binarized graph - ( predict DONE IN 0.8s) -[[2750 0 0 0 0 0 0 0 0 0 0] - [ 0 100 0 0 0 0 0 0 0 0 0] - [ 0 0 59 0 22 4 6 1 7 1 0] - [ 0 3 1 29 5 31 8 18 1 3 1] - [ 0 1 13 2 30 11 25 1 13 3 1] - [ 0 1 1 9 4 46 11 15 3 9 1] - [ 0 1 7 2 24 10 21 7 23 2 3] - [ 0 0 1 6 7 35 10 17 3 21 0] - [ 0 0 7 2 14 10 16 4 25 0 22] - [ 0 0 0 3 7 14 4 12 2 58 0] - [ 0 0 5 3 11 3 7 0 5 0 66]] - trace = 3201 - Accuracy= 0.854 -- Results of inference under constraints - ( predict DONE IN 0.8s) -[[2750 0 0 0 0 0 0 0 0 0 0] - [ 0 100 0 0 0 0 0 0 0 0 0] - [ 0 0 59 0 22 4 6 1 7 1 0] - [ 0 3 1 29 5 31 8 18 1 3 1] - [ 0 1 13 2 30 11 25 1 13 3 1] - [ 0 1 1 9 4 46 11 15 3 9 1] - [ 0 1 7 2 24 10 21 7 23 2 3] - [ 0 0 1 6 7 35 10 17 3 21 0] - [ 0 0 7 2 14 10 16 4 25 0 22] - [ 0 0 0 3 7 14 4 12 2 58 0] - [ 0 0 5 3 11 3 7 0 5 0 66]] - trace = 3201 - Accuracy= 0.854 -- NOW TRAINING WITH BETTER EDGE FEATURES ----- -Model EdgeFeatureGraphCRF fitted. 740.4s -- Results using also input features for edges. 740.4s - ( predict DONE IN 1.0s) -[[2749 0 0 0 0 0 0 0 1 0 0] - [ 0 100 0 0 0 0 0 0 0 0 0] - [ 0 0 100 0 0 0 0 0 0 0 0] - [ 0 0 0 100 0 0 0 0 0 0 0] - [ 0 0 0 0 98 0 1 0 1 0 0] - [ 0 0 0 2 0 98 0 0 0 0 0] - [ 0 0 0 0 2 0 98 0 0 0 0] - [ 0 1 0 0 0 2 0 97 0 0 0] - [ 0 0 1 0 0 0 1 0 98 0 0] - [ 0 0 0 1 0 0 0 0 0 99 0] - [ 0 0 0 0 1 0 0 0 0 0 99]] - trace = 3736 - Accuracy= 0.996 -- Result with binarized graph - ( predict DONE IN 1.0s) -[[2749 0 0 0 0 0 0 0 1 0 0] - [ 0 100 0 0 0 0 0 0 0 0 0] - [ 0 0 100 0 0 0 0 0 0 0 0] - [ 0 0 0 100 0 0 0 0 0 0 0] - [ 0 0 0 0 98 0 1 0 1 0 0] - [ 0 0 0 2 0 98 0 0 0 0 0] - [ 0 0 0 0 2 0 98 0 0 0 0] - [ 0 1 0 0 0 2 0 97 0 0 0] - [ 0 0 1 0 0 0 1 0 98 0 0] - [ 0 0 0 1 0 0 0 0 0 99 0] - [ 0 0 0 0 1 0 0 0 0 0 99]] - trace = 3736 - Accuracy= 0.996 -- Results of inference under constraints - ( predict DONE IN 1.0s) -[[2749 0 0 0 0 0 0 0 1 0 0] - [ 0 100 0 0 0 0 0 0 0 0 0] - [ 0 0 100 0 0 0 0 0 0 0 0] - [ 0 0 0 100 0 0 0 0 0 0 0] - [ 0 0 0 0 98 0 1 0 1 0 0] - [ 0 0 0 2 0 98 0 0 0 0 0] - [ 0 0 0 0 2 0 98 0 0 0 0] - [ 0 1 0 0 0 2 0 97 0 0 0] - [ 0 0 1 0 0 0 1 0 98 0 0] - [ 0 0 0 1 0 0 0 0 0 99 0] - [ 0 0 0 0 1 0 0 0 0 0 99]] - trace = 3736 - Accuracy= 0.996 diff --git a/examples/logs/plot_snakes_typed.log b/examples/logs/plot_snakes_typed.log deleted file mode 100644 index 0a4e7a3f..00000000 --- a/examples/logs/plot_snakes_typed.log +++ /dev/null @@ -1,1476 +0,0 @@ -Please be patient. Learning will take 5-20 minutes. -1000 inference calls -2000 inference calls -3000 inference calls -4000 inference calls -5000 inference calls -6000 inference calls -Results using only directional features for edges -Test accuracy: 0.829 -[[2750 0 0 0 0 0 0 0 0 0 0] - [ 0 98 0 0 1 0 0 0 1 0 0] - [ 0 6 38 3 34 8 1 2 5 1 2] - [ 0 9 8 10 8 41 1 12 3 7 1] - [ 0 1 14 2 37 8 1 9 21 5 2] - [ 0 4 2 9 16 29 2 19 11 7 1] - [ 0 2 13 3 30 16 2 7 20 5 2] - [ 0 7 5 8 15 29 3 14 8 11 0] - [ 0 3 10 3 29 10 1 6 20 3 15] - [ 0 9 3 2 10 8 0 15 4 46 3] - [ 0 2 7 3 9 1 1 3 7 3 64]] -Training 1-slack dual structural SVM -iteration 0 -cutting plane objective: 0.019872, primal objective 756.600000 -iteration 1 -new constraint too weak. -cutting plane objective: 0.038904, primal objective 462.213801 -iteration 2 -cutting plane objective: 0.039553, primal objective 15.695517 -iteration 3 -cutting plane objective: 0.135721, primal objective 499.742843 -iteration 4 -cutting plane objective: 0.141298, primal objective 18.615756 -iteration 5 -cutting plane objective: 0.180218, primal objective 517.912014 -iteration 6 -cutting plane objective: 0.200170, primal objective 51.516560 -iteration 7 -cutting plane objective: 0.217854, primal objective 336.931437 -iteration 8 -cutting plane objective: 0.233433, primal objective 46.977896 -iteration 9 -cutting plane objective: 0.265987, primal objective 281.416928 -iteration 10 -cutting plane objective: 0.293149, primal objective 33.545220 -iteration 11 -cutting plane objective: 0.310093, primal objective 308.614278 -iteration 12 -cutting plane objective: 0.331982, primal objective 47.636283 -iteration 13 -cutting plane objective: 0.396049, primal objective 286.505546 -iteration 14 -cutting plane objective: 0.421507, primal objective 32.833105 -iteration 15 -cutting plane objective: 0.447097, primal objective 325.530203 -iteration 16 -cutting plane objective: 0.471307, primal objective 61.175845 -iteration 17 -cutting plane objective: 0.538959, primal objective 286.387701 -iteration 18 -cutting plane objective: 0.553061, primal objective 54.961277 -iteration 19 -cutting plane objective: 0.732316, primal objective 276.671828 -iteration 20 -cutting plane objective: 0.765760, primal objective 83.412089 -iteration 21 -cutting plane objective: 0.850887, primal objective 77.632448 -iteration 22 -cutting plane objective: 0.905878, primal objective 59.206131 -iteration 23 -cutting plane objective: 1.042260, primal objective 278.294152 -iteration 24 -cutting plane objective: 1.070590, primal objective 76.604480 -iteration 25 -cutting plane objective: 1.123092, primal objective 49.977941 -iteration 26 -cutting plane objective: 1.271715, primal objective 331.240125 -iteration 27 -cutting plane objective: 1.286027, primal objective 53.541896 -iteration 28 -cutting plane objective: 1.617411, primal objective 377.967855 -iteration 29 -cutting plane objective: 1.798357, primal objective 79.846862 -iteration 30 -cutting plane objective: 2.082935, primal objective 304.828385 -iteration 31 -cutting plane objective: 2.675264, primal objective 117.951119 -iteration 32 -cutting plane objective: 2.844978, primal objective 64.758097 -iteration 33 -cutting plane objective: 3.287955, primal objective 342.055089 -iteration 34 -cutting plane objective: 3.388039, primal objective 88.711681 -iteration 35 -cutting plane objective: 3.721702, primal objective 74.197913 -iteration 36 -cutting plane objective: 4.063515, primal objective 408.218394 -iteration 37 -cutting plane objective: 4.404916, primal objective 96.404884 -iteration 38 -cutting plane objective: 4.493112, primal objective 388.749621 -iteration 39 -cutting plane objective: 4.629265, primal objective 80.523698 -iteration 40 -cutting plane objective: 4.908023, primal objective 180.172472 -iteration 41 -cutting plane objective: 5.047723, primal objective 69.013924 -iteration 42 -cutting plane objective: 5.314418, primal objective 74.058355 -iteration 43 -cutting plane objective: 5.548530, primal objective 67.863726 -iteration 44 -cutting plane objective: 5.701956, primal objective 53.170459 -iteration 45 -cutting plane objective: 5.857337, primal objective 50.467279 -iteration 46 -cutting plane objective: 5.971032, primal objective 57.336636 -iteration 47 -cutting plane objective: 6.049148, primal objective 46.686498 -iteration 48 -cutting plane objective: 6.310814, primal objective 193.970238 -iteration 49 -cutting plane objective: 6.594890, primal objective 53.553441 -iteration 50 -cutting plane objective: 6.817985, primal objective 61.540080 -iteration 51 -cutting plane objective: 6.905080, primal objective 53.958899 -iteration 52 -cutting plane objective: 6.996705, primal objective 50.189089 -iteration 53 -cutting plane objective: 7.238325, primal objective 134.945180 -iteration 54 -cutting plane objective: 7.359412, primal objective 57.380775 -iteration 55 -cutting plane objective: 7.533335, primal objective 52.485116 -iteration 56 -cutting plane objective: 7.671114, primal objective 50.081620 -iteration 57 -cutting plane objective: 7.764426, primal objective 55.497301 -iteration 58 -cutting plane objective: 7.879441, primal objective 50.653875 -iteration 59 -cutting plane objective: 7.948227, primal objective 45.092745 -iteration 60 -cutting plane objective: 8.022129, primal objective 43.754028 -iteration 61 -cutting plane objective: 8.086457, primal objective 39.429920 -iteration 62 -cutting plane objective: 8.143238, primal objective 117.167563 -iteration 63 -cutting plane objective: 8.311361, primal objective 51.726534 -iteration 64 -cutting plane objective: 8.382285, primal objective 45.834890 -iteration 65 -cutting plane objective: 8.445380, primal objective 40.064655 -iteration 66 -cutting plane objective: 8.515011, primal objective 37.831118 -iteration 67 -cutting plane objective: 8.617629, primal objective 36.393356 -iteration 68 -cutting plane objective: 8.681467, primal objective 34.840377 -iteration 69 -cutting plane objective: 8.976755, primal objective 110.674298 -iteration 70 -cutting plane objective: 9.246389, primal objective 61.375676 -iteration 71 -cutting plane objective: 9.668646, primal objective 59.305100 -iteration 72 -cutting plane objective: 9.875519, primal objective 57.280319 -iteration 73 -cutting plane objective: 10.027298, primal objective 56.104111 -iteration 74 -cutting plane objective: 10.214066, primal objective 49.943404 -iteration 75 -cutting plane objective: 10.348591, primal objective 42.373991 -iteration 76 -cutting plane objective: 10.360995, primal objective 46.056028 -iteration 77 -cutting plane objective: 10.490433, primal objective 35.739535 -iteration 78 -cutting plane objective: 10.660000, primal objective 92.701122 -iteration 79 -cutting plane objective: 10.897688, primal objective 54.777889 -iteration 80 -cutting plane objective: 11.086600, primal objective 53.689534 -iteration 81 -cutting plane objective: 11.141144, primal objective 54.034713 -iteration 82 -cutting plane objective: 11.284600, primal objective 42.644617 -iteration 83 -cutting plane objective: 11.380347, primal objective 48.407249 -iteration 84 -cutting plane objective: 11.416572, primal objective 44.132411 -iteration 85 -cutting plane objective: 11.571412, primal objective 34.961918 -iteration 86 -cutting plane objective: 11.704028, primal objective 38.640979 -iteration 87 -cutting plane objective: 11.784767, primal objective 38.241169 -iteration 88 -cutting plane objective: 11.830782, primal objective 41.310102 -iteration 89 -cutting plane objective: 11.872251, primal objective 35.710610 -iteration 90 -cutting plane objective: 11.970451, primal objective 29.776013 -iteration 91 -cutting plane objective: 12.042980, primal objective 70.255281 -iteration 92 -cutting plane objective: 12.321428, primal objective 47.621574 -iteration 93 -cutting plane objective: 12.434090, primal objective 54.820456 -iteration 94 -cutting plane objective: 12.545058, primal objective 44.277521 -iteration 95 -cutting plane objective: 12.579911, primal objective 50.366843 -iteration 96 -cutting plane objective: 12.703294, primal objective 42.584152 -iteration 97 -cutting plane objective: 12.814386, primal objective 44.675268 -iteration 98 -cutting plane objective: 12.877223, primal objective 41.281536 -iteration 99 -cutting plane objective: 12.921012, primal objective 37.439323 -iteration 100 -cutting plane objective: 12.998230, primal objective 35.289201 -iteration 101 -cutting plane objective: 13.071419, primal objective 36.749097 -iteration 102 -cutting plane objective: 13.140595, primal objective 31.122268 -iteration 103 -cutting plane objective: 13.238240, primal objective 31.039180 -iteration 104 -cutting plane objective: 13.274355, primal objective 32.384291 -iteration 105 -cutting plane objective: 13.342754, primal objective 27.726460 -iteration 106 -cutting plane objective: 13.378876, primal objective 56.737089 -iteration 107 -cutting plane objective: 13.513287, primal objective 45.070374 -iteration 108 -cutting plane objective: 13.668893, primal objective 45.242897 -iteration 109 -cutting plane objective: 13.772756, primal objective 42.252533 -iteration 110 -cutting plane objective: 13.848949, primal objective 38.421927 -iteration 111 -cutting plane objective: 13.918798, primal objective 32.979882 -iteration 112 -cutting plane objective: 14.014080, primal objective 35.216789 -iteration 113 -cutting plane objective: 14.062768, primal objective 41.931717 -iteration 114 -cutting plane objective: 14.129279, primal objective 30.476606 -iteration 115 -cutting plane objective: 14.199358, primal objective 32.496563 -iteration 116 -cutting plane objective: 14.255371, primal objective 31.287407 -iteration 117 -cutting plane objective: 14.313073, primal objective 31.771053 -iteration 118 -cutting plane objective: 14.332574, primal objective 30.729696 -iteration 119 -cutting plane objective: 14.366705, primal objective 26.617029 -iteration 120 -cutting plane objective: 14.403335, primal objective 27.628803 -iteration 121 -cutting plane objective: 14.429644, primal objective 28.567795 -iteration 122 -cutting plane objective: 14.469745, primal objective 27.639099 -iteration 123 -cutting plane objective: 14.490355, primal objective 25.586656 -iteration 124 -cutting plane objective: 14.504424, primal objective 24.510179 -iteration 125 -cutting plane objective: 14.516832, primal objective 38.118386 -iteration 126 -cutting plane objective: 14.742530, primal objective 39.861384 -iteration 127 -cutting plane objective: 14.906810, primal objective 39.531021 -iteration 128 -cutting plane objective: 14.964538, primal objective 39.741604 -iteration 129 -cutting plane objective: 15.066200, primal objective 33.027552 -iteration 130 -cutting plane objective: 15.173573, primal objective 36.010357 -iteration 131 -cutting plane objective: 15.244508, primal objective 32.454034 -iteration 132 -cutting plane objective: 15.307902, primal objective 32.142314 -iteration 133 -cutting plane objective: 15.370147, primal objective 33.227497 -iteration 134 -cutting plane objective: 15.435844, primal objective 29.290471 -iteration 135 -cutting plane objective: 15.455029, primal objective 29.740110 -iteration 136 -cutting plane objective: 15.487805, primal objective 26.241301 -iteration 137 -cutting plane objective: 15.530650, primal objective 26.389384 -iteration 138 -cutting plane objective: 15.559001, primal objective 29.019526 -iteration 139 -cutting plane objective: 15.578269, primal objective 27.657838 -iteration 140 -cutting plane objective: 15.591534, primal objective 25.981607 -iteration 141 -cutting plane objective: 15.605012, primal objective 27.118902 -iteration 142 -cutting plane objective: 15.626955, primal objective 25.609108 -iteration 143 -cutting plane objective: 15.676807, primal objective 25.950261 -iteration 144 -cutting plane objective: 15.704026, primal objective 24.426672 -iteration 145 -cutting plane objective: 15.729378, primal objective 24.653150 -iteration 146 -cutting plane objective: 15.759814, primal objective 24.408942 -iteration 147 -cutting plane objective: 15.783420, primal objective 23.747515 -iteration 148 -cutting plane objective: 15.796411, primal objective 23.745447 -iteration 149 -cutting plane objective: 15.813970, primal objective 22.341130 -iteration 150 -cutting plane objective: 15.827383, primal objective 21.512536 -iteration 151 -cutting plane objective: 15.857623, primal objective 40.008093 -iteration 152 -cutting plane objective: 16.112699, primal objective 41.946535 -iteration 153 -cutting plane objective: 16.240748, primal objective 42.477879 -iteration 154 -cutting plane objective: 16.415461, primal objective 36.934896 -iteration 155 -cutting plane objective: 16.529820, primal objective 34.629216 -iteration 156 -cutting plane objective: 16.589955, primal objective 36.567574 -iteration 157 -cutting plane objective: 16.693600, primal objective 31.592590 -iteration 158 -cutting plane objective: 16.791745, primal objective 31.562259 -iteration 159 -cutting plane objective: 16.844531, primal objective 30.922127 -iteration 160 -cutting plane objective: 16.882273, primal objective 32.110430 -iteration 161 -cutting plane objective: 16.926870, primal objective 27.542302 -iteration 162 -cutting plane objective: 16.972016, primal objective 29.909823 -iteration 163 -cutting plane objective: 16.992850, primal objective 31.024998 -iteration 164 -cutting plane objective: 17.023246, primal objective 28.302176 -iteration 165 -cutting plane objective: 17.068547, primal objective 27.389193 -iteration 166 -cutting plane objective: 17.098948, primal objective 26.376054 -iteration 167 -cutting plane objective: 17.123413, primal objective 25.140992 -iteration 168 -cutting plane objective: 17.145637, primal objective 25.293771 -iteration 169 -cutting plane objective: 17.160597, primal objective 24.891791 -iteration 170 -cutting plane objective: 17.182297, primal objective 24.854375 -iteration 171 -cutting plane objective: 17.206514, primal objective 24.229423 -iteration 172 -cutting plane objective: 17.227862, primal objective 24.138926 -iteration 173 -cutting plane objective: 17.239502, primal objective 23.948760 -iteration 174 -cutting plane objective: 17.256542, primal objective 23.679435 -iteration 175 -cutting plane objective: 17.269835, primal objective 24.211192 -iteration 176 -cutting plane objective: 17.288319, primal objective 22.446479 -iteration 177 -cutting plane objective: 17.311084, primal objective 35.034461 -iteration 178 -cutting plane objective: 17.584768, primal objective 41.303077 -iteration 179 -cutting plane objective: 17.730201, primal objective 45.557020 -iteration 180 -cutting plane objective: 17.857572, primal objective 40.515854 -iteration 181 -cutting plane objective: 17.931328, primal objective 37.035197 -iteration 182 -cutting plane objective: 18.020099, primal objective 33.692262 -iteration 183 -cutting plane objective: 18.094606, primal objective 34.565970 -iteration 184 -cutting plane objective: 18.157064, primal objective 33.558166 -iteration 185 -cutting plane objective: 18.223848, primal objective 32.875251 -iteration 186 -cutting plane objective: 18.274319, primal objective 30.253177 -iteration 187 -cutting plane objective: 18.321115, primal objective 30.265179 -iteration 188 -cutting plane objective: 18.361318, primal objective 29.046013 -iteration 189 -cutting plane objective: 18.392455, primal objective 27.982337 -iteration 190 -cutting plane objective: 18.423358, primal objective 29.604863 -iteration 191 -cutting plane objective: 18.457755, primal objective 27.372942 -iteration 192 -cutting plane objective: 18.488021, primal objective 26.884197 -iteration 193 -cutting plane objective: 18.509007, primal objective 28.104562 -iteration 194 -cutting plane objective: 18.530443, primal objective 25.625755 -iteration 195 -cutting plane objective: 18.550246, primal objective 28.297988 -iteration 196 -cutting plane objective: 18.579698, primal objective 25.486664 -iteration 197 -cutting plane objective: 18.600024, primal objective 25.889710 -iteration 198 -cutting plane objective: 18.611331, primal objective 26.601719 -iteration 199 -cutting plane objective: 18.631269, primal objective 24.391966 -iteration 200 -cutting plane objective: 18.651220, primal objective 24.362099 -iteration 201 -cutting plane objective: 18.662568, primal objective 24.995704 -iteration 202 -cutting plane objective: 18.674863, primal objective 24.783030 -iteration 203 -cutting plane objective: 18.689842, primal objective 24.238198 -iteration 204 -cutting plane objective: 18.703041, primal objective 23.189288 -iteration 205 -cutting plane objective: 18.715830, primal objective 23.246123 -iteration 206 -cutting plane objective: 18.723583, primal objective 23.362962 -iteration 207 -cutting plane objective: 18.734480, primal objective 22.584175 -iteration 208 -cutting plane objective: 18.743365, primal objective 27.858498 -iteration 209 -cutting plane objective: 18.905044, primal objective 36.345570 -iteration 210 -cutting plane objective: 19.015666, primal objective 36.723502 -iteration 211 -cutting plane objective: 19.083564, primal objective 33.532242 -iteration 212 -cutting plane objective: 19.154390, primal objective 32.651228 -iteration 213 -cutting plane objective: 19.208529, primal objective 31.088988 -iteration 214 -cutting plane objective: 19.262657, primal objective 29.947074 -iteration 215 -cutting plane objective: 19.292811, primal objective 30.141265 -iteration 216 -cutting plane objective: 19.336226, primal objective 27.883462 -iteration 217 -cutting plane objective: 19.368576, primal objective 28.155540 -iteration 218 -cutting plane objective: 19.396752, primal objective 28.576452 -iteration 219 -cutting plane objective: 19.430494, primal objective 27.383806 -iteration 220 -cutting plane objective: 19.451701, primal objective 27.277672 -iteration 221 -cutting plane objective: 19.481313, primal objective 27.606754 -iteration 222 -cutting plane objective: 19.507760, primal objective 26.099495 -iteration 223 -cutting plane objective: 19.527715, primal objective 27.356829 -iteration 224 -cutting plane objective: 19.538091, primal objective 26.129442 -iteration 225 -cutting plane objective: 19.558567, primal objective 25.426673 -iteration 226 -cutting plane objective: 19.572461, primal objective 25.768954 -iteration 227 -cutting plane objective: 19.590646, primal objective 24.653763 -iteration 228 -cutting plane objective: 19.612164, primal objective 25.222956 -iteration 229 -cutting plane objective: 19.624748, primal objective 25.107009 -iteration 230 -cutting plane objective: 19.636567, primal objective 24.838748 -iteration 231 -cutting plane objective: 19.645769, primal objective 23.729175 -iteration 232 -cutting plane objective: 19.653630, primal objective 24.007738 -iteration 233 -cutting plane objective: 19.663241, primal objective 23.591188 -iteration 234 -cutting plane objective: 19.672471, primal objective 23.541146 -iteration 235 -cutting plane objective: 19.678394, primal objective 23.703990 -iteration 236 -cutting plane objective: 19.688930, primal objective 23.197163 -iteration 237 -cutting plane objective: 19.696072, primal objective 23.777556 -iteration 238 -cutting plane objective: 19.701599, primal objective 23.344421 -iteration 239 -cutting plane objective: 19.709086, primal objective 22.861171 -iteration 240 -cutting plane objective: 19.715964, primal objective 22.718072 -iteration 241 -cutting plane objective: 19.720704, primal objective 22.759357 -iteration 242 -cutting plane objective: 19.724719, primal objective 22.488610 -iteration 243 -cutting plane objective: 19.728284, primal objective 22.090405 -iteration 244 -cutting plane objective: 19.731785, primal objective 21.893303 -iteration 245 -new constraint too weak. -no additional constraints -Switching to ad3 inference -iteration 246 -cutting plane objective: 19.740518, primal objective 277.543643 -iteration 247 -cutting plane objective: 19.747216, primal objective 54.938903 -iteration 248 -cutting plane objective: 20.361410, primal objective 121.478774 -iteration 249 -cutting plane objective: 21.038496, primal objective 69.490816 -iteration 250 -cutting plane objective: 21.444008, primal objective 62.711182 -iteration 251 -cutting plane objective: 21.712583, primal objective 54.027282 -iteration 252 -cutting plane objective: 21.891889, primal objective 52.079547 -iteration 253 -cutting plane objective: 22.150648, primal objective 45.136568 -iteration 254 -cutting plane objective: 22.376458, primal objective 116.187744 -iteration 255 -cutting plane objective: 22.987750, primal objective 72.400185 -iteration 256 -cutting plane objective: 23.107620, primal objective 65.940528 -iteration 257 -cutting plane objective: 23.435505, primal objective 56.813426 -iteration 258 -cutting plane objective: 23.502455, primal objective 58.833499 -iteration 259 -cutting plane objective: 23.821033, primal objective 51.532771 -iteration 260 -cutting plane objective: 23.997264, primal objective 62.338774 -iteration 261 -cutting plane objective: 24.148997, primal objective 52.287887 -iteration 262 -cutting plane objective: 24.284673, primal objective 48.569832 -iteration 263 -cutting plane objective: 24.394759, primal objective 48.546630 -iteration 264 -cutting plane objective: 24.504855, primal objective 51.349970 -iteration 265 -cutting plane objective: 24.603537, primal objective 46.453357 -iteration 266 -cutting plane objective: 24.843374, primal objective 105.572554 -iteration 267 -cutting plane objective: 25.082067, primal objective 62.851719 -iteration 268 -cutting plane objective: 25.273329, primal objective 64.987973 -iteration 269 -cutting plane objective: 25.466227, primal objective 54.095038 -iteration 270 -cutting plane objective: 25.628534, primal objective 53.507269 -iteration 271 -cutting plane objective: 25.822553, primal objective 57.581414 -iteration 272 -cutting plane objective: 26.013074, primal objective 52.709686 -iteration 273 -cutting plane objective: 26.148908, primal objective 51.965542 -iteration 274 -cutting plane objective: 26.242762, primal objective 50.423732 -iteration 275 -cutting plane objective: 26.362973, primal objective 48.855360 -iteration 276 -cutting plane objective: 26.519640, primal objective 54.322950 -iteration 277 -cutting plane objective: 26.602421, primal objective 53.348782 -iteration 278 -cutting plane objective: 26.703987, primal objective 45.786819 -iteration 279 -cutting plane objective: 26.731452, primal objective 93.121500 -iteration 280 -cutting plane objective: 27.098968, primal objective 71.463749 -iteration 281 -cutting plane objective: 27.399831, primal objective 62.448015 -iteration 282 -cutting plane objective: 27.682632, primal objective 61.016739 -iteration 283 -cutting plane objective: 27.816397, primal objective 59.495245 -iteration 284 -cutting plane objective: 28.012931, primal objective 54.918061 -iteration 285 -cutting plane objective: 28.155126, primal objective 57.650078 -iteration 286 -cutting plane objective: 28.392132, primal objective 50.850739 -iteration 287 -cutting plane objective: 28.520658, primal objective 55.083307 -iteration 288 -cutting plane objective: 28.652725, primal objective 49.877599 -iteration 289 -cutting plane objective: 28.744848, primal objective 49.640668 -iteration 290 -cutting plane objective: 28.829915, primal objective 49.068535 -iteration 291 -cutting plane objective: 28.918603, primal objective 47.072560 -iteration 292 -cutting plane objective: 28.989226, primal objective 46.695790 -iteration 293 -cutting plane objective: 29.079261, primal objective 44.057642 -iteration 294 -cutting plane objective: 29.291114, primal objective 89.243532 -iteration 295 -cutting plane objective: 29.647958, primal objective 61.806888 -iteration 296 -cutting plane objective: 29.806036, primal objective 64.504411 -iteration 297 -cutting plane objective: 30.056655, primal objective 59.201594 -iteration 298 -cutting plane objective: 30.247216, primal objective 58.934001 -iteration 299 -cutting plane objective: 30.426310, primal objective 55.889184 -iteration 300 -cutting plane objective: 30.458525, primal objective 57.865813 -iteration 301 -cutting plane objective: 30.676319, primal objective 52.853986 -iteration 302 -cutting plane objective: 30.843012, primal objective 54.264329 -iteration 303 -cutting plane objective: 30.937745, primal objective 52.415248 -iteration 304 -cutting plane objective: 31.029548, primal objective 48.875741 -iteration 305 -cutting plane objective: 31.126341, primal objective 49.935645 -iteration 306 -cutting plane objective: 31.240662, primal objective 49.935390 -iteration 307 -cutting plane objective: 31.343540, primal objective 47.717134 -iteration 308 -cutting plane objective: 31.384021, primal objective 51.343821 -iteration 309 -cutting plane objective: 31.473540, primal objective 45.930987 -iteration 310 -cutting plane objective: 31.487228, primal objective 86.132179 -iteration 311 -cutting plane objective: 31.656760, primal objective 61.487181 -iteration 312 -cutting plane objective: 31.719132, primal objective 58.682933 -iteration 313 -cutting plane objective: 31.881288, primal objective 53.707593 -iteration 314 -cutting plane objective: 31.996094, primal objective 57.868450 -iteration 315 -cutting plane objective: 32.119040, primal objective 52.627828 -iteration 316 -cutting plane objective: 32.243279, primal objective 50.777363 -iteration 317 -cutting plane objective: 32.329802, primal objective 50.779353 -iteration 318 -cutting plane objective: 32.428452, primal objective 51.325226 -iteration 319 -cutting plane objective: 32.511702, primal objective 49.883232 -iteration 320 -cutting plane objective: 32.579997, primal objective 47.836306 -iteration 321 -cutting plane objective: 32.667324, primal objective 48.235687 -iteration 322 -cutting plane objective: 32.741056, primal objective 46.481267 -iteration 323 -cutting plane objective: 32.826191, primal objective 46.180131 -iteration 324 -cutting plane objective: 33.034644, primal objective 73.766742 -iteration 325 -cutting plane objective: 33.209126, primal objective 59.665062 -iteration 326 -cutting plane objective: 33.434830, primal objective 56.831227 -iteration 327 -cutting plane objective: 33.621972, primal objective 57.451114 -iteration 328 -cutting plane objective: 33.804584, primal objective 55.363451 -iteration 329 -cutting plane objective: 33.966614, primal objective 55.333321 -iteration 330 -cutting plane objective: 34.131394, primal objective 51.171930 -iteration 331 -cutting plane objective: 34.269898, primal objective 57.708789 -iteration 332 -cutting plane objective: 34.369885, primal objective 53.707698 -iteration 333 -cutting plane objective: 34.458461, primal objective 52.377899 -iteration 334 -cutting plane objective: 34.552755, primal objective 48.512908 -iteration 335 -cutting plane objective: 34.580638, primal objective 50.377465 -iteration 336 -cutting plane objective: 34.669584, primal objective 48.070365 -iteration 337 -cutting plane objective: 34.755923, primal objective 50.421221 -iteration 338 -cutting plane objective: 34.831442, primal objective 49.169683 -iteration 339 -cutting plane objective: 34.876186, primal objective 49.632812 -iteration 340 -cutting plane objective: 34.925525, primal objective 47.777317 -iteration 341 -cutting plane objective: 34.998525, primal objective 48.162106 -iteration 342 -cutting plane objective: 35.045553, primal objective 48.133287 -iteration 343 -cutting plane objective: 35.109015, primal objective 46.819500 -iteration 344 -cutting plane objective: 35.155711, primal objective 47.051436 -iteration 345 -cutting plane objective: 35.196735, primal objective 46.700018 -iteration 346 -cutting plane objective: 35.237797, primal objective 46.838492 -iteration 347 -cutting plane objective: 35.283779, primal objective 45.326752 -iteration 348 -cutting plane objective: 35.521891, primal objective 66.524296 -iteration 349 -cutting plane objective: 35.703803, primal objective 57.333080 -iteration 350 -cutting plane objective: 35.906799, primal objective 57.657687 -iteration 351 -cutting plane objective: 36.053958, primal objective 56.031346 -iteration 352 -cutting plane objective: 36.234934, primal objective 53.636153 -iteration 353 -cutting plane objective: 36.341414, primal objective 56.332082 -iteration 354 -cutting plane objective: 36.444964, primal objective 57.935026 -iteration 355 -cutting plane objective: 36.576880, primal objective 54.762486 -iteration 356 -cutting plane objective: 36.688919, primal objective 53.735584 -iteration 357 -cutting plane objective: 36.791099, primal objective 52.126281 -iteration 358 -cutting plane objective: 36.876112, primal objective 52.289686 -iteration 359 -cutting plane objective: 36.963208, primal objective 51.147145 -iteration 360 -cutting plane objective: 37.069543, primal objective 51.356811 -iteration 361 -cutting plane objective: 37.151586, primal objective 50.997177 -iteration 362 -cutting plane objective: 37.225636, primal objective 51.757264 -iteration 363 -cutting plane objective: 37.291856, primal objective 49.725274 -iteration 364 -cutting plane objective: 37.365054, primal objective 49.165327 -iteration 365 -cutting plane objective: 37.421455, primal objective 49.549253 -iteration 366 -cutting plane objective: 37.469833, primal objective 49.931493 -iteration 367 -cutting plane objective: 37.521295, primal objective 48.917906 -iteration 368 -cutting plane objective: 37.567162, primal objective 48.168400 -iteration 369 -cutting plane objective: 37.609989, primal objective 48.139434 -iteration 370 -cutting plane objective: 37.645404, primal objective 48.323373 -iteration 371 -cutting plane objective: 37.685027, primal objective 47.586412 -iteration 372 -cutting plane objective: 37.717919, primal objective 46.849012 -iteration 373 -cutting plane objective: 37.746205, primal objective 47.012826 -iteration 374 -cutting plane objective: 37.777056, primal objective 45.795802 -iteration 375 -cutting plane objective: 37.808104, primal objective 46.826427 -iteration 376 -cutting plane objective: 37.842631, primal objective 45.563177 -iteration 377 -cutting plane objective: 37.997031, primal objective 61.741652 -iteration 378 -cutting plane objective: 38.137114, primal objective 55.231201 -iteration 379 -cutting plane objective: 38.264639, primal objective 55.323326 -iteration 380 -cutting plane objective: 38.351852, primal objective 54.159588 -iteration 381 -cutting plane objective: 38.453961, primal objective 51.830719 -iteration 382 -cutting plane objective: 38.526402, primal objective 51.557095 -iteration 383 -cutting plane objective: 38.610734, primal objective 50.903091 -iteration 384 -cutting plane objective: 38.694956, primal objective 50.175441 -iteration 385 -cutting plane objective: 38.750461, primal objective 50.390575 -iteration 386 -cutting plane objective: 38.816428, primal objective 51.087793 -iteration 387 -cutting plane objective: 38.824463, primal objective 51.954340 -iteration 388 -cutting plane objective: 38.889279, primal objective 49.381607 -iteration 389 -cutting plane objective: 38.967133, primal objective 49.591135 -iteration 390 -cutting plane objective: 39.043220, primal objective 49.431823 -iteration 391 -cutting plane objective: 39.090282, primal objective 50.580487 -iteration 392 -cutting plane objective: 39.135705, primal objective 48.619329 -iteration 393 -cutting plane objective: 39.187507, primal objective 48.549039 -iteration 394 -cutting plane objective: 39.237645, primal objective 48.028908 -iteration 395 -cutting plane objective: 39.284517, primal objective 47.051863 -iteration 396 -cutting plane objective: 39.330745, primal objective 47.560238 -iteration 397 -cutting plane objective: 39.370100, primal objective 47.788802 -iteration 398 -cutting plane objective: 39.413633, primal objective 48.595372 -iteration 399 -cutting plane objective: 39.451676, primal objective 47.401479 -iteration 400 -cutting plane objective: 39.478350, primal objective 47.452649 -iteration 401 -cutting plane objective: 39.508271, primal objective 46.320363 -iteration 402 -cutting plane objective: 39.524614, primal objective 46.207101 -iteration 403 -cutting plane objective: 39.548567, primal objective 45.610274 -iteration 404 -cutting plane objective: 39.567947, primal objective 45.565967 -iteration 405 -cutting plane objective: 39.587765, primal objective 45.167604 -iteration 406 -cutting plane objective: 39.621460, primal objective 61.499869 -iteration 407 -cutting plane objective: 39.735177, primal objective 54.311566 -iteration 408 -cutting plane objective: 39.818411, primal objective 54.185205 -iteration 409 -cutting plane objective: 39.893787, primal objective 52.326498 -iteration 410 -cutting plane objective: 39.966651, primal objective 51.457569 -iteration 411 -cutting plane objective: 40.025227, primal objective 50.526348 -iteration 412 -cutting plane objective: 40.085008, primal objective 50.640769 -iteration 413 -cutting plane objective: 40.138749, primal objective 49.923707 -iteration 414 -cutting plane objective: 40.172139, primal objective 49.880886 -iteration 415 -cutting plane objective: 40.207032, primal objective 49.401324 -iteration 416 -cutting plane objective: 40.248986, primal objective 49.255515 -iteration 417 -cutting plane objective: 40.274022, primal objective 48.799770 -iteration 418 -cutting plane objective: 40.317236, primal objective 48.471938 -iteration 419 -cutting plane objective: 40.362521, primal objective 48.426364 -iteration 420 -cutting plane objective: 40.408769, primal objective 49.336856 -iteration 421 -cutting plane objective: 40.444401, primal objective 48.638279 -iteration 422 -cutting plane objective: 40.478940, primal objective 47.433494 -iteration 423 -cutting plane objective: 40.511180, primal objective 48.186916 -iteration 424 -cutting plane objective: 40.546595, primal objective 47.210720 -iteration 425 -cutting plane objective: 40.572901, primal objective 48.165288 -iteration 426 -cutting plane objective: 40.611206, primal objective 47.359289 -iteration 427 -cutting plane objective: 40.638771, primal objective 47.727217 -iteration 428 -cutting plane objective: 40.670389, primal objective 46.671290 -iteration 429 -cutting plane objective: 40.696643, primal objective 47.097754 -iteration 430 -cutting plane objective: 40.717111, primal objective 46.605956 -iteration 431 -cutting plane objective: 40.745395, primal objective 46.562990 -iteration 432 -cutting plane objective: 40.765295, primal objective 46.562799 -iteration 433 -cutting plane objective: 40.787529, primal objective 45.675705 -iteration 434 -cutting plane objective: 40.896790, primal objective 57.064382 -iteration 435 -cutting plane objective: 40.984176, primal objective 53.717002 -iteration 436 -cutting plane objective: 41.055439, primal objective 51.564877 -iteration 437 -cutting plane objective: 41.121984, primal objective 50.882540 -iteration 438 -cutting plane objective: 41.182713, primal objective 52.106853 -iteration 439 -cutting plane objective: 41.240129, primal objective 51.884299 -iteration 440 -cutting plane objective: 41.314679, primal objective 52.423110 -iteration 441 -cutting plane objective: 41.366143, primal objective 51.175604 -iteration 442 -cutting plane objective: 41.415077, primal objective 51.068580 -iteration 443 -cutting plane objective: 41.453352, primal objective 50.806076 -iteration 444 -cutting plane objective: 41.511131, primal objective 50.004755 -iteration 445 -cutting plane objective: 41.557386, primal objective 50.560701 -iteration 446 -cutting plane objective: 41.605809, primal objective 49.436283 -iteration 447 -cutting plane objective: 41.648209, primal objective 49.520643 -iteration 448 -cutting plane objective: 41.676554, primal objective 50.325978 -iteration 449 -cutting plane objective: 41.718070, primal objective 48.442864 -iteration 450 -cutting plane objective: 41.744915, primal objective 49.775659 -iteration 451 -cutting plane objective: 41.767760, primal objective 48.555874 -iteration 452 -cutting plane objective: 41.800355, primal objective 48.567181 -iteration 453 -cutting plane objective: 41.830157, primal objective 48.108429 -iteration 454 -cutting plane objective: 41.860966, primal objective 47.891200 -iteration 455 -cutting plane objective: 41.881486, primal objective 48.410518 -iteration 456 -cutting plane objective: 41.903566, primal objective 48.465374 -iteration 457 -cutting plane objective: 41.927494, primal objective 47.537310 -iteration 458 -cutting plane objective: 41.952757, primal objective 47.963777 -iteration 459 -cutting plane objective: 41.980442, primal objective 48.113021 -iteration 460 -cutting plane objective: 41.996905, primal objective 48.025304 -iteration 461 -cutting plane objective: 42.025225, primal objective 47.569929 -iteration 462 -cutting plane objective: 42.044505, primal objective 47.512155 -iteration 463 -cutting plane objective: 42.064035, primal objective 47.448036 -iteration 464 -cutting plane objective: 42.084959, primal objective 46.845952 -iteration 465 -cutting plane objective: 42.100841, primal objective 47.224497 -iteration 466 -cutting plane objective: 42.116083, primal objective 47.052681 -iteration 467 -cutting plane objective: 42.132631, primal objective 46.514931 -iteration 468 -cutting plane objective: 42.145579, primal objective 46.840112 -iteration 469 -cutting plane objective: 42.163848, primal objective 46.682447 -iteration 470 -cutting plane objective: 42.179220, primal objective 46.583182 -iteration 471 -cutting plane objective: 42.192965, primal objective 46.752422 -iteration 472 -cutting plane objective: 42.205050, primal objective 46.690550 -iteration 473 -cutting plane objective: 42.217534, primal objective 46.582640 -iteration 474 -cutting plane objective: 42.227564, primal objective 46.342950 -iteration 475 -cutting plane objective: 42.241381, primal objective 46.026060 -iteration 476 -cutting plane objective: 42.312613, primal objective 55.306993 -iteration 477 -cutting plane objective: 42.361664, primal objective 51.641100 -iteration 478 -cutting plane objective: 42.425387, primal objective 49.840399 -iteration 479 -cutting plane objective: 42.470515, primal objective 49.693245 -iteration 480 -cutting plane objective: 42.513243, primal objective 50.136865 -iteration 481 -cutting plane objective: 42.555074, primal objective 50.914155 -iteration 482 -cutting plane objective: 42.592809, primal objective 49.228776 -iteration 483 -cutting plane objective: 42.631904, primal objective 49.165645 -iteration 484 -cutting plane objective: 42.670521, primal objective 48.968778 -iteration 485 -cutting plane objective: 42.698786, primal objective 49.238600 -iteration 486 -cutting plane objective: 42.721514, primal objective 48.725163 -iteration 487 -cutting plane objective: 42.745387, primal objective 48.035692 -iteration 488 -cutting plane objective: 42.775211, primal objective 48.432481 -iteration 489 -cutting plane objective: 42.801522, primal objective 48.370978 -iteration 490 -cutting plane objective: 42.824307, primal objective 48.124140 -iteration 491 -cutting plane objective: 42.844942, primal objective 48.363060 -iteration 492 -cutting plane objective: 42.863712, primal objective 47.864942 -iteration 493 -cutting plane objective: 42.887789, primal objective 47.647711 -iteration 494 -cutting plane objective: 42.910830, primal objective 47.773211 -iteration 495 -cutting plane objective: 42.931775, primal objective 47.918808 -iteration 496 -cutting plane objective: 42.951648, primal objective 47.806290 -iteration 497 -cutting plane objective: 42.972117, primal objective 47.514832 -iteration 498 -cutting plane objective: 42.992297, primal objective 47.612411 -iteration 499 -cutting plane objective: 43.010329, primal objective 47.234518 -iteration 500 -cutting plane objective: 43.025491, primal objective 47.310092 -iteration 501 -cutting plane objective: 43.037983, primal objective 47.098889 -iteration 502 -cutting plane objective: 43.049242, primal objective 47.304889 -iteration 503 -cutting plane objective: 43.061689, primal objective 46.723948 -iteration 504 -cutting plane objective: 43.075889, primal objective 47.050410 -iteration 505 -cutting plane objective: 43.089906, primal objective 47.480244 -iteration 506 -cutting plane objective: 43.100336, primal objective 46.807853 -iteration 507 -cutting plane objective: 43.108938, primal objective 46.767303 -iteration 508 -cutting plane objective: 43.121109, primal objective 46.369990 -iteration 509 -cutting plane objective: 43.130531, primal objective 46.530540 -iteration 510 -cutting plane objective: 43.141865, primal objective 46.419028 -iteration 511 -cutting plane objective: 43.154182, primal objective 46.617030 -iteration 512 -cutting plane objective: 43.164501, primal objective 46.558451 -iteration 513 -cutting plane objective: 43.174198, primal objective 46.807876 -iteration 514 -cutting plane objective: 43.183043, primal objective 46.260739 -iteration 515 -cutting plane objective: 43.223603, primal objective 52.834861 -iteration 516 -cutting plane objective: 43.273979, primal objective 50.375055 -iteration 517 -cutting plane objective: 43.311721, primal objective 50.707909 -iteration 518 -cutting plane objective: 43.352673, primal objective 49.640318 -iteration 519 -cutting plane objective: 43.384107, primal objective 49.918813 -iteration 520 -cutting plane objective: 43.416465, primal objective 49.274893 -iteration 521 -cutting plane objective: 43.452441, primal objective 49.272775 -iteration 522 -cutting plane objective: 43.481801, primal objective 49.240485 -iteration 523 -cutting plane objective: 43.505703, primal objective 49.058759 -iteration 524 -cutting plane objective: 43.530733, primal objective 48.450409 -iteration 525 -cutting plane objective: 43.547577, primal objective 49.038355 -iteration 526 -cutting plane objective: 43.575319, primal objective 48.581374 -iteration 527 -cutting plane objective: 43.595171, primal objective 48.054213 -iteration 528 -cutting plane objective: 43.607938, primal objective 47.912996 -iteration 529 -cutting plane objective: 43.626134, primal objective 47.450004 -iteration 530 -cutting plane objective: 43.646514, primal objective 47.995381 -iteration 531 -cutting plane objective: 43.667569, primal objective 48.085065 -iteration 532 -cutting plane objective: 43.686676, primal objective 48.007830 -iteration 533 -cutting plane objective: 43.712646, primal objective 48.249849 -iteration 534 -cutting plane objective: 43.730066, primal objective 48.326927 -iteration 535 -cutting plane objective: 43.745561, primal objective 47.714256 -iteration 536 -cutting plane objective: 43.758292, primal objective 47.529434 -iteration 537 -cutting plane objective: 43.771064, primal objective 47.570419 -iteration 538 -cutting plane objective: 43.785719, primal objective 47.435847 -iteration 539 -cutting plane objective: 43.798947, primal objective 47.243962 -iteration 540 -cutting plane objective: 43.810558, primal objective 47.571412 -iteration 541 -cutting plane objective: 43.823964, primal objective 47.598628 -iteration 542 -cutting plane objective: 43.834684, primal objective 47.086703 -iteration 543 -cutting plane objective: 43.847696, primal objective 47.442380 -iteration 544 -cutting plane objective: 43.857997, primal objective 46.727770 -iteration 545 -cutting plane objective: 43.865595, primal objective 46.705302 -iteration 546 -cutting plane objective: 43.872454, primal objective 47.118972 -iteration 547 -cutting plane objective: 43.880550, primal objective 46.706461 -iteration 548 -cutting plane objective: 43.884495, primal objective 46.795411 -iteration 549 -cutting plane objective: 43.893036, primal objective 46.387726 -iteration 550 -cutting plane objective: 43.901140, primal objective 46.835442 -iteration 551 -cutting plane objective: 43.909026, primal objective 46.766550 -iteration 552 -cutting plane objective: 43.917524, primal objective 46.662896 -iteration 553 -cutting plane objective: 43.927945, primal objective 46.469632 -iteration 554 -cutting plane objective: 43.936893, primal objective 46.422914 -iteration 555 -cutting plane objective: 43.944849, primal objective 46.635197 -iteration 556 -cutting plane objective: 43.951799, primal objective 46.530667 -iteration 557 -cutting plane objective: 43.960817, primal objective 46.385541 -iteration 558 -cutting plane objective: 43.968528, primal objective 46.625885 -iteration 559 -cutting plane objective: 43.973768, primal objective 46.288062 -iteration 560 -cutting plane objective: 43.993339, primal objective 52.113207 -iteration 561 -cutting plane objective: 44.025552, primal objective 49.554422 -iteration 562 -cutting plane objective: 44.051588, primal objective 49.119559 -iteration 563 -cutting plane objective: 44.077695, primal objective 49.130734 -iteration 564 -cutting plane objective: 44.102586, primal objective 48.926756 -iteration 565 -cutting plane objective: 44.115489, primal objective 48.387668 -iteration 566 -cutting plane objective: 44.128857, primal objective 48.022978 -iteration 567 -cutting plane objective: 44.142789, primal objective 47.998367 -iteration 568 -cutting plane objective: 44.157361, primal objective 47.559019 -iteration 569 -cutting plane objective: 44.172283, primal objective 48.233456 -iteration 570 -cutting plane objective: 44.184643, primal objective 48.208925 -iteration 571 -cutting plane objective: 44.196357, primal objective 47.906139 -iteration 572 -cutting plane objective: 44.212569, primal objective 48.087980 -iteration 573 -cutting plane objective: 44.223039, primal objective 47.721440 -iteration 574 -cutting plane objective: 44.233750, primal objective 47.686926 -iteration 575 -cutting plane objective: 44.248568, primal objective 47.455357 -iteration 576 -cutting plane objective: 44.261516, primal objective 47.728046 -iteration 577 -cutting plane objective: 44.272153, primal objective 47.088333 -iteration 578 -cutting plane objective: 44.283592, primal objective 47.423833 -iteration 579 -cutting plane objective: 44.294738, primal objective 47.352999 -iteration 580 -cutting plane objective: 44.304950, primal objective 47.232698 -iteration 581 -cutting plane objective: 44.313504, primal objective 47.240919 -iteration 582 -cutting plane objective: 44.323404, primal objective 47.267722 -iteration 583 -cutting plane objective: 44.332864, primal objective 47.208191 -iteration 584 -cutting plane objective: 44.341748, primal objective 47.153929 -iteration 585 -cutting plane objective: 44.348483, primal objective 46.898137 -iteration 586 -cutting plane objective: 44.354968, primal objective 47.082592 -iteration 587 -cutting plane objective: 44.360294, primal objective 46.801816 -iteration 588 -cutting plane objective: 44.366586, primal objective 46.988810 -iteration 589 -cutting plane objective: 44.372775, primal objective 46.582295 -iteration 590 -cutting plane objective: 44.378990, primal objective 46.541389 -iteration 591 -cutting plane objective: 44.383805, primal objective 46.531858 -iteration 592 -cutting plane objective: 44.389199, primal objective 46.523805 -iteration 593 -cutting plane objective: 44.394177, primal objective 46.528430 -iteration 594 -cutting plane objective: 44.400049, primal objective 46.440173 -iteration 595 -cutting plane objective: 44.404562, primal objective 46.548270 -iteration 596 -cutting plane objective: 44.408784, primal objective 46.470540 -iteration 597 -new constraint too weak. -cutting plane objective: 44.439824, primal objective 49.378301 -iteration 598 -cutting plane objective: 44.465954, primal objective 48.777049 -iteration 599 -cutting plane objective: 44.485542, primal objective 48.678252 -iteration 600 -cutting plane objective: 44.504180, primal objective 48.610474 -iteration 601 -cutting plane objective: 44.524295, primal objective 48.249795 -iteration 602 -cutting plane objective: 44.542621, primal objective 48.091666 -iteration 603 -cutting plane objective: 44.557350, primal objective 47.969619 -iteration 604 -cutting plane objective: 44.568825, primal objective 48.322974 -iteration 605 -cutting plane objective: 44.583878, primal objective 47.837242 -iteration 606 -cutting plane objective: 44.598342, primal objective 47.607253 -iteration 607 -cutting plane objective: 44.605554, primal objective 48.060459 -iteration 608 -cutting plane objective: 44.617795, primal objective 47.753131 -iteration 609 -cutting plane objective: 44.625449, primal objective 47.354934 -iteration 610 -cutting plane objective: 44.632955, primal objective 47.320574 -iteration 611 -cutting plane objective: 44.640633, primal objective 47.440613 -iteration 612 -cutting plane objective: 44.649716, primal objective 47.495059 -iteration 613 -cutting plane objective: 44.659672, primal objective 47.470130 -iteration 614 -cutting plane objective: 44.666983, primal objective 47.241963 -iteration 615 -cutting plane objective: 44.676545, primal objective 47.058892 -iteration 616 -cutting plane objective: 44.685557, primal objective 47.285583 -iteration 617 -cutting plane objective: 44.693247, primal objective 47.287941 -iteration 618 -cutting plane objective: 44.701508, primal objective 47.030915 -iteration 619 -cutting plane objective: 44.707170, primal objective 47.163261 -iteration 620 -cutting plane objective: 44.713266, primal objective 46.969104 -iteration 621 -cutting plane objective: 44.719528, primal objective 46.832278 -iteration 622 -cutting plane objective: 44.725387, primal objective 46.922858 -iteration 623 -cutting plane objective: 44.730540, primal objective 46.786663 -iteration 624 -cutting plane objective: 44.736461, primal objective 46.825526 -iteration 625 -new constraint too weak. -cutting plane objective: 44.752083, primal objective 48.774799 -iteration 626 -cutting plane objective: 44.769423, primal objective 47.997275 -iteration 627 -cutting plane objective: 44.781747, primal objective 48.072543 -iteration 628 -cutting plane objective: 44.792405, primal objective 48.082034 -iteration 629 -cutting plane objective: 44.800988, primal objective 47.803370 -iteration 630 -cutting plane objective: 44.809933, primal objective 47.634412 -iteration 631 -cutting plane objective: 44.818328, primal objective 47.418097 -iteration 632 -cutting plane objective: 44.828383, primal objective 47.606751 -iteration 633 -cutting plane objective: 44.836258, primal objective 47.652823 -iteration 634 -cutting plane objective: 44.844533, primal objective 47.365089 -iteration 635 -cutting plane objective: 44.853619, primal objective 47.478129 -iteration 636 -cutting plane objective: 44.861697, primal objective 47.460959 -iteration 637 -cutting plane objective: 44.868637, primal objective 47.316038 -iteration 638 -cutting plane objective: 44.874854, primal objective 47.381950 -iteration 639 -cutting plane objective: 44.880335, primal objective 47.204120 -iteration 640 -cutting plane objective: 44.885732, primal objective 47.162493 -iteration 641 -cutting plane objective: 44.891993, primal objective 47.156626 -iteration 642 -cutting plane objective: 44.899067, primal objective 47.096594 -iteration 643 -cutting plane objective: 44.903889, primal objective 47.100602 -iteration 644 -cutting plane objective: 44.909042, primal objective 47.210688 -iteration 645 -cutting plane objective: 44.915139, primal objective 46.956284 -iteration 646 -new constraint too weak. -cutting plane objective: 44.926472, primal objective 48.027930 -iteration 647 -cutting plane objective: 44.936515, primal objective 47.775455 -iteration 648 -cutting plane objective: 44.946557, primal objective 47.596100 -iteration 649 -cutting plane objective: 44.952651, primal objective 47.689936 -iteration 650 -cutting plane objective: 44.961395, primal objective 47.532969 -iteration 651 -cutting plane objective: 44.968138, primal objective 47.631642 -iteration 652 -cutting plane objective: 44.975903, primal objective 47.541158 -iteration 653 -cutting plane objective: 44.982206, primal objective 47.445009 -iteration 654 -cutting plane objective: 44.990649, primal objective 47.330042 -iteration 655 -cutting plane objective: 44.998674, primal objective 47.453943 -iteration 656 -cutting plane objective: 45.003591, primal objective 47.411593 -iteration 657 -cutting plane objective: 45.010570, primal objective 47.479892 -iteration 658 -cutting plane objective: 45.016379, primal objective 47.154594 -iteration 659 -cutting plane objective: 45.021874, primal objective 47.108300 -iteration 660 -cutting plane objective: 45.027322, primal objective 47.188755 -iteration 661 -new constraint too weak. -cutting plane objective: 45.036116, primal objective 47.617069 -iteration 662 -cutting plane objective: 45.043593, primal objective 47.304272 -iteration 663 -cutting plane objective: 45.051923, primal objective 47.455887 -iteration 664 -cutting plane objective: 45.059136, primal objective 47.647937 -iteration 665 -cutting plane objective: 45.065383, primal objective 47.422196 -iteration 666 -cutting plane objective: 45.071971, primal objective 47.212878 -iteration 667 -cutting plane objective: 45.077455, primal objective 47.131600 -iteration 668 -cutting plane objective: 45.084012, primal objective 47.224766 -iteration 669 -cutting plane objective: 45.089605, primal objective 47.136758 -iteration 670 -cutting plane objective: 45.095178, primal objective 47.146985 -iteration 671 -cutting plane objective: 45.100633, primal objective 47.098961 -iteration 672 -new constraint too weak. -cutting plane objective: 45.107283, primal objective 47.520703 -iteration 673 -cutting plane objective: 45.114744, primal objective 47.407076 -iteration 674 -cutting plane objective: 45.121579, primal objective 47.343884 -iteration 675 -cutting plane objective: 45.128382, primal objective 47.341440 -iteration 676 -cutting plane objective: 45.132699, primal objective 47.271365 -iteration 677 -new constraint too weak. -cutting plane objective: 45.140261, primal objective 47.569480 -iteration 678 -cutting plane objective: 45.147898, primal objective 47.665761 -iteration 679 -cutting plane objective: 45.157485, primal objective 47.479075 -iteration 680 -cutting plane objective: 45.165177, primal objective 47.632770 -iteration 681 -cutting plane objective: 45.172476, primal objective 47.618447 -iteration 682 -cutting plane objective: 45.180181, primal objective 47.720736 -iteration 683 -cutting plane objective: 45.188574, primal objective 47.561174 -iteration 684 -cutting plane objective: 45.197416, primal objective 47.773228 -iteration 685 -cutting plane objective: 45.205932, primal objective 47.471479 -iteration 686 -cutting plane objective: 45.213801, primal objective 47.935943 -iteration 687 -cutting plane objective: 45.222835, primal objective 47.769860 -iteration 688 -cutting plane objective: 45.230366, primal objective 47.583348 -iteration 689 -cutting plane objective: 45.237364, primal objective 47.766477 -iteration 690 -cutting plane objective: 45.244965, primal objective 47.582993 -iteration 691 -cutting plane objective: 45.251357, primal objective 47.698541 -iteration 692 -cutting plane objective: 45.258899, primal objective 47.520509 -iteration 693 -cutting plane objective: 45.267206, primal objective 47.326435 -iteration 694 -cutting plane objective: 45.274819, primal objective 47.748319 -iteration 695 -cutting plane objective: 45.282694, primal objective 47.733576 -iteration 696 -cutting plane objective: 45.288299, primal objective 47.558968 -iteration 697 -cutting plane objective: 45.295173, primal objective 47.373888 -iteration 698 -new constraint too weak. -cutting plane objective: 45.301986, primal objective 47.565159 -iteration 699 -cutting plane objective: 45.308397, primal objective 47.657055 -iteration 700 -cutting plane objective: 45.316628, primal objective 47.775878 -iteration 701 -cutting plane objective: 45.326118, primal objective 47.540368 -iteration 702 -cutting plane objective: 45.331291, primal objective 47.741623 -iteration 703 -cutting plane objective: 45.338424, primal objective 47.530808 -iteration 704 -cutting plane objective: 45.343557, primal objective 47.662534 -iteration 705 -cutting plane objective: 45.349114, primal objective 47.360803 -iteration 706 -cutting plane objective: 45.355668, primal objective 47.373585 -iteration 707 -cutting plane objective: 45.361184, primal objective 47.398588 -iteration 708 -cutting plane objective: 45.367670, primal objective 47.382663 -iteration 709 -cutting plane objective: 45.374293, primal objective 47.371971 -iteration 710 -cutting plane objective: 45.379615, primal objective 47.520312 -iteration 711 -cutting plane objective: 45.384749, primal objective 47.428997 -iteration 712 -new constraint too weak. -cutting plane objective: 45.389687, primal objective 47.520781 -iteration 713 -new constraint too weak. -new constraint too weak. -no additional constraints -final primal objective: 47.218747 gap: 1.829060 -Results using also input features for edges -Test accuracy: 0.996 -[[2749 0 0 0 0 0 0 0 1 0 0] - [ 0 100 0 0 0 0 0 0 0 0 0] - [ 0 0 100 0 0 0 0 0 0 0 0] - [ 0 0 0 100 0 0 0 0 0 0 0] - [ 0 0 0 0 98 0 1 0 1 0 0] - [ 0 0 0 2 0 98 0 0 0 0 0] - [ 0 0 0 0 2 0 98 0 0 0 0] - [ 0 1 0 0 0 2 0 97 0 0 0] - [ 0 0 1 0 0 0 1 0 98 0 0] - [ 0 0 0 1 0 0 0 0 0 99 0] - [ 0 0 0 0 1 0 0 0 0 0 99]] diff --git a/pystruct/__init__.py b/pystruct/__init__.py index 4ad67eb7..260c070a 100644 --- a/pystruct/__init__.py +++ b/pystruct/__init__.py @@ -1 +1 @@ -__version__ = "0.3.8" +__version__ = "0.3.1" diff --git a/setup.py b/setup.py index afab2f13..bb75bd10 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ include_dirs = [np.get_include()] setup(name="pystruct", - version="0.2.5", + version="0.3.1", install_requires=["ad3", "numpy"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', From 2dc862b4110d373a28be032e61656d2495755873 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 19 Jul 2018 16:59:40 +0200 Subject: [PATCH 145/155] 0.3RC2 --- .travis.yml | 2 + pystruct/inference/inference_methods.py | 5 - pystruct/tests/pytest-0.3.3.log | 703 ------------------------ setup.py | 1 - 4 files changed, 2 insertions(+), 709 deletions(-) delete mode 100644 pystruct/tests/pytest-0.3.3.log diff --git a/.travis.yml b/.travis.yml index b0d06ef8..3673eff9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,6 +31,8 @@ env: # python3.5 only because of cvxopt? - DISTRIB="conda3" PYTHON_VERSION="3.5" OPENGM="false" NUMPY_VERSION="1.13" SCIPY_VERSION="1.0" + - DISTRIB="conda3" PYTHON_VERSION="3.6" OPENGM="false" + NUMPY_VERSION="1.14" SCIPY_VERSION="1.1" install: source continuous_integration/install.sh script: bash continuous_integration/test_script.sh after_success: diff --git a/pystruct/inference/inference_methods.py b/pystruct/inference/inference_methods.py index 26bc19df..1b85793c 100644 --- a/pystruct/inference/inference_methods.py +++ b/pystruct/inference/inference_methods.py @@ -497,11 +497,6 @@ def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges Approximate (usually) MAP variable assignment. If relaxed=False, this is a tuple of unary and edge 'marginals'. - Code written on Feb 2017 to deal with multiple node types, by JL Meunier, - for the EU READ project (grant agreement No 674943) - - JL Meunier - """ import ad3 # n_states, pairwise_potentials = \ diff --git a/pystruct/tests/pytest-0.3.3.log b/pystruct/tests/pytest-0.3.3.log deleted file mode 100644 index 572d4d7a..00000000 --- a/pystruct/tests/pytest-0.3.3.log +++ /dev/null @@ -1,703 +0,0 @@ -============================= test session starts ============================== -platform linux2 -- Python 2.7.8, pytest-3.0.5, py-1.4.32, pluggy-0.4.0 -rootdir: /opt/project/read/jl_git/pystruct_JL, inifile: -collected 150 items - -test_datasets.py . -test_libraries.py FF -test_inference/test_exact_inference.py . -test_inference/test_maxprod.py ..FF..FF -test_learners/test_binary_svm.py ....... -test_learners/test_crammer_singer_svm.py ......... -test_learners/test_edge_feature_graph_learning.py .. -test_learners/test_frankwolfe_svm.py .... -test_learners/test_graph_svm.py ... -test_learners/test_latent_node_crf_learning.py F.... -test_learners/test_latent_svm.py ..... -test_learners/test_n_slack_ssvm.py ......... -test_learners/test_one_slack_ssvm.py ........ -test_learners/test_perceptron.py ....... -test_learners/test_structured_perceptron.py .. -test_learners/test_subgradient_latent_svm.py ... -test_learners/test_subgradient_svm.py ...... -test_models/test_chain_crf.py .F -test_models/test_directional_crf.py .... -test_models/test_edge_feature_graph_crf.py ...... -test_models/test_graph_crf.py ......... -test_models/test_grid_crf.py .....FF... -test_models/test_latent_crf.py .............. -test_models/test_latent_node_crf.py ..... -test_models/test_multilabel_problem.py ... -test_models/test_node_type_edge_feature_graph_crf.py ........... -test_utils/test_utils_inference.py ... -test_utils/test_utils_logging.py . - -=================================== FAILURES =================================== -_________________________________ test_pyqpbo __________________________________ - - def test_pyqpbo(): - import pyqpbo - pyqpbo -> assert 'qpbo' in get_installed() - -test_libraries.py:7: -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ -../inference/inference_methods.py:17: in get_installed - inference_dispatch(unary, pw, edges, inference_method=method) -../inference/inference_methods.py:100: in inference_dispatch - return_energy=return_energy, **kwargs) -../inference/inference_methods.py:474: in inference_ad3plus - n_iterations=4000, exact=branch_and_bound) -../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:44: in general_constrained_graph - return general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose, n_iterations, eta, exact) -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - -unaries = array([[ 0.]]), edges = array([], shape=(0, 2), dtype=int64) -edge_weights = array([[ 0.]]), constraints = None, verbose = 0 -n_iterations = 4000, eta = 0.1, exact = False - - def general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose=1, n_iterations=1000, eta=0.1, exact=False): - """ - inference on a graph, with one type of node, taking into account logical constraints between unaries. - - The constraints must be a list of tuples like ( , , , ) - The tuple is defined differently for single- and multi-type inference. See in each function below. - - where: - - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' - - unaries is a list of the index of the unaries involved in this constraint - - states is a list of unary states, 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. - - negated is a list of boolean indicated if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list - - The graph is binarized as explained in Martins et al. ICML 2011 paper: "An Augmented Lagrangian Approach to Constrained MAP Inference". - - NOTE: I had to re-compile AD3 since v2.0.1 from Anaconda missed the create_binary_variable method - - JL Meunier - October 2016 - """ - if unaries.shape[1] != edge_weights.shape[1]: - raise ValueError("incompatible shapes of unaries" - " and edge_weights.") -> if edge_weights.shape[1] != edge_weights.shape[2]: -E IndexError: tuple index out of range - -../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:70: IndexError -___________________________________ test_ad3 ___________________________________ - - def test_ad3(): - import ad3 - ad3 -> assert 'ad3' in get_installed() - -test_libraries.py:13: -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ -../inference/inference_methods.py:17: in get_installed - inference_dispatch(unary, pw, edges, inference_method=method) -../inference/inference_methods.py:100: in inference_dispatch - return_energy=return_energy, **kwargs) -../inference/inference_methods.py:474: in inference_ad3plus - n_iterations=4000, exact=branch_and_bound) -../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:44: in general_constrained_graph - return general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose, n_iterations, eta, exact) -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - -unaries = array([[ 0.]]), edges = array([], shape=(0, 2), dtype=int64) -edge_weights = array([[ 0.]]), constraints = None, verbose = 0 -n_iterations = 4000, eta = 0.1, exact = False - - def general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose=1, n_iterations=1000, eta=0.1, exact=False): - """ - inference on a graph, with one type of node, taking into account logical constraints between unaries. - - The constraints must be a list of tuples like ( , , , ) - The tuple is defined differently for single- and multi-type inference. See in each function below. - - where: - - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' - - unaries is a list of the index of the unaries involved in this constraint - - states is a list of unary states, 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. - - negated is a list of boolean indicated if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list - - The graph is binarized as explained in Martins et al. ICML 2011 paper: "An Augmented Lagrangian Approach to Constrained MAP Inference". - - NOTE: I had to re-compile AD3 since v2.0.1 from Anaconda missed the create_binary_variable method - - JL Meunier - October 2016 - """ - if unaries.shape[1] != edge_weights.shape[1]: - raise ValueError("incompatible shapes of unaries" - " and edge_weights.") -> if edge_weights.shape[1] != edge_weights.shape[2]: -E IndexError: tuple index out of range - -../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:70: IndexError -_________________________ test_tree_max_product_chain __________________________ - - def test_tree_max_product_chain(): - rnd = np.random.RandomState(0) - forward = np.c_[np.arange(9), np.arange(1, 10)] - backward = np.c_[np.arange(1, 10), np.arange(9)] - for i in range(10): - unary_potentials = rnd.normal(size=(10, 3)) - pairwise_potentials = rnd.normal(size=(9, 3, 3)) - for chain in [forward, backward]: - result_ad3 = inference_ad3(unary_potentials, pairwise_potentials, - chain, branch_and_bound=True) - result_mp = inference_max_product(unary_potentials, -> pairwise_potentials, chain) - -test_inference/test_maxprod.py:70: -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - -unary_potentials = array([[ 1.76405235, 0.40015721, 0.97873798], - [ 2.2408932 , 1.867557...62, -1.45436567, 0.04575852], - [-0.18718385, 1.53277921, 1.46935877]]) -pairwise_potentials = array([[[ 0.15494743, 0.37816252, -0.88778575], - [-1.98079647, -0.3479..., -0.41361898, -0.74745481], - [ 1.92294203, 1.48051479, 1.86755896]]]) -edges = array([[0, 1], - [1, 2], - [2, 3], - [3, 4], - [4, 5], - [5, 6], - [6, 7], - [7, 8], - [8, 9]]) -max_iter = 30, damping = 0.5, tol = 1e-05, relaxed = None - - def inference_max_product(unary_potentials, pairwise_potentials, edges, - max_iter=30, damping=0.5, tol=1e-5, relaxed=None): - """Max-product inference. - - In case the edges specify a tree, dynamic programming is used - producing a result in only a single pass. - - Parameters - ---------- - unary_potentials : nd-array - Unary potentials of energy function. - - pairwise_potentials : nd-array - Pairwise potentials of energy function. - - edges : nd-array - Edges of energy function. - - max_iter : int (default=10) - Maximum number of iterations. Ignored if graph is a tree. - - damping : float (default=.5) - Daming of messages in loopy message passing. - Ignored if graph is a tree. - - tol : float (default=1e-5) - Stopping tollerance for loopy message passing. - """ -> from ._viterbi import viterbi -E ImportError: No module named _viterbi - -../inference/maxprod.py:50: ImportError -__________________________ test_tree_max_product_tree __________________________ - - def test_tree_max_product_tree(): - try: - from scipy.sparse.csgraph import minimum_spanning_tree - except: - raise SkipTest("Not testing trees, scipy version >= 0.11 required") - - rnd = np.random.RandomState(0) - for i in range(100): - # generate random tree using mst - graph = rnd.uniform(size=(10, 10)) - tree = minimum_spanning_tree(sparse.csr_matrix(graph)) - tree_edges = np.c_[tree.nonzero()] - - unary_potentials = rnd.normal(size=(10, 3)) - pairwise_potentials = rnd.normal(size=(9, 3, 3)) - result_ad3 = inference_ad3(unary_potentials, pairwise_potentials, - tree_edges, branch_and_bound=True) - result_mp = inference_max_product(unary_potentials, -> pairwise_potentials, tree_edges) - -test_inference/test_maxprod.py:92: -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - -unary_potentials = array([[-1.16514984, 0.90082649, 0.46566244], - [-1.53624369, 1.488252...41, 1.94362119, -0.41361898], - [-0.74745481, 1.92294203, 1.48051479]]) -pairwise_potentials = array([[[ 1.86755896, 0.90604466, -0.86122569], - [ 1.91006495, -0.2680..., -1.10438334, 0.05216508], - [-0.739563 , 1.5430146 , -1.29285691]]]) -edges = array([[1, 4], - [1, 5], - [1, 6], - [3, 4], - [6, 0], - [7, 5], - [8, 2], - [8, 7], - [9, 7]], dtype=int32) -max_iter = 30, damping = 0.5, tol = 1e-05, relaxed = None - - def inference_max_product(unary_potentials, pairwise_potentials, edges, - max_iter=30, damping=0.5, tol=1e-5, relaxed=None): - """Max-product inference. - - In case the edges specify a tree, dynamic programming is used - producing a result in only a single pass. - - Parameters - ---------- - unary_potentials : nd-array - Unary potentials of energy function. - - pairwise_potentials : nd-array - Pairwise potentials of energy function. - - edges : nd-array - Edges of energy function. - - max_iter : int (default=10) - Maximum number of iterations. Ignored if graph is a tree. - - damping : float (default=.5) - Daming of messages in loopy message passing. - Ignored if graph is a tree. - - tol : float (default=1e-5) - Stopping tollerance for loopy message passing. - """ -> from ._viterbi import viterbi -E ImportError: No module named _viterbi - -../inference/maxprod.py:50: ImportError -________________________ test_max_product_binary_blocks ________________________ - - def test_max_product_binary_blocks(): - X, Y = generate_blocks(n_samples=1) - x, y = X[0], Y[0] - w = np.array([1, 0, # unary - 0, 1, - 0, # pairwise - -4, 0]) - crf = GridCRF(inference_method='max-product') - crf.initialize(X, Y) -> y_hat = crf.inference(x, w) - -test_inference/test_maxprod.py:139: -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ -../models/grid_crf.py:66: in inference - return_energy=return_energy) -../models/crf.py:178: in inference - return_energy=return_energy) -../inference/inference_methods.py:109: in inference_dispatch - edges, **kwargs) -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - -unary_potentials = array([[-1.64607852, 1.64607852], - [ 0.39976419, -0.39976419], - [...748486], - [-1.92111906, 1.92111906], - [-2.38331001, 2.38331001]]) -pairwise_potentials = array([[ 0., -4.], - [-4., 0.]]) -edges = array([[ 0, 1], - [ 1, 2], - [ 2, 3], - [ 3, 4], - ...], - [104, 116], - [105, 117], - [106, 118], - [107, 119]]) -max_iter = 30, damping = 0.5, tol = 1e-05, relaxed = False - - def inference_max_product(unary_potentials, pairwise_potentials, edges, - max_iter=30, damping=0.5, tol=1e-5, relaxed=None): - """Max-product inference. - - In case the edges specify a tree, dynamic programming is used - producing a result in only a single pass. - - Parameters - ---------- - unary_potentials : nd-array - Unary potentials of energy function. - - pairwise_potentials : nd-array - Pairwise potentials of energy function. - - edges : nd-array - Edges of energy function. - - max_iter : int (default=10) - Maximum number of iterations. Ignored if graph is a tree. - - damping : float (default=.5) - Daming of messages in loopy message passing. - Ignored if graph is a tree. - - tol : float (default=1e-5) - Stopping tollerance for loopy message passing. - """ -> from ._viterbi import viterbi -E ImportError: No module named _viterbi - -../inference/maxprod.py:50: ImportError -_______________________ test_max_product_multinomial_crf _______________________ - - def test_max_product_multinomial_crf(): - X, Y = generate_blocks_multinomial(n_samples=1) - x, y = X[0], Y[0] - w = np.array([1., 0., 0., # unary - 0., 1., 0., - 0., 0., 1., - .4, # pairwise - -.3, .3, - -.5, -.1, .3]) - crf = GridCRF(inference_method='max-product') - crf.initialize(X, Y) -> y_hat = crf.inference(x, w) - -test_inference/test_maxprod.py:154: -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ -../models/grid_crf.py:66: in inference - return_energy=return_energy) -../models/crf.py:178: in inference - return_energy=return_energy) -../inference/inference_methods.py:109: in inference_dispatch - edges, **kwargs) -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - -unary_potentials = array([[ 1.18821277e+00, -5.49700395e-01, 1.49119087e-01], - [ 1.663....65956844e+00], - [ -4.41209409e-01, 5.64297032e-01, 1.24800047e+00]]) -pairwise_potentials = array([[ 0.4, -0.3, -0.5], - [-0.3, 0.3, -0.1], - [-0.5, -0.1, 0.3]]) -edges = array([[ 0, 1], - [ 1, 2], - [ 2, 3], - [ 3, 4], - ...], - [104, 116], - [105, 117], - [106, 118], - [107, 119]]) -max_iter = 30, damping = 0.5, tol = 1e-05, relaxed = False - - def inference_max_product(unary_potentials, pairwise_potentials, edges, - max_iter=30, damping=0.5, tol=1e-5, relaxed=None): - """Max-product inference. - - In case the edges specify a tree, dynamic programming is used - producing a result in only a single pass. - - Parameters - ---------- - unary_potentials : nd-array - Unary potentials of energy function. - - pairwise_potentials : nd-array - Pairwise potentials of energy function. - - edges : nd-array - Edges of energy function. - - max_iter : int (default=10) - Maximum number of iterations. Ignored if graph is a tree. - - damping : float (default=.5) - Daming of messages in loopy message passing. - Ignored if graph is a tree. - - tol : float (default=1e-5) - Stopping tollerance for loopy message passing. - """ -> from ._viterbi import viterbi -E ImportError: No module named _viterbi - -../inference/maxprod.py:50: ImportError -_________________ test_binary_blocks_cutting_plane_latent_node _________________ - - def test_binary_blocks_cutting_plane_latent_node(): - #testing cutting plane ssvm on easy binary dataset - # we use the LatentNodeCRF without latent nodes and check that it does the - # same as GraphCRF - X, Y = generate_blocks(n_samples=3) - crf = GraphCRF() - clf = NSlackSSVM(model=crf, max_iter=20, C=100, check_constraints=True, - break_on_bad=False, n_jobs=1) - x1, x2, x3 = X - y1, y2, y3 = Y - n_states = len(np.unique(Y)) - # delete some rows to make it more fun - x1, y1 = x1[:, :-1], y1[:, :-1] - x2, y2 = x2[:-1], y2[:-1] - # generate graphs - X_ = [x1, x2, x3] - G = [make_grid_edges(x) for x in X_] - - # reshape / flatten x and y - X_ = [x.reshape(-1, n_states) for x in X_] - Y = [y.ravel() for y in [y1, y2, y3]] - - X = list(zip(X_, G)) - - clf.fit(X, Y) - Y_pred = clf.predict(X) - for y, y_pred in zip(Y, Y_pred): - assert_array_equal(y, y_pred) - - latent_crf = LatentNodeCRF(n_labels=2, n_hidden_states=0) - latent_svm = LatentSSVM(NSlackSSVM(model=latent_crf, max_iter=20, C=100, - check_constraints=True, - break_on_bad=False, n_jobs=1), - latent_iter=3) - X_latent = list(zip(X_, G, np.zeros(len(X_)))) -> latent_svm.fit(X_latent, Y, H_init=Y) - -test_learners/test_latent_node_crf_learning.py:59: -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ -../learners/latent_structured_svm.py:123: in fit - initialize=False) -../learners/n_slack_ssvm.py:313: in fit - for x, y in zip(X_b, Y_b)) -../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py:804: in __call__ - while self.dispatch_one_batch(iterator): -../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py:662: in dispatch_one_batch - self._dispatch(tasks) -../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py:570: in _dispatch - job = ImmediateComputeBatch(batch) -../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py:183: in __init__ - self.results = batch() -../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py:72: in __call__ - return [func(*args, **kwargs) for func, args, kwargs in self.items] -../utils/inference.py:65: in find_constraint - y_hat = model.loss_augmented_inference(x, y, w, relaxed=relaxed) -../models/latent_node_crf.py:217: in loss_augmented_inference - unary_potentials = self._get_unary_potentials(x, w) -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - -self = LatentNodeCRF(n_states: 2, inference_method: ad3) -x = (array([[-1.64607852, 1.64607852], - [ 0.39976419, -0.39976419], - [...087795], - [-0.76748486, 0.767... 2, 3], - [ 3, 4], - ...], - [ 95, 106], - [ 96, 107], - [ 97, 108], - [ 98, 109]]), 0.0) -w = array([ 0., 0., 0., 0., 0., 0., 0.]) - - def _get_unary_potentials(self, x, w): - """Computes unary potentials for x and w. - - Parameters - ---------- - x : tuple - Instance Representation. - - w : ndarray, shape=(size_joint_feature,) - Weight vector for CRF instance. - - Returns - ------- - unary : ndarray, shape=(n_states) - Unary weights. - """ - self._check_size_w(w) - self._check_size_x(x) - features = self._get_features(x) - unary_params = w[:self.n_input_states * self.n_features].reshape( - self.n_input_states, self.n_features) - - if self.latent_node_features: - unaries = np.dot(features, unary_params.T) - n_hidden = x[2] - n_visible = features.shape[0] - n_hidden - else: - # we only have features for visible nodes - n_visible, n_hidden = features.shape[0], x[2] - # assemble unary potentials for all nodes from observed evidence -> unaries = np.zeros((n_visible + n_hidden, self.n_states)) -E TypeError: 'numpy.float64' object cannot be interpreted as an index - -../models/latent_node_crf.py:202: TypeError -_____________________________ test_directed_chain ______________________________ - - def test_directed_chain(): - # check that a directed model actually works differntly in the two - # directions. chain of length three, three states 0, 1, 2 which want to be - # in this order, evidence only in the middle - x = np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) - - w = np.array([1, 0, 0, # unary - 0, 1, 0, - 0, 0, 1, - 0, 1, 0, # pairwise - 0, 0, 1, - 0, 0, 0]) - crf = ChainCRF(n_states=3, n_features=3) -> y = crf.inference(x, w) - -test_models/test_chain_crf.py:41: -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ -../models/crf.py:178: in inference - return_energy=return_energy) -../inference/inference_methods.py:109: in inference_dispatch - edges, **kwargs) -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - -unary_potentials = array([[0, 0, 0], - [0, 1, 0], - [0, 0, 0]]) -pairwise_potentials = array([[0, 1, 0], - [0, 0, 1], - [0, 0, 0]]) -edges = array([[0, 1], - [1, 2]]), max_iter = 30, damping = 0.5 -tol = 1e-05, relaxed = False - - def inference_max_product(unary_potentials, pairwise_potentials, edges, - max_iter=30, damping=0.5, tol=1e-5, relaxed=None): - """Max-product inference. - - In case the edges specify a tree, dynamic programming is used - producing a result in only a single pass. - - Parameters - ---------- - unary_potentials : nd-array - Unary potentials of energy function. - - pairwise_potentials : nd-array - Pairwise potentials of energy function. - - edges : nd-array - Edges of energy function. - - max_iter : int (default=10) - Maximum number of iterations. Ignored if graph is a tree. - - damping : float (default=.5) - Daming of messages in loopy message passing. - Ignored if graph is a tree. - - tol : float (default=1e-5) - Stopping tollerance for loopy message passing. - """ -> from ._viterbi import viterbi -E ImportError: No module named _viterbi - -../inference/maxprod.py:50: ImportError -_________________________ test_blocks_multinomial_crf __________________________ - - def test_blocks_multinomial_crf(): - X, Y = generate_blocks_multinomial(n_samples=1, size_x=9, seed=0) - x, y = X[0], Y[0] - w = np.array([1., 0., 0., # unaryA - 0., 1., 0., - 0., 0., 1., - .4, # pairwise - -.3, .3, - -.5, -.1, .3]) -> for inference_method in get_installed(): - -test_models/test_grid_crf.py:123: -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ -../inference/inference_methods.py:17: in get_installed - inference_dispatch(unary, pw, edges, inference_method=method) -../inference/inference_methods.py:100: in inference_dispatch - return_energy=return_energy, **kwargs) -../inference/inference_methods.py:474: in inference_ad3plus - n_iterations=4000, exact=branch_and_bound) -../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:44: in general_constrained_graph - return general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose, n_iterations, eta, exact) -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - -unaries = array([[ 0.]]), edges = array([], shape=(0, 2), dtype=int64) -edge_weights = array([[ 0.]]), constraints = None, verbose = 0 -n_iterations = 4000, eta = 0.1, exact = False - - def general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose=1, n_iterations=1000, eta=0.1, exact=False): - """ - inference on a graph, with one type of node, taking into account logical constraints between unaries. - - The constraints must be a list of tuples like ( , , , ) - The tuple is defined differently for single- and multi-type inference. See in each function below. - - where: - - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' - - unaries is a list of the index of the unaries involved in this constraint - - states is a list of unary states, 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. - - negated is a list of boolean indicated if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list - - The graph is binarized as explained in Martins et al. ICML 2011 paper: "An Augmented Lagrangian Approach to Constrained MAP Inference". - - NOTE: I had to re-compile AD3 since v2.0.1 from Anaconda missed the create_binary_variable method - - JL Meunier - October 2016 - """ - if unaries.shape[1] != edge_weights.shape[1]: - raise ValueError("incompatible shapes of unaries" - " and edge_weights.") -> if edge_weights.shape[1] != edge_weights.shape[2]: -E IndexError: tuple index out of range - -../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:70: IndexError -___________________________ test_binary_grid_unaries ___________________________ - - def test_binary_grid_unaries(): - # test handling on unaries for binary grid CRFs - for ds in binary: - X, Y = ds(n_samples=1) - x, y = X[0], Y[0] -> for inference_method in get_installed(): - -test_models/test_grid_crf.py:135: -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ -../inference/inference_methods.py:17: in get_installed - inference_dispatch(unary, pw, edges, inference_method=method) -../inference/inference_methods.py:100: in inference_dispatch - return_energy=return_energy, **kwargs) -../inference/inference_methods.py:474: in inference_ad3plus - n_iterations=4000, exact=branch_and_bound) -../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:44: in general_constrained_graph - return general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose, n_iterations, eta, exact) -_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ - -unaries = array([[ 0.]]), edges = array([], shape=(0, 2), dtype=int64) -edge_weights = array([[ 0.]]), constraints = None, verbose = 0 -n_iterations = 4000, eta = 0.1, exact = False - - def general_constrained_graph_singletype(unaries, edges, edge_weights, constraints, verbose=1, n_iterations=1000, eta=0.1, exact=False): - """ - inference on a graph, with one type of node, taking into account logical constraints between unaries. - - The constraints must be a list of tuples like ( , , , ) - The tuple is defined differently for single- and multi-type inference. See in each function below. - - where: - - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' - - unaries is a list of the index of the unaries involved in this constraint - - states is a list of unary states, 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. - - negated is a list of boolean indicated if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list - - The graph is binarized as explained in Martins et al. ICML 2011 paper: "An Augmented Lagrangian Approach to Constrained MAP Inference". - - NOTE: I had to re-compile AD3 since v2.0.1 from Anaconda missed the create_binary_variable method - - JL Meunier - October 2016 - """ - if unaries.shape[1] != edge_weights.shape[1]: - raise ValueError("incompatible shapes of unaries" - " and edge_weights.") -> if edge_weights.shape[1] != edge_weights.shape[2]: -E IndexError: tuple index out of range - -../../../../VIRTUALENV_PYTHON_type/lib/python2.7/site-packages/ad3/simple_constrained_inference.py:70: IndexError -=================== 10 failed, 140 passed in 321.52 seconds ==================== diff --git a/setup.py b/setup.py index bb75bd10..24e81060 100644 --- a/setup.py +++ b/setup.py @@ -39,7 +39,6 @@ 'Operating System :: Unix', 'Operating System :: MacOS', 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', From fffe47faa4a54d3f6b797e4e3304ba1b85b99116 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 26 Jul 2018 10:24:06 +0200 Subject: [PATCH 146/155] bug fix for edge features + python3 --- examples/plot_snakes.py | 122 +++++++++++++++++++++------------------- 1 file changed, 64 insertions(+), 58 deletions(-) diff --git a/examples/plot_snakes.py b/examples/plot_snakes.py index 0292aec9..60710a9f 100644 --- a/examples/plot_snakes.py +++ b/examples/plot_snakes.py @@ -30,8 +30,10 @@ PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). But it does work as well as Decision Tree Fields ;) """ +from __future__ import (absolute_import, division, print_function) + import numpy as np -import matplotlib.pyplot as plt +# import matplotlib.pyplot as plt from sklearn.preprocessing import label_binarize from sklearn.metrics import confusion_matrix, accuracy_score @@ -84,66 +86,70 @@ def prepare_data(X): edge_features = np.zeros((edges.shape[0], features.shape[1], 4)) edge_features[:len(right), :, 0] = features[right[:, 0]] edge_features[:len(right), :, 1] = features[right[:, 1]] - edge_features[len(right):, :, 0] = features[down[:, 0]] - edge_features[len(right):, :, 1] = features[down[:, 1]] +#---ORIGINAL CODE +# edge_features[len(right):, :, 0] = features[down[:, 0]] +# edge_features[len(right):, :, 1] = features[down[:, 1]] + edge_features[len(right):, :, 2] = features[down[:, 0]] + edge_features[len(right):, :, 3] = features[down[:, 1]] +#---END OF FIX edge_features = edge_features.reshape(edges.shape[0], -1) X_directions.append((features, edges, edge_features_directions)) X_edge_features.append((features, edges, edge_features)) return X_directions, X_edge_features - -print("Please be patient. Learning will take 5-20 minutes.") -snakes = load_snakes() -X_train, Y_train = snakes['X_train'], snakes['Y_train'] - -X_train = [one_hot_colors(x) for x in X_train] -Y_train_flat = [y_.ravel() for y_ in Y_train] - -X_train_directions, X_train_edge_features = prepare_data(X_train) - -inference = 'qpbo' -# first, train on X with directions only: -crf = EdgeFeatureGraphCRF(inference_method=inference) -ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, +if __name__ == '__main__': + print("Please be patient. Learning will take 5-20 minutes.") + snakes = load_snakes() + X_train, Y_train = snakes['X_train'], snakes['Y_train'] + + X_train = [one_hot_colors(x) for x in X_train] + Y_train_flat = [y_.ravel() for y_ in Y_train] + + X_train_directions, X_train_edge_features = prepare_data(X_train) + + inference = 'qpbo' + # first, train on X with directions only: + crf = EdgeFeatureGraphCRF(inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, n_jobs=1) -ssvm.fit(X_train_directions, Y_train_flat) - -# Evaluate using confusion matrix. -# Clearly the middel of the snake is the hardest part. -X_test, Y_test = snakes['X_test'], snakes['Y_test'] -X_test = [one_hot_colors(x) for x in X_test] -Y_test_flat = [y_.ravel() for y_ in Y_test] -X_test_directions, X_test_edge_features = prepare_data(X_test) -Y_pred = ssvm.predict(X_test_directions) -print("Results using only directional features for edges") -print("Test accuracy: %.3f" - % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) -print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) - -# now, use more informative edge features: -crf = EdgeFeatureGraphCRF(inference_method=inference) -ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', - n_jobs=-1) -ssvm.fit(X_train_edge_features, Y_train_flat) -Y_pred2 = ssvm.predict(X_test_edge_features) -print("Results using also input features for edges") -print("Test accuracy: %.3f" - % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) -print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) - -# plot stuff -fig, axes = plt.subplots(2, 2) -axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') -axes[0, 0].set_title('Input') -y = Y_test[0].astype(np.int) -bg = 2 * (y != 0) # enhance contrast -axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) -axes[0, 1].set_title("Ground Truth") -axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) -axes[1, 0].set_title("Prediction w/o edge features") -axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) -axes[1, 1].set_title("Prediction with edge features") -for a in axes.ravel(): - a.set_xticks(()) - a.set_yticks(()) -plt.show() + ssvm.fit(X_train_directions, Y_train_flat) + + # Evaluate using confusion matrix. + # Clearly the middel of the snake is the hardest part. + X_test, Y_test = snakes['X_test'], snakes['Y_test'] + X_test = [one_hot_colors(x) for x in X_test] + Y_test_flat = [y_.ravel() for y_ in Y_test] + X_test_directions, X_test_edge_features = prepare_data(X_test) + Y_pred = ssvm.predict(X_test_directions) + print("Results using only directional features for edges") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) + + # now, use more informative edge features: + crf = EdgeFeatureGraphCRF(inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', + n_jobs=-1) + ssvm.fit(X_train_edge_features, Y_train_flat) + Y_pred2 = ssvm.predict(X_test_edge_features) + print("Results using also input features for edges") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + + # plot stuff + fig, axes = plt.subplots(2, 2) + axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') + axes[0, 0].set_title('Input') + y = Y_test[0].astype(np.int) + bg = 2 * (y != 0) # enhance contrast + axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) + axes[0, 1].set_title("Ground Truth") + axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 0].set_title("Prediction w/o edge features") + axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) + axes[1, 1].set_title("Prediction with edge features") + for a in axes.ravel(): + a.set_xticks(()) + a.set_yticks(()) + plt.show() From d03dc45325391c65b3cc779f6f3deada913a271e Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 26 Jul 2018 11:10:09 +0200 Subject: [PATCH 147/155] new CRF model (NodeTypeEdgeFeatureGraphCRF) and predicting under some logical constraint --- examples/plot_hidden_short_snakes_typed.py | 604 ++++++++++++ .../plot_hidden_short_snakes_typed_gen.py | 414 +++++++++ examples/plot_hidden_snakes.py | 321 +++++++ examples/plot_snakes_constraints.py | 269 ++++++ examples/plot_snakes_typed.py | 161 ++++ .../node_type_edge_feature_graph_crf.py | 440 +++++++++ pystruct/models/typed_crf.py | 342 +++++++ .../test_node_type_edge_feature_graph_crf.py | 872 ++++++++++++++++++ 8 files changed, 3423 insertions(+) create mode 100644 examples/plot_hidden_short_snakes_typed.py create mode 100644 examples/plot_hidden_short_snakes_typed_gen.py create mode 100644 examples/plot_hidden_snakes.py create mode 100644 examples/plot_snakes_constraints.py create mode 100644 examples/plot_snakes_typed.py create mode 100644 pystruct/models/node_type_edge_feature_graph_crf.py create mode 100644 pystruct/models/typed_crf.py create mode 100644 pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py diff --git a/examples/plot_hidden_short_snakes_typed.py b/examples/plot_hidden_short_snakes_typed.py new file mode 100644 index 00000000..b78a936a --- /dev/null +++ b/examples/plot_hidden_short_snakes_typed.py @@ -0,0 +1,604 @@ +""" +============================================== +Conditional Interactions on the Snakes Dataset +============================================== + +This is a variant of plot_snakes.py + +Snake are hidding, so we have 2 categorisers: +- determining if a snake is in the picture, +- identifying its head to tail body (at pixel-level) + +We use the NodeTypeEdgeFeatureGraphCRF class with 2 type of nodes. + + +This example uses the snake dataset introduced in +Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 + +This dataset is specifically designed to require the pairwise interaction terms +to be conditioned on the input, in other words to use non-trival edge-features. + +The task is as following: a "snake" of length ten wandered over a grid. For +each cell, it had the option to go up, down, left or right (unless it came from +there). The input consists of these decisions, while the desired output is an +annotation of the snake from 0 (head) to 9 (tail). See the plots for an +example. + +As input features we use a 3x3 window around each pixel (and pad with background +where necessary). We code the five different input colors (for up, down, left, right, +background) using a one-hot encoding. This is a rather naive approach, not using any +information about the dataset (other than that it is a 2d grid). + +The task can not be solved using the simple DirectionalGridCRF - which can only +infer head and tail (which are also possible to infer just from the unary +features). If we add edge-features that contain the features of the nodes that are +connected by the edge, the CRF can solve the task. + +From an inference point of view, this task is very hard. QPBO move-making is +not able to solve it alone, so we use the relaxed AD3 inference for learning. + +PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). +But it does work as well as Decision Tree Fields ;) + + + + JL Meunier - January 2017 + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943 + + Copyright Xerox + +""" +from __future__ import (absolute_import, division, print_function) + +import sys, os, time +import random +try: + import cPickle as pickle +except: + import pickle + +import numpy as np +import matplotlib.pyplot as plt + +from sklearn.metrics import confusion_matrix, accuracy_score +from sklearn.linear_model import LogisticRegression +#from sklearn.grid_search import GridSearchCV +from sklearn.model_selection import GridSearchCV + +from pystruct.learners import OneSlackSSVM +from pystruct.datasets import load_snakes +from pystruct.models import NodeTypeEdgeFeatureGraphCRF + +from plot_snakes import one_hot_colors, neighborhood_feature, prepare_data + +from plot_hidden_snakes import augmentWithNoSnakeImages, shuffle_in_unison, shorten_snakes + + + +#============================================================================================== + +bFIXED_RANDOM_SEED = True + +NCELL=10 + +nbSWAP_Pixel_Pict_TYPES = 0 #0,1,2 are useful (this was for DEBUG) + +bMAKE_PICT_EASY = False #DEBUG: we had a feature on the picture that tells directly if a snake is present or not + +#INFERENCE="ad3+" #ad3+ is required when there are hard logic constraints +INFERENCE="ad3" #ad3 is faster than ad3+ +N_JOBS=8 + +MAXITER=750 + +sMODELFILE = None +#sMODELFILE = "model.pkl" #we save the model in a file and do not re-trian if the file exists + +#============================================================================================== + +def printConfig(): + print("== NCELL=", NCELL) + print("== FIXED_SEED=", bFIXED_RANDOM_SEED) + print("== INFERENCE =", INFERENCE) + print("== N_JOBS =", N_JOBS) + print("== SWAP=", nbSWAP_Pixel_Pict_TYPES) + print("== EASY=", bMAKE_PICT_EASY) + print("== MAX_ITER=", MAXITER) + print("== MODEL FILE=", sMODELFILE) + +if __name__ == '__main__': + printConfig() + + +def plot_snake(picture): + plt.imshow(picture, interpolation='nearest') + plt.show() + +def prepare_picture_data(X): + """ + compute picture features (on 1-hot encoded pictures) + """ + lPictFeat = list() + for a_hot_picture in X: + #count number of cells of each color + #feat = np.zeros((1,5), dtype=np.int8) + feat = np.zeros((1,7), dtype=np.int64) + + #Histogram of pixels from 0 to 4 + """ + Test accuracy: 0.500 + [[45 55] + [45 55]] + """ + for i in range(5): + ai, aj = np.where(a_hot_picture[...,i] == 1) + feat[0,i] = len(ai) + + #adding height and width of the snake + """ + Test accuracy: 0.420 Test accuracy: 0.515 Test accuracy: 0.495 + [[39 61] [[48 52] [[52 48] + [55 45]] [45 55]] [53 47]] + """ + ai, aj = np.where(a_hot_picture[...,3] != 1) + feat[0,5] = max(ai)-min(ai) #height + feat[0,6] = max(aj)-min(aj) #width + + lPictFeat.append(feat) + + return lPictFeat + +def convertToTwoType(X_train, #list of hot pictures + X_train_directions, # list of node_feat (2D array) , edges (_ x 2 array), edge_feat (2D array) for pixel nodes + Y_train, # list of 2D arrays + X_train_pict_feat, #a list of picture_node_features + Y_train_pict, #a list of integers [0,1] + nCell=10): + """ + return X,Y for NodeTypeEdgeFeatureGraphCRF + + + X and Y + ------- + Node features are given as a list of n_types arrays of shape (n_type_nodes, n_type_features): + - n_type_nodes is the number of nodes of that type + - n_type_features is the number of features for this type of node + + Edges are given as a list of n_types x n_types arrays of shape (n_type_edges, 2). + Columns are resp.: node index (in corresponding node type), node index (in corresponding node type) + + Edge features are given as a list of n_types x n_types arrays of shape (n_type_type_edge, n_type_type_edge_features) + - n_type_type_edge is the number of edges of type type_type + - n_type_type_edge_features is the number of features for edge of type type_type + + An instance ``X`` is represented as a tuple ``([node_features, ..], [edges, ..], [edge_features, ..])`` + + Labels ``Y`` are given as one array of shape (n_nodes) The meaning of a label depends upon the node type. + + """ + + lX, lY = list(), list() + + for (X, + (aPixelFeat, aPixelPixelEdges, aPixelPixelEdgeFeat), + aPixelLbl, + aPictFeat, + iPictLbl) in zip(X_train, X_train_directions, Y_train, X_train_pict_feat, Y_train_pict ): + + + aPixelPictEdges = np.zeros( (aPixelFeat.shape[0], 2), np.int64) + aPixelPictEdges[:,0] = np.arange(aPixelFeat.shape[0]) + features = neighborhood_feature(X) + aPixelPictEdgeFeat = features + + lNodeFeat = [aPixelFeat, aPictFeat] + lEdge = [aPixelPixelEdges, + aPixelPictEdges, #pixel to picture + None, #picture to pixel + None] #picture to picture + lEdgeFeat = [aPixelPixelEdgeFeat, + aPixelPictEdgeFeat, + None, + None] + + #Y is flat for each graph + y = np.zeros((aPixelLbl.size+1, ), dtype=np.int64) + y[:-1] = aPixelLbl.ravel() + y[-1] = int(iPictLbl)+nCell+1 + + x = (lNodeFeat, lEdge, lEdgeFeat) + + lX.append(x) + lY.append(y) + + return lX,lY + +def swap_node_types(l_perm, l_n_state, lX, lY, constraints=None): + """ + lX and lY have been produced for a CRF configured with l_n_state + + We permute this as indicated by the permutation (typically for the snake: l_perm=[1, 0] ) + + """ + _lX, _lY = [], [] + _constraints = None + + n_types = len(l_n_state) + a_perm = np.asarray(l_perm) #e.g. 3 for l_n_state = [2, 3, 4] + a_cumsum_n_state = np.asarray([sum(l_n_state[:i]) for i in range(len(l_n_state))]) # [0, 2, 5] + a_delta_y_by_y = np.asarray([item for i,n in enumerate(l_n_state) for item in n*(a_cumsum_n_state[i:i+1]).tolist()]) # [0, 0, 2, 2, 2, 5, 5, 5, 5] + a_typ_by_y = np.asarray([item for i,n in enumerate(l_n_state) for item in n*[i]]) # [0, 0, 1, 1, 1, 2, 2, 2, 2] + + _l_n_state = [l_n_state[i] for i in l_perm] + _a_cumsum_n_state = np.asarray([sum(_l_n_state[:i]) for i in range(len(_l_n_state))]) + + for (lNF, lE, lEF), Y in zip(lX, lY): + + _lNF = [lNF[i] for i in l_perm] + + _Y = np.zeros(Y.shape, dtype=Y.dtype) + #we need to re-arrange the Ys accordingly + l_n_nodes = [nf.shape[0] for nf in lNF] + _l_n_nodes = [nf.shape[0] for nf in _lNF] + cumsum_n_nodes = [0] + [sum( l_n_nodes[:i+1]) for i in range(len( l_n_nodes))] + _cumsum_n_nodes = [0] + [sum(_l_n_nodes[:i+1]) for i in range(len(_l_n_nodes))] + for i in range(len(lNF)): + j = l_perm[i] + _Y[_cumsum_n_nodes[j]:_cumsum_n_nodes[j+1]] = Y[cumsum_n_nodes[i]:cumsum_n_nodes[i+1]] + + _Y = _Y - a_delta_y_by_y[_Y] + _a_cumsum_n_state[a_perm[a_typ_by_y[_Y]]] + + _lE = [lE[i*n_types+j] for i in l_perm for j in l_perm] + _lEF = [lEF[i*n_types+j] for i in l_perm for j in l_perm] + + _lX.append( (_lNF, _lE, _lEF) ) + _lY.append(_Y) + + if constraints: + print("WARNING: some constraints are not properly swapped because the " + "node order has a meaning.") + _constraints = list() + for _lConstraints in constraints: + for (op, l_l_unary, l_l_state, l_lnegated) in _lConstraints: + #keep the op but permute by types + _l_l_unary = [l_l_unary [i] for i in l_perm] + _l_l_state = [l_l_state [i] for i in l_perm] + _l_lnegated = [l_lnegated[i] for i in l_perm] + _lConstraints.append( (op, _l_l_unary, _l_l_state, _l_lnegated)) + _constraints.append(_lConstraints) + + return _lX, _lY, _constraints + +def listConstraints(lX, ncell=NCELL): + """ + produce the list of constraints for this list of multi-type graphs + """ + lConstraints = list() + for _lNF, _lE, _lEF in lX: + nf_pixel, nf_pict = _lNF + nb_pixels = len(nf_pixel) + l_l_unary = [ range(nb_pixels), [0]] + l_l_states = [ 0, 0 ] #we pass a scalar for each type instead of a list since the values are the same across each type + l_l_negated = [ False, False ] #same + + lConstraint_for_X = [("ANDOUT", l_l_unary, l_l_states, l_l_negated)] #we have a list of constraints per X + + for _state in range(1, ncell+1): + lConstraint_for_X.append( ("XOROUT" , l_l_unary + , [ _state, 1 ] #exactly one cell in state _state with picture label being snake + , l_l_negated) + ) #we have a list of constraints per X + + lConstraints.append( lConstraint_for_X ) + return lConstraints + +def listConstraints_ATMOSTONE(lX, ncell=NCELL): + """ + produce the list of constraints for this list of multi-type graphs + """ + lConstraints = list() + for _lNF, _lE, _lEF in lX: + nf_pixel, nf_pict = _lNF + nb_pixels = len(nf_pixel) + + lConstraint_for_X = list() + + for _state in range(1, ncell+1): + lConstraint_for_X.append( ("ATMOSTONE" , [ range(nb_pixels), []] + , [ _state, None ] #atmost one cell in state _state whatever picture label + , [ False, None ]) + ) #we have a list of constraints per X + + lConstraints.append( lConstraint_for_X ) + return lConstraints + + +def makeItEasy(lX_pict_feat, lY_pict): + """ + add the picture label in a feature... + """ + for X,y in zip(lX_pict_feat, lY_pict): + X[0] = y + + +def appendIntVectorToCsv(fd, name, aV): + saV = np.array_str(aV, max_line_width=99999, precision=0) + saV = saV.strip()[1:-1] #removal of brackets + saV = ','.join(saV.split()) + fd.write("%s,%s\n"%(name, saV)) + fd.flush() + +def REPORT(l_Y_GT, lY_Pred, t=None, ncell=NCELL, filename=None, bHisto=False, name=""): + if t: + print("\t( predict DONE IN %.1fs)"%t) + + _flat_GT, _flat_P = (np.hstack([y.ravel() for y in l_Y_GT]), + np.hstack([y.ravel() for y in lY_Pred])) + confmat = confusion_matrix(_flat_GT, _flat_P) + print(confmat) + print("\ttrace =", confmat.trace()) + score = accuracy_score(_flat_GT, _flat_P) + print("\tAccuracy= %.3f"%score) + + #CSV out? + if filename: + histo = np.histogram(np.hstack(_flat_GT), bins=range(ncell+2)) + diag = np.diag(confmat) + with open(filename, "ab") as fdCSV: + if bHisto: appendIntVectorToCsv(fdCSV, name+"_histo,", histo[0]) + appendIntVectorToCsv(fdCSV, name+",%.3f"%score, diag) + +if __name__ == '__main__': + + if bFIXED_RANDOM_SEED: + np.random.seed(1605) + random.seed(98) + else: + np.random.seed() + random.seed() + + print("Please be patient...") + snakes = load_snakes() + + #-------------------------------------------------------------------------------------------------- + X_train, Y_train = snakes['X_train'], snakes['Y_train'] + #X_train, Y_train = X_train[:3], Y_train[:3] + print("TRAIN SET ", len(X_train), len(Y_train)) + + if NCELL <10: X_train, Y_train = shorten_snakes(X_train, Y_train, NCELL) + + nb_hidden, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False, nCell=NCELL) + print("TRAIN SET ",len(X_train), len(Y_train)) + Y_train_pict = np.array([1]*(len(X_train)-nb_hidden) + [0]*nb_hidden) + + X_train = [one_hot_colors(x) for x in X_train] + + X_train, Y_train, Y_train_pict = shuffle_in_unison(X_train, Y_train, Y_train_pict) + + + X_train_pict_feat = prepare_picture_data(X_train) + if bMAKE_PICT_EASY: + print("Making the train picture task easy") + makeItEasy(X_train_pict_feat, Y_train_pict) + + X_train_directions, X_train_edge_features = prepare_data(X_train) + #-------------------------------------------------------------------------------------------------- + X_test, Y_test = snakes['X_test'], snakes['Y_test'] + + if NCELL <10: X_test, Y_test = shorten_snakes(X_test, Y_test, NCELL) + + nb_hidden, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", False, nCell=NCELL) + Y_test_pict = np.array([1]*(len(X_test)-nb_hidden) + [0]*nb_hidden) + print("TEST SET ", len(X_test), len(Y_test)) + + X_test = [one_hot_colors(x) for x in X_test] + + #useless X_test, Y_test, Y_test_pict = shuffle_in_unison(X_test, Y_test, Y_test_pict) + + X_test_pict_feat = prepare_picture_data(X_test) + if bMAKE_PICT_EASY: + print("Making the test picture task easy") + makeItEasy(X_test_pict_feat, Y_test_pict) + + X_test_directions, X_test_edge_features = prepare_data(X_test) + + #-------------------------------------------------------------------------------------------------- + print("===================================================================" + "===================================") + if True: + from pystruct.models.edge_feature_graph_crf import EdgeFeatureGraphCRF + print("ONE TYPE TRAINING AND TESTING: PIXELS") + +# inference = 'ad3+' +# inference = 'qpbo' + inference=INFERENCE + inference = "qpbo" + crf = EdgeFeatureGraphCRF(inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=0, + max_iter=MAXITER, + n_jobs=N_JOBS + #,verbose=1 + , switch_to='ad3' + ) + + Y_train_flat = [y_.ravel() for y_ in Y_train] + print( "\ttrain label histogram : ", + np.histogram(np.hstack(Y_train_flat), bins=range(NCELL+2))) + + t0 = time.time() + ssvm.fit(X_train_edge_features, Y_train_flat) + print("FIT DONE IN %.1fs"%(time.time() - t0)) + sys.stdout.flush() + + t0 = time.time() + _Y_pred = ssvm.predict( X_test_edge_features ) + REPORT(Y_test, _Y_pred, time.time() - t0) + + #-------------------------------------------------------------------------------------------------- + if True: + print("_"*50) + print("ONE TYPE TRAINING AND TESTING: PICTURES") + + print( "\ttrain label histogram : ", + np.histogram(Y_train_pict, bins=range(3))) + + lr = LogisticRegression(class_weight='balanced') + + mdl = GridSearchCV(lr , {'C':[0.1, 0.5, 1.0, 2.0] }) + + XX = np.vstack(X_train_pict_feat) + + t0 = time.time() + mdl.fit(XX, Y_train_pict) + print("FIT DONE IN %.1fs"%(time.time() - t0)) + + t0 = time.time() + _Y_pred = mdl.predict( np.vstack(X_test_pict_feat) ) + REPORT([Y_test_pict], _Y_pred, time.time() - t0) + + #-------------------------------------------------------------------------------------------------- + print("===================================================================" + "===================================") + + + # first, train on X with directions only: + #crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[2]], inference_method=inference) + # first, train on X with directions only: +# l_weights = [ +# [10.0/200] + [10.0/200]*10, +# [10.0/20 , 10.0/20] +# ] +# print("WEIGHTS:", l_weights + if nbSWAP_Pixel_Pict_TYPES %2 == 0: + l_n_states = [NCELL+1, 2] # 11 states for pixel nodes, 2 states for pictures + l_n_feat = [45, 7] # 45 features for pixels, 7 for pictures + ll_n_feat = [[180, 45], # 2 feature between pixel nodes, 1 between pixel and picture + [45 , 0]] # , nothing between picture nodes (no picture_to_picture edge anyway) + else: + l_n_states = [2, NCELL+1] + l_n_feat = [7, 45] + ll_n_feat = [[0, 45], [45 , 180]] + + if not sMODELFILE or not os.path.exists(sMODELFILE): + print(" TRAINING MULTI-TYPE MODEL ") + #TRAINING + crf = NodeTypeEdgeFeatureGraphCRF(2, # How many node types? + l_n_states, # How many states per type? + l_n_feat, # How many node features per type? + ll_n_feat, # How many edge features per type x type? + inference_method=INFERENCE + # , l_class_weight = l_weights + ) + print(crf) + + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=0, + max_iter=MAXITER, + n_jobs=N_JOBS + #,verbose=1 + #, switch_to='ad3' + ) + + print("===============================================================" + "=======================================") + print("YY[0].shape", Y_train[0].shape) + XX, YY = convertToTwoType(X_train, + X_train_edge_features, # list of node_feat , edges, edge_feat for pixel nodes + Y_train, + X_train_pict_feat, #a list of picture_node_features + Y_train_pict, #a list of integers [0,1] + nCell=NCELL) + + if nbSWAP_Pixel_Pict_TYPES: + if nbSWAP_Pixel_Pict_TYPES % 2 == 0: + XX, YY = swap_node_types([1,0], [NCELL+1, 2], XX, YY) + XX, YY = swap_node_types([1,0], [2 , NCELL+1], XX, YY) + else: + XX, YY = swap_node_types([1,0], [NCELL+1, 2], XX, YY) + + + print( "\tlabel histogram : ", + np.histogram(np.hstack([y.ravel() for y in YY]), + bins=range(14))) + + + print("YY[0].shape", YY[0].shape) + crf.initialize(XX, YY)# check if the data is properly built + sys.stdout.flush() + + t0 = time.time() + ssvm.fit(XX, YY) + print("FIT DONE IN %.1fs"%(time.time() - t0)) + sys.stdout.flush() + + ssvm.alphas = None + ssvm.constraints_ = None + ssvm.inference_cache_ = None + if sMODELFILE: + print("Saving model in: ", sMODELFILE) + with open(sMODELFILE, "wb") as fd: + cPickle.dump(ssvm, fd) + else: + #REUSE PREVIOUSLY TRAINED MODEL + print(" RUSING PREVIOULSLY TRAINED MULTI-TYPE MODEL: ", sMODELFILE) + + with open(sMODELFILE, "rb") as fd: + ssvm = pickle.load(fd) + + + print("INFERENCE WITH ", INFERENCE) + XX_test, YY_test =convertToTwoType(X_test, + X_test_edge_features, # list of node_feat , edges, edge_feat for pixel nodes + Y_test, + X_test_pict_feat, #a list of picture_node_features + Y_test_pict, #a list of integers [0,1] + nCell=NCELL) + print( "\tlabel histogram (PIXELs and PICTUREs): ", + np.histogram(np.hstack([y.ravel() for y in YY_test]), + bins=range(14))) + + +# l_constraints = listConstraints(XX_test) + l_constraints = listConstraints_ATMOSTONE(XX_test) + + if nbSWAP_Pixel_Pict_TYPES %2 == 1: + XX_test, YY_test, l_constraints = swap_node_types([1,0], [NCELL+1, 2], XX_test, YY_test, l_constraints) + + print("\t- results without constraints (using %s)"%INFERENCE) + t0 = time.time() + YY_pred = ssvm.predict( XX_test ) + REPORT(YY_test, YY_pred, time.time() - t0) + + print("_"*50) + print("\t- results exploiting constraints (using ad3+)") + ssvm.model.inference_method = "ad3+" + t0 = time.time() + YY_pred = ssvm.predict( XX_test, l_constraints ) + REPORT(YY_test, YY_pred, time.time() - t0) + + + print("_"*50) + + if INFERENCE == "ad3": + ssvm.model.inference_method = "ad3+" + else: + ssvm.model.inference_method = "ad3" + print("\t- results without constraints (using %s)"%ssvm.model.inference_method) + + t0 = time.time() + YY_pred = ssvm.predict( XX_test ) + REPORT(YY_test, YY_pred, time.time() - t0) + + print("DONE") + + printConfig() + + +""" + + + + +""" \ No newline at end of file diff --git a/examples/plot_hidden_short_snakes_typed_gen.py b/examples/plot_hidden_short_snakes_typed_gen.py new file mode 100644 index 00000000..dce94d1d --- /dev/null +++ b/examples/plot_hidden_short_snakes_typed_gen.py @@ -0,0 +1,414 @@ +""" +============================================== +Conditional Interactions on the Snakes Dataset +============================================== + +This is a variant of plot_snakes.py + +Snake are hidding, so we have 2 tasks: +- determining if a snake is in the picture, +- identifying its head to tail body. + +We use the NodeTypeEdgeFeatureGraphCRF class with 2 type of nodes. + +HERE WE GENERATE THE SNAKES AT RANDOM INSTEAD OF USING THE SNAKE DATASET + + +This example uses the snake dataset introduced in +Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 + +This dataset is specifically designed to require the pairwise interaction terms +to be conditioned on the input, in other words to use non-trival edge-features. + +The task is as following: a "snake" of length ten wandered over a grid. For +each cell, it had the option to go up, down, left or right (unless it came from +there). The input consists of these decisions, while the desired output is an +annotation of the snake from 0 (head) to 9 (tail). See the plots for an +example. + +As input features we use a 3x3 window around each pixel (and pad with background +where necessary). We code the five different input colors (for up, down, left, right, +background) using a one-hot encoding. This is a rather naive approach, not using any +information about the dataset (other than that it is a 2d grid). + +The task can not be solved using the simple DirectionalGridCRF - which can only +infer head and tail (which are also possible to infer just from the unary +features). If we add edge-features that contain the features of the nodes that are +connected by the edge, the CRF can solve the task. + +From an inference point of view, this task is very hard. QPBO move-making is +not able to solve it alone, so we use the relaxed AD3 inference for learning. + +PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). +But it does work as well as Decision Tree Fields ;) + + + + JL Meunier - January 2017 + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943 + + Copyright Xerox + +""" + +import sys, os, time +import random, cPickle + +import numpy as np + +from sklearn.metrics import confusion_matrix, accuracy_score +from sklearn.linear_model import LogisticRegression +from sklearn.grid_search import GridSearchCV + +from pystruct.learners import OneSlackSSVM +from pystruct.datasets import load_snakes +from pystruct.models import NodeTypeEdgeFeatureGraphCRF + +from plot_snakes import one_hot_colors + +from plot_hidden_snakes import augmentWithNoSnakeImages, shuffle_in_unison, shorten_snakes + +from plot_hidden_short_snakes_typed import plot_snake, prepare_data, prepare_picture_data, convertToTwoType,listConstraints, listConstraints_ATMOSTONE, REPORT + +#============================================================================================== + +bFIXED_RANDOM_SEED = True + +NCELL=10 + +#INFERENCE="ad3+" #ad3+ is required when there are hard logic constraints +INFERENCE="ad3" #ad3 is faster than ad3+ +N_JOBS=8 +#MAXITER=750 +lNbSAMPLE=[200, 400, 600, 800] #how many sample do we generate for each experiment? +nbEXPERIMENT = 10 + +# N_JOBS=1 +# lNbSAMPLE=[20] +# nbEXPERIMENT=1 +# MAXITER=3 +#============================================================================================== + +def printConfig(): + print "== NCELL=", NCELL + print "== FIXED_SEED=", bFIXED_RANDOM_SEED + print "== INFERENCE =", INFERENCE + print "== N_JOBS =", N_JOBS + #print "== MAX_ITER=", MAXITER + print "== lNbSAMPLE=", lNbSAMPLE + print "== nbEXPERIMENT=", nbEXPERIMENT + +if __name__ == '__main__': printConfig() + + +class GenSnakeException(Exception): pass + +def genSnakes(N, dUniqueSnakelij, ncell=NCELL): + """ + Generate snakes at random. + dUniqueSnakelij contains the signature of all Snakes. We ensure unicity of each Snake. + Return N tuple (snakes, Y) + """ + ltSnakeY = [] + + ndim = 1+ ncell+1+ncell +1 #where we'll draw each snake. Border, possible straight snake, centre, possible straight snake, border + aBoard = np.zeros( (ndim, ndim) , dtype=np.int8) + im,jm = 1+ ncell, 1+ ncell #middle of board + lDirection = range(4) #assume it is N, E, S, W + lDirectionIncr = [(-1,0), (0,1), (1,0), (0,-1)] + lDirectionColor = [ [255,0,0], [255,255,0], [0,255,0], [0,255,255] ] + for _n in range(N): + while True: + aBoard[:,:] = -1 #all background + i,j = im,jm + lij = list() + ldir=list() + aSnake, Y = None, None + + try: + for _ncell in range(ncell): + random.shuffle(lDirection) #we will try each direction in turn + for dir in lDirection: + _i, _j = i+lDirectionIncr[dir][0], j+lDirectionIncr[dir][1] + if aBoard[_i,_j] == -1: break #ok, valid direction, we jump on a background pixel + if aBoard[_i,_j] != -1: raise GenSnakeException("Failed to generate a snake") #got stuck + aBoard[i,j] = dir + lij.append( (i,j) ) + ldir.append(dir) + i,j = _i,_j + try: + dUniqueSnakelij[tuple(lij)] + raise GenSnakeException("Same as in trainset") + except KeyError: + dUniqueSnakelij[tuple(lij)] = True + #ok we have a Snake, let's create the image with background borders + imin,jmin = map(min, zip(*lij)) + imax,jmax = map(max, zip(*lij)) + aSnake = np.zeros((imax-imin+3, jmax-jmin+3, 3), dtype=np.uint8) + aSnake[:,:,2] = 255 #0,0,255 + aY = np.zeros((imax-imin+3, jmax-jmin+3) , dtype=np.uint8) + for _lbl, ((_i,_j), _dir) in enumerate(zip(lij, ldir)): + aSnake[_i-imin+1, _j-jmin+1,:] = lDirectionColor[_dir] + aY [_i-imin+1, _j-jmin+1] = _lbl + 1 + + break + except GenSnakeException: pass + ltSnakeY.append( (aSnake, aY) ) +# print aSnake +# print aY +# plot_snake(aSnake) + return ltSnakeY + +def plot_many_snakes(lX, nv=10, nh=20, ncell=NCELL): + """ + Plot the one-hot-encoded snake on grids of size nv x nh + """ + N = ncell+1 #to have border + i = 0 + while i < len(lX): + j = min(i+nv*nh, len(lX)) + lImg = lX[i:j] + allimg = np.zeros(shape=(N*nv,N*nh,3), dtype=np.uint8) + ih,iw = 0,0 + for i_img, img in enumerate(lImg): + h,w,c = img.shape + assert c == 3 + allimg[ih:ih+h, iw:iw+w, :] = img + iw += N + if i_img % nh == (nh-1): + ih += N + iw = 0 + plot_snake(allimg) + i = j + +def plot_mistakes(lY_ref, lY_pred, lX_pict, ncell=NCELL): + """ + Plot snake wrongly predicted, first NoSnake pictures, then Snake pictures + """ + _ltSnake = (list(), list()) #misclassified NoSnake pictures, misclassified Snake pictures + for _y_ref, _y_pred, _x in zip(lY_ref, lY_pred, lX_pict): + assert _y_ref.shape==_y_pred.shape + assert _y_ref.size ==_x.size/3+1 + assert _y_ref[-1] in [ncell+1,ncell+2] + if _y_ref[-1] != _y_pred[-1]: + iSnake = _y_ref[-1] - ncell - 1 #0=NoSnake 1=Snake + _ltSnake[iSnake].append(_x) + + print "NoSnake pictures predicted as Snake" + plot_many_snakes(_ltSnake[0]) + print "Snake pictures predicted as NoSnake" + plot_many_snakes(_ltSnake[1]) + + + +if __name__ == '__main__': + + if bFIXED_RANDOM_SEED: + np.random.seed(1605) + random.seed(98) + else: + np.random.seed() + random.seed() + + print("Please be patient...") + snakes = load_snakes() + + #-------------------------------------------------------------------------------------------------- + #we always test against the original test set + X_test, Y_test = snakes['X_test'], snakes['Y_test'] + #plot_many_snakes(X_test) +# X_test_img = X_test + if NCELL <10: X_test, Y_test = shorten_snakes(X_test, Y_test, NCELL) + + nb_hidden, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", False, nCell=NCELL) + Y_test_pict = np.array([1]*(len(X_test)-nb_hidden) + [0]*nb_hidden) + print "TEST SET ", len(X_test), len(Y_test) + X_test_pict = X_test + X_test = [one_hot_colors(x) for x in X_test] + X_test_pict_feat = prepare_picture_data(X_test) + X_test_directions, X_test_edge_features = prepare_data(X_test) + + #-------------------------------------------------------------------------------------------------- + for iExp in range(nbEXPERIMENT): + print "#"*75 + print "# EXPERIMENT %d / %d"%(iExp+1, nbEXPERIMENT) + print "#"*75 + + dUniqueSnakelij = dict() + + lXY = genSnakes(max(lNbSAMPLE), dUniqueSnakelij) + X_train_all, Y_train_all = zip(*lXY) + X_train_all, Y_train_all = list(X_train_all), list(Y_train_all) + print "***** GENERATED %d snakes of length %d *****"%(len(X_train_all), NCELL) + + #Also generate an additional test set + NTEST=100 + lXYTest = genSnakes( NTEST, dUniqueSnakelij ) + X_test_gen, Y_test_gen = zip(*lXYTest) + X_test_gen, Y_test_gen = list(X_test_gen), list(Y_test_gen) + print "***** GENERATED %d snakes of length %d *****"%(NTEST, NCELL) +# plot_many_snakes(X_test_img+X_test_gen) + nb_hidden, X_test_gen, Y_test_gen = augmentWithNoSnakeImages(X_test_gen, Y_test_gen, "test_gen", False, nCell=NCELL) + Y_test_gen_pict = np.array([1]*(len(X_test_gen)-nb_hidden) + [0]*nb_hidden) + print "GENERATED TEST SET ", len(X_test_gen), len(Y_test_gen) + + X_test_gen = [one_hot_colors(x) for x in X_test_gen] + X_test_gen_pict_feat = prepare_picture_data(X_test_gen) + X_test_gen_directions, X_test_gen_edge_features = prepare_data(X_test_gen) + + for nbSample in lNbSAMPLE: + print "======================================================================================================" + print "TRAINING" + X_train, Y_train = X_train_all[0:nbSample], Y_train_all[0:nbSample] + + nb_hidden, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", False, nCell=NCELL) + print "TRAIN SET ",len(X_train), len(Y_train) + Y_train_pict = np.array([1]*(len(X_train)-nb_hidden) + [0]*nb_hidden) + + X_train = [one_hot_colors(x) for x in X_train] + X_train, Y_train, Y_train_pict = shuffle_in_unison(X_train, Y_train, Y_train_pict) + X_train_pict_feat = prepare_picture_data(X_train) + X_train_directions, X_train_edge_features = prepare_data(X_train) + + #-------------------------------------------------------------------------------------------------- + if True: + print "===========================================================================" + from pystruct.models.edge_feature_graph_crf import EdgeFeatureGraphCRF + print "ONE TYPE TRAINING AND TESTING: PIXELS" + + inference = "qpbo" + crf = EdgeFeatureGraphCRF(inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, +# max_iter=MAXITER, + n_jobs=N_JOBS + #,verbose=1 + , switch_to='ad3' + ) + + Y_train_flat = [y_.ravel() for y_ in Y_train] + print "\ttrain label histogram : ", np.histogram(np.hstack(Y_train_flat), bins=range(NCELL+2)) + + t0 = time.time() + ssvm.fit(X_train_edge_features, Y_train_flat) + print "FIT DONE IN %.1fs"%(time.time() - t0) + sys.stdout.flush() + + t0 = time.time() + _Y_pred = ssvm.predict( X_test_edge_features ) + REPORT(Y_test, _Y_pred, time.time() - t0, NCELL, "gen_singletype_%d.csv"%nbSample, True, "singletype_%d"%nbSample) + _Y_pred = ssvm.predict( X_test_gen_edge_features ) + REPORT(Y_test_gen, _Y_pred, None , NCELL, "gen_singletype_gentest_%d.csv"%nbSample, True, "singletype_%d_gentest"%nbSample) + + #-------------------------------------------------------------------------------------------------- + if True: + print "_"*50 + print "ONE TYPE TRAINING AND TESTING: PICTURES" + + print "\ttrain label histogram : ", np.histogram(Y_train_pict, bins=range(3)) + + lr = LogisticRegression(class_weight='balanced') + + mdl = GridSearchCV(lr , {'C':[0.1, 0.5, 1.0, 2.0] }) + + XX = np.vstack(X_train_pict_feat) + + t0 = time.time() + mdl.fit(XX, Y_train_pict) + print "FIT DONE IN %.1fs"%(time.time() - t0) + + t0 = time.time() + _Y_pred = mdl.predict( np.vstack(X_test_pict_feat) ) + REPORT([Y_test_pict], _Y_pred, time.time() - t0, 2, "gen_picture.csv", True, "picture_logit_%d"%nbSample) + + #-------------------------------------------------------------------------------------------------- + print "======================================================================================================" + + l_n_states = [NCELL+1, 2] # 11 states for pixel nodes, 2 states for pictures + l_n_feat = [45, 7] # 45 features for pixels, 7 for pictures + ll_n_feat = [[180, 45], # 2 feature between pixel nodes, 1 between pixel and picture + [45 , 0]] # , nothing between picture nodes (no picture_to_picture edge anyway) + + print " TRAINING MULTI-TYPE MODEL " + #TRAINING + crf = NodeTypeEdgeFeatureGraphCRF(2, # How many node types? + l_n_states, # How many states per type? + l_n_feat, # How many node features per type? + ll_n_feat, # How many edge features per type x type? + inference_method=INFERENCE + ) + print crf + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=0.1, +# max_iter=MAXITER, + n_jobs=N_JOBS + ) + + print "======================================================================================================" + print "YY[0].shape", Y_train[0].shape + XX, YY = convertToTwoType(X_train, + X_train_edge_features, # list of node_feat , edges, edge_feat for pixel nodes + Y_train, + X_train_pict_feat, #a list of picture_node_features + Y_train_pict, #a list of integers [0,1] + nCell=NCELL) + + print "\tlabel histogram : ", np.histogram( np.hstack([y.ravel() for y in YY]), bins=range(14)) + + + print "YY[0].shape", YY[0].shape + crf.initialize(XX, YY)# check if the data is properly built + sys.stdout.flush() + + t0 = time.time() + ssvm.fit(XX, YY) + print "FIT DONE IN %.1fs"%(time.time() - t0) + sys.stdout.flush() + + print "_"*50 + XX_test, YY_test =convertToTwoType(X_test, + X_test_edge_features, # list of node_feat , edges, edge_feat for pixel nodes + Y_test, + X_test_pict_feat, #a list of picture_node_features + Y_test_pict, #a list of integers [0,1] + nCell=NCELL) + print "\tlabel histogram (PIXELs and PICTUREs): ", np.histogram( np.hstack([y.ravel() for y in YY_test]), bins=range(14)) + XX_test_gen, YY_test_gen =convertToTwoType(X_test_gen, + X_test_gen_edge_features, # list of node_feat , edges, edge_feat for pixel nodes + Y_test_gen, + X_test_pict_feat, #a list of picture_node_features + Y_test_pict, #a list of integers [0,1] + nCell=NCELL) + + + l_constraints = listConstraints_ATMOSTONE(XX_test , NCELL) + l_constraints_gen = listConstraints_ATMOSTONE(XX_test_gen, NCELL) + + print "_"*50 + print "\t- results without constraints (using %s)"%INFERENCE + t0 = time.time() + YY_pred = ssvm.predict( XX_test ) + REPORT(YY_test, YY_pred, time.time() - t0 , NCELL+2, "gen_multitype_%d.csv"%nbSample, True, "multitype_%d"%nbSample) + #plot_mistakes(YY_test, YY_pred, X_test_pict) + YY_pred = ssvm.predict( XX_test_gen ) + REPORT(YY_test_gen, YY_pred, None , NCELL+2, "gen_multitype_gentest_%d.csv"%nbSample, True, "multitype_%d_gentest"%nbSample) + + print "_"*50 + print "\t- results exploiting constraints (using ad3+)" + ssvm.model.inference_method = "ad3+" + t0 = time.time() + YY_pred = ssvm.predict( XX_test , l_constraints ) + REPORT(YY_test, YY_pred, time.time() - t0 , NCELL+2, "gen_multitype_constraints_%d.csv"%nbSample, True, "multitype_constraints_%d"%nbSample) + YY_pred = ssvm.predict( XX_test_gen , l_constraints_gen ) + REPORT(YY_test_gen, YY_pred, None , NCELL+2, "gen_multitype_constraints_gentest_%d.csv"%nbSample, True, "multitype_constraints_%d_gentest"%nbSample) + + + print "_"*50 + + print "One Experiment DONE" + + print "ALL EXPERIMENTS DONE" + + printConfig() + \ No newline at end of file diff --git a/examples/plot_hidden_snakes.py b/examples/plot_hidden_snakes.py new file mode 100644 index 00000000..0e533038 --- /dev/null +++ b/examples/plot_hidden_snakes.py @@ -0,0 +1,321 @@ +""" +============================================== +Conditional Interactions on the Snakes Dataset +============================================== + +This is a variant of plot_snakes.py + +Snake are hiding!! Therefore, some picture have colored pixels despite they do not contain any snake. + + JL Meunier - January 2017 + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943 + + Copyright Xerox + +This example uses the snake dataset introduced in +Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 + +This dataset is specifically designed to require the pairwise interaction terms +to be conditioned on the input, in other words to use non-trival edge-features. + +The task is as following: a "snake" of length ten wandered over a grid. For +each cell, it had the option to go up, down, left or right (unless it came from +there). The input consists of these decisions, while the desired output is an +annotation of the snake from 0 (head) to 9 (tail). See the plots for an +example. + +As input features we use a 3x3 window around each pixel (and pad with background +where necessary). We code the five different input colors (for up, down, left, right, +background) using a one-hot encoding. This is a rather naive approach, not using any +information about the dataset (other than that it is a 2d grid). + +The task can not be solved using the simple DirectionalGridCRF - which can only +infer head and tail (which are also possible to infer just from the unary +features). If we add edge-features that contain the features of the nodes that are +connected by the edge, the CRF can solve the task. + +From an inference point of view, this task is very hard. QPBO move-making is +not able to solve it alone, so we use the relaxed AD3 inference for learning. + +PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). +But it does work as well as Decision Tree Fields ;) +""" +from __future__ import (absolute_import, division, print_function) + +import numpy as np +import matplotlib.pyplot as plt +import random +from sklearn.preprocessing import label_binarize +from sklearn.metrics import confusion_matrix, accuracy_score +import time + +from pystruct.learners import OneSlackSSVM +from pystruct.datasets import load_snakes +from pystruct.models import EdgeFeatureGraphCRF +from pystruct.models import NodeTypeEdgeFeatureGraphCRF + +from plot_snakes import one_hot_colors, prepare_data + + +def isSnakePresent(a_hot_picture, nCell=10): + """ + Algorithmic check, to make sure that after tempering with the snake we do not have a snake! :-) + Works on the 1-hot encoded picture + """ + ai, aj = np.where(a_hot_picture[...,3] != 1) + + #let's start from each cell until we can walk thru an entire snake + #yeah, brute force, but otherwise it is tricky to check!! + bSnake = False + for i0,j0 in zip(ai,aj): + + lij = walkThruSnake(a_hot_picture, (i0, j0), nCell) + if len(lij) == nCell-1: + bSnake = True + break + return bSnake + +def walkThruSnake(a_hot_picture, tIJ, nCell=10): + """ + Walk thru the snake from I,J + Return the list of visited cells (excluding start cell) + """ + (i,j) = tIJ + lij = list() + color_index = np.where(a_hot_picture[i,j,:]==1)[0][0] + while len(lij) < nCell -1: + dj = np.array( [ 0, 0, 1, None, -1])[color_index] + di = np.array( [-1, 1, 0, None, 0])[color_index] + i += di + j += dj + color_index = np.where(a_hot_picture[i,j,:]==1)[0][0] + if color_index == 3: break #background + if (i,j) in lij: break #crossing itself, or looping + lij.append((i,j)) + return lij + +def changeOneSnakeCell(a_picture, bOneHot=True, nCell=10): #in place!! + """ + Change the color of 1 snake cells into another snake cell color + """ + if bOneHot: + ai, aj = np.where(a_picture[...,3] != 1) + else: + _p = np.copy(a_picture) + _p = one_hot_colors(_p) + ai, aj = np.where(_p[...,3] != 1) + assert len(ai) == nCell, (len(ai), nCell) + + iChange = random.randint(0,nCell-1) + + for i in range(10): + iFromCell = random.randint(0,nCell-1) + if (a_picture[ai[iChange], aj[iChange],:] != a_picture[ai[iFromCell], aj[iFromCell],:]).any(): + a_picture[ai[iChange], aj[iChange],:] = a_picture[ai[iFromCell], aj[iFromCell],:] + #so that we do not care about which color is valid... + break + + return a_picture + +def distortSnake(a_picture, bOneHot=True, nCell=10): + """ + Shuffle either the snake's cells or the pcitures' pixels. + """ + bDOCUMENT = False #to show the change on screen + + if bDOCUMENT: + pict_mem = np.copy(a_picture) + + changeOneSnakeCell(a_picture, bOneHot, nCell=nCell) + + if bDOCUMENT: + if bOneHot: + zz = a_picture + else: + zz = one_hot_colors(a_picture) + if not isSnakePresent(zz, nCell): + plot_snake(pict_mem) + plot_snake(a_picture) + +def convertToSingleTypeX(X): + """ + For NodeTypeEdgeFeatureGraphCRF X is structured differently. + But NodeTypeEdgeFeatureGraphCRF can handle graphs with a single node type. One simply needs to convert X to the new structure using this method. + """ + return [([nf], [e], [ef]) for (nf,e,ef) in X] + + +def plot_snake(picture): + plt.imshow(picture, interpolation='nearest') + plt.show() + + +def augmentWithNoSnakeImages(X,Y, name, bOneHot=True, iMult=1, nCell=10): + """ + return the number of added picture (ADDED AT THE END OF INPUT LISTS) + """ + print("ADDING PICTURE WIHOUT SNAKES!!! %d elements in %s"%(len(X), name)) + + X_NoSnake = [] + Y_NoSnake = [] + for i in range(int(iMult)): + X_NoSnake.extend([np.copy(x) for x in X]) + Y_NoSnake.extend([np.copy(y) for y in Y]) #shorten_sakes does modify Y... + + if True: + #best method for our experiment + for x in X_NoSnake: distortSnake(x, bOneHot, nCell) + else: + shorten_snakes(X_NoSnake, Y_NoSnake, nCell-1) + + newX = list() + newY = list() + for x,y in zip(X_NoSnake, Y_NoSnake): + _x = x if bOneHot else one_hot_colors(x) + if isSnakePresent(_x): + print("\t- DISCARDING a shuffled snake which is still a snake!!!!") +# if True and not bOneHot: plot_snake(x) + else: + newX.append(x) + newY.append(np.zeros(y.shape, dtype=np.int32)) + assert len(newX)==len(newY) + return len(newX), X+newX, Y+newY + +def shuffle_in_unison(*args): + lTuple = list(zip(*args)) + random.shuffle(lTuple) + return zip(*lTuple) + +def shorten_snakes(lX,lY, N): + """ + It is faster to work on shorter snakes, but easier as well for the models + """ + newlX,newlY = list(), list() + for X, Y in zip(lX,lY): + assert X.shape[:2] == Y.shape, (X.shape, Y.shape) + ai, aj = np.where(Y>N) + X[ai,aj,:] = X[0,0,:] + Y[ai,aj] = 0 + #crop + ai, aj = np.where(Y!=0) + aimin,aimax = min(ai)-1, max(ai)+2 + ajmin,ajmax = min(aj)-1, max(aj)+2 + newlY.append( Y[aimin:aimax, ajmin:ajmax] ) + newlX.append( X[aimin:aimax, ajmin:ajmax,:]) + + return newlX, newlY + +#===================================================================================================== +if __name__ == '__main__': + np.random.seed(1605) + random.seed(98) + + print("Please be patient. Learning will take 5-20 minutes.") + + #if you want to shorten all the snakes + #NCELL = 3 + NCELL = 10 + print("NCELL=", NCELL) + + + snakes = load_snakes() + + # --- TRAIN + X_train, Y_train = snakes['X_train'], snakes['Y_train'] + #X_train, Y_train = X_train[:10], Y_train[:10] #if you want to debug... + if NCELL < 10: X_train, Y_train = shorten_snakes(X_train, Y_train, NCELL) + + nbNoSnake, X_train, Y_train = augmentWithNoSnakeImages(X_train, Y_train, "train", bOneHot=False, nCell=NCELL) + X_train = [one_hot_colors(x) for x in X_train] + X_train, Y_train = shuffle_in_unison(X_train, Y_train) + X_train_directions, X_train_edge_features = prepare_data(X_train) + Y_train_flat = [y_.ravel() for y_ in Y_train] + + print("%d picture for training"%len(X_train)) + + # --- TEST + X_test, Y_test = snakes['X_test'], snakes['Y_test'] + if NCELL < 10: X_test, Y_test = shorten_snakes(X_test, Y_test, NCELL) + _, X_test, Y_test = augmentWithNoSnakeImages(X_test, Y_test, "test", bOneHot=False, nCell=NCELL) + + X_test = [one_hot_colors(x) for x in X_test] + X_test_directions, X_test_edge_features = prepare_data(X_test) + Y_test_flat = [y_.ravel() for y_ in Y_test] + + print("%d picture for test"%len(X_test)) + + # ------------------------------------------------------------------------------------- + + inference = 'qpbo' + bClassic = True #True => use the old good EdgeFeatureGraphCRF + + # now, use more informative edge features: + t0 = time.time() + if bClassic: + print("EdgeFeatureGraphCRF") + crf = EdgeFeatureGraphCRF(inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + #WHY THIS??? max_iter=100, + #why not this switch_to=ad3??? + switch_to='ad3', + #verbose=1, + n_jobs=2, + ) + ssvm.fit( X_train_edge_features , Y_train_flat) + else: + print("NodeTypeEdgeFeatureGraphCRF") + crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]], inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + switch_to='ad3', + #JL adds a max-iter sometimes + #max_iter=100, + n_jobs=1) + ssvm.fit( convertToSingleTypeX(X_train_edge_features) , Y_train_flat) + print("Training time = %.1fs"%(time.time()-t0)) + + if bClassic: + Y_pred2 = ssvm.predict( X_test_edge_features ) + else: + Y_pred2 = ssvm.predict( convertToSingleTypeX(X_test_edge_features) ) + print("Results using input features for edges") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + + + + #------------------------------------------------------------------------------------------------------------------------ + #Predict under constraints + if True and not bClassic: + def buildConstraintsFromSingleTyped(X, bOne=True): + """ + We iterate over each graph, and make sure that for each, we constrain to have a single instances of classes 1 to 9 + (or atmost one) + + The constraints must be a list of tuples like ( , , , ) + where: + - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - unaries is a list of the index of the unaries involved in this constraint + - states is a list of unary states, 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. + - negated is a list of boolean indicated if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list + """ + sLogicOp = "XOR" if bOne else "ATMOSTONE" + lConstraint = [] + for ([nf], [e], [ef]) in X: + n_nodes = nf.shape[0] + lConstraintPerGraph = [ (sLogicOp, range(n_nodes), i, False) for i in range(1,NCELL+1) ] #only one + lConstraint.append( lConstraintPerGraph ) + return lConstraint + + X_3 = convertToSingleTypeX(X_test_edge_features) + lC = buildConstraintsFromSingleTyped(X_3, False) + Y_pred2 = ssvm.predict( X_3, lC ) + print("Results using also input features for edges") + print("Inference with an ATMOST constraint per snake label") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + diff --git a/examples/plot_snakes_constraints.py b/examples/plot_snakes_constraints.py new file mode 100644 index 00000000..7108e830 --- /dev/null +++ b/examples/plot_snakes_constraints.py @@ -0,0 +1,269 @@ +""" +============================================== +Conditional Interactions on the Snakes Dataset +============================================== +This example uses the snake dataset introduced in +Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 + +This dataset is specifically designed to require the pairwise interaction terms +to be conditioned on the input, in other words to use non-trival edge-features. + +The task is as following: a "snake" of length ten wandered over a grid. For +each cell, it had the option to go up, down, left or right (unless it came from +there). The input consists of these decisions, while the desired output is an +annotation of the snake from 0 (head) to 9 (tail). See the plots for an +example. + +As input features we use a 3x3 window around each pixel (and pad with background +where necessary). We code the five different input colors (for up, down, left, right, +background) using a one-hot encoding. This is a rather naive approach, not using any +information about the dataset (other than that it is a 2d grid). + +The task can not be solved using the simple DirectionalGridCRF - which can only +infer head and tail (which are also possible to infer just from the unary +features). If we add edge-features that contain the features of the nodes that are +connected by the edge, the CRF can solve the task. + +From an inference point of view, this task is very hard. QPBO move-making is +not able to solve it alone, so we use the relaxed AD3 inference for learning. + +PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). +But it does work as well as Decision Tree Fields ;) + +UPDATE: we also inject domain knowledge at inference time by telling that there +is at-most or exactly one of each annotation from 1 to 10 (0 is background). + + JL Meunier - January 2017 + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943 + + Copyright Xerox + +""" +import time +import numpy as np + +from sklearn.metrics import confusion_matrix, accuracy_score + +from pystruct.learners import OneSlackSSVM +from pystruct.datasets import load_snakes +from pystruct.models import EdgeFeatureGraphCRF + +from plot_snakes import one_hot_colors, prepare_data + +def REPORT(l_Y_GT, lY_Pred, t=None): + if t: print "\t( predict DONE IN %.1fs)"%t + + _flat_GT, _flat_P = (np.hstack([y.ravel() for y in l_Y_GT]), + np.hstack([y.ravel() for y in lY_Pred])) + confmat = confusion_matrix(_flat_GT, _flat_P) + print confmat + print "\ttrace =", confmat.trace() + print "\tAccuracy= %.3f"%accuracy_score(_flat_GT, _flat_P) + + +print("Please be patient. Learning will take 5-20 minutes.") +snakes = load_snakes() +X_train, Y_train = snakes['X_train'], snakes['Y_train'] +#X_train, Y_train = X_train[:5], Y_train[:5] + +X_train = [one_hot_colors(x) for x in X_train] +Y_train_flat = [y_.ravel() for y_ in Y_train] + +X_train_directions, X_train_edge_features = prepare_data(X_train) +print "%d picture for training"%len(X_train) + +# Evaluate using confusion matrix. +# Clearly the middel of the snake is the hardest part. +X_test, Y_test = snakes['X_test'], snakes['Y_test'] +X_test = [one_hot_colors(x) for x in X_test] +Y_test_flat = [y_.ravel() for y_ in Y_test] +X_test_directions, X_test_edge_features = prepare_data(X_test) +print "%d picture for test"%len(X_test) + + +print "- TRAINING ONLY WITH DIRECTIONAL EDGE FEATURES -----" +#inference = 'qpbo' +#I'm interested in AD3 inference. +inference = 'ad3' + +# first, train on X with directions only: +crf = EdgeFeatureGraphCRF(inference_method=inference) +ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, + n_jobs=1) +t0 = time.time() +ssvm.fit(X_train_directions, Y_train_flat) +print("Model EdgeFeatureGraphCRF fitted. %.1fs"%(time.time()-t0)) + +Y_GT = np.hstack(Y_test_flat) +print("- Results using only directional features for edges. %.1fs"%(time.time()-t0)) +t0 = time.time() +Y_pred = ssvm.predict(X_test_directions) +REPORT(Y_GT, Y_pred, time.time()-t0) + +print "- Result with binarized graph" +t0 = time.time() +Y_pred = ssvm.predict(X_test_directions, [True]*len(X_test_directions)) +REPORT(Y_GT, Y_pred, time.time()-t0) + + +#Predict under constraints +def buildConstraints(X, bOne=True): + """ + We iterate over each graph, and make sure that for each, we constrain to have a single instances of classes 1 to 9 + (or atmost one) + + The constraints must be a list of tuples like ( , , , ) + where: + - operator is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - unaries is a list of the index of the unaries involved in this constraint + - states is a list of unary states, 1 per involved unary. If the states are all the same, you can pass it directly as a scalar value. + - negated is a list of boolean indicated if the unary must be negated. Again, if all values are the same, pass a single boolean value instead of a list + """ + sLogicOp = "XOR" if bOne else "ATMOSTONE" + lConstraint = [] + for (node_features, edges, edge_features) in X: + n_nodes = node_features.shape[0] + lConstraintPerGraph = [ (sLogicOp, range(n_nodes), i, False) for i in range(1,10) ] #only one + lConstraint.append( lConstraintPerGraph ) + return lConstraint + + +print "- Results of inference under constraints" +lConstraint = buildConstraints(X_test_directions) +t0 = time.time() +Y_pred = ssvm.predict(X_test_directions, lConstraint) +REPORT(Y_GT, Y_pred, time.time()-t0) + +# now, use more informative edge features: +print "- NOW TRAINING WITH BETTER EDGE FEATURES -----" +inference = 'qpbo' +crf = EdgeFeatureGraphCRF(inference_method=inference) +ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, switch_to='ad3', + n_jobs=1) +t0 = time.time() +ssvm.fit(X_train_edge_features, Y_train_flat) +print("Model EdgeFeatureGraphCRF fitted. %.1fs"%(time.time()-t0)) + + +print("- Results using also input features for edges. %.1fs"%(time.time()-t0)) +t0 = time.time() +Y_pred = ssvm.predict(X_test_edge_features) +REPORT(Y_GT, Y_pred, time.time()-t0) + +print "- Result with binarized graph" +t0 = time.time() +Y_pred = ssvm.predict(X_test_edge_features, [True]*len(X_test_edge_features)) +REPORT(Y_GT, Y_pred, time.time()-t0) + +#Predict under constraints +print "- Results of inference under constraints" +lConstraint = buildConstraints(X_test_edge_features) +t0 = time.time() +Y_pred = ssvm.predict(X_test_edge_features, lConstraint) +REPORT(Y_GT, Y_pred, time.time()-t0) + + +""" +Please be patient. Learning will take 5-20 minutes. +200 picture for training +100 picture for test +- TRAINING ONLY WITH DIRECTIONAL EDGE FEATURES ----- +Model EdgeFeatureGraphCRF fitted. 115.9s +- Results using only directional features for edges. 115.9s + ( predict DONE IN 0.7s) +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 59 0 22 4 6 1 7 1 0] + [ 0 3 1 29 5 31 8 18 1 3 1] + [ 0 1 13 2 30 11 25 1 13 3 1] + [ 0 1 1 9 4 46 11 15 3 9 1] + [ 0 1 7 2 24 10 21 7 23 2 3] + [ 0 0 1 6 7 35 10 17 3 21 0] + [ 0 0 7 2 14 10 16 4 25 0 22] + [ 0 0 0 3 7 14 4 12 2 58 0] + [ 0 0 5 3 11 3 7 0 5 0 66]] + trace = 3201 + Accuracy= 0.854 +- Result with binarized graph + ( predict DONE IN 0.7s) +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 59 0 22 4 6 1 7 1 0] + [ 0 3 1 29 5 31 8 18 1 3 1] + [ 0 1 13 2 30 11 25 1 13 3 1] + [ 0 1 1 9 4 46 11 15 3 9 1] + [ 0 1 7 2 24 10 21 7 23 2 3] + [ 0 0 1 6 7 35 10 17 3 21 0] + [ 0 0 7 2 14 10 16 4 25 0 22] + [ 0 0 0 3 7 14 4 12 2 58 0] + [ 0 0 5 3 11 3 7 0 5 0 66]] + trace = 3201 + Accuracy= 0.854 +- Results of inference under constraints + ( predict DONE IN 0.7s) +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 59 0 22 4 6 1 7 1 0] + [ 0 3 1 29 5 31 8 18 1 3 1] + [ 0 1 13 2 30 11 25 1 13 3 1] + [ 0 1 1 9 4 46 11 15 3 9 1] + [ 0 1 7 2 24 10 21 7 23 2 3] + [ 0 0 1 6 7 35 10 17 3 21 0] + [ 0 0 7 2 14 10 16 4 25 0 22] + [ 0 0 0 3 7 14 4 12 2 58 0] + [ 0 0 5 3 11 3 7 0 5 0 66]] + trace = 3201 + Accuracy= 0.854 +- NOW TRAINING WITH BETTER EDGE FEATURES ----- +Model EdgeFeatureGraphCRF fitted. 679.6s +- Results using also input features for edges. 679.6s + ( predict DONE IN 0.9s) +[[2749 0 0 0 0 0 0 0 1 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 100 0 0 0 0 0 0 0] + [ 0 0 0 0 98 0 1 0 1 0 0] + [ 0 0 0 2 0 98 0 0 0 0 0] + [ 0 0 0 0 2 0 98 0 0 0 0] + [ 0 1 0 0 0 2 0 97 0 0 0] + [ 0 0 1 0 0 0 1 0 98 0 0] + [ 0 0 0 1 0 0 0 0 0 99 0] + [ 0 0 0 0 1 0 0 0 0 0 99]] + trace = 3736 + Accuracy= 0.996 +- Result with binarized graph + ( predict DONE IN 0.9s) +[[2749 0 0 0 0 0 0 0 1 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 100 0 0 0 0 0 0 0] + [ 0 0 0 0 98 0 1 0 1 0 0] + [ 0 0 0 2 0 98 0 0 0 0 0] + [ 0 0 0 0 2 0 98 0 0 0 0] + [ 0 1 0 0 0 2 0 97 0 0 0] + [ 0 0 1 0 0 0 1 0 98 0 0] + [ 0 0 0 1 0 0 0 0 0 99 0] + [ 0 0 0 0 1 0 0 0 0 0 99]] + trace = 3736 + Accuracy= 0.996 +- Results of inference under constraints + ( predict DONE IN 0.9s) +[[2749 0 0 0 0 0 0 0 1 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 100 0 0 0 0 0 0 0] + [ 0 0 0 0 98 0 1 0 1 0 0] + [ 0 0 0 2 0 98 0 0 0 0 0] + [ 0 0 0 0 2 0 98 0 0 0 0] + [ 0 1 0 0 0 2 0 97 0 0 0] + [ 0 0 1 0 0 0 1 0 98 0 0] + [ 0 0 0 1 0 0 0 0 0 99 0] + [ 0 0 0 0 1 0 0 0 0 0 99]] + trace = 3736 + Accuracy= 0.996 + + +""" \ No newline at end of file diff --git a/examples/plot_snakes_typed.py b/examples/plot_snakes_typed.py new file mode 100644 index 00000000..92d37189 --- /dev/null +++ b/examples/plot_snakes_typed.py @@ -0,0 +1,161 @@ +""" +============================================== +Conditional Interactions on the Snakes Dataset +============================================== + +This is a variant of plot_snakes.py where we use the NodeTypeEdgeFeatureGraphCRF +class instead of EdgeFeatureGraphCRF, despite there is only 1 type of nodes. +So this should give exact same results as plot_snakes.py + + +This example uses the snake dataset introduced in +Nowozin, Rother, Bagon, Sharp, Yao, Kohli: Decision Tree Fields ICCV 2011 + +This dataset is specifically designed to require the pairwise interaction terms +to be conditioned on the input, in other words to use non-trival edge-features. + +The task is as following: a "snake" of length ten wandered over a grid. For +each cell, it had the option to go up, down, left or right (unless it came from +there). The input consists of these decisions, while the desired output is an +annotation of the snake from 0 (head) to 9 (tail). See the plots for an +example. + +As input features we use a 3x3 window around each pixel (and pad with background +where necessary). We code the five different input colors (for up, down, left, right, +background) using a one-hot encoding. This is a rather naive approach, not using any +information about the dataset (other than that it is a 2d grid). + +The task can not be solved using the simple DirectionalGridCRF - which can only +infer head and tail (which are also possible to infer just from the unary +features). If we add edge-features that contain the features of the nodes that are +connected by the edge, the CRF can solve the task. + +From an inference point of view, this task is very hard. QPBO move-making is +not able to solve it alone, so we use the relaxed AD3 inference for learning. + +PS: This example runs a bit (5 minutes on 12 cores, 20 minutes on one core for me). +But it does work as well as Decision Tree Fields ;) + + JL Meunier - January 2017 + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943 + + Copyright Xerox + +""" +from __future__ import (absolute_import, division, print_function) + +import numpy as np +# import matplotlib.pyplot as plt + +from sklearn.preprocessing import label_binarize +from sklearn.metrics import confusion_matrix, accuracy_score + +from pystruct.learners import OneSlackSSVM +from pystruct.datasets import load_snakes +from pystruct.utils import make_grid_edges, edge_list_to_features +#from pystruct.models import EdgeFeatureGraphCRF +from pystruct.models import NodeTypeEdgeFeatureGraphCRF + +from plot_snakes import one_hot_colors, neighborhood_feature, prepare_data + +def convertToSingleTypeX(X): + """ + For NodeTypeEdgeFeatureGraphCRF X is structured differently. + But NodeTypeEdgeFeatureGraphCRF can handle graph with a single node type. One needs to convert X to the new structure using this method. + """ + return [([nf], [e], [ef]) for (nf,e,ef) in X] + +if __name__ == '__main__': + print("Please be patient. Learning will take 5-20 minutes.") + snakes = load_snakes() + X_train, Y_train = snakes['X_train'], snakes['Y_train'] + + X_train = [one_hot_colors(x) for x in X_train] + Y_train_flat = [y_.ravel() for y_ in Y_train] + + + X_train_directions, X_train_edge_features = prepare_data(X_train) + + inference = 'ad3+' + # first, train on X with directions only: + crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[2]], inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, max_iter=100, + n_jobs=1) + ssvm.fit(convertToSingleTypeX(X_train_directions), Y_train_flat) + + # Evaluate using confusion matrix. + # Clearly the middel of the snake is the hardest part. + X_test, Y_test = snakes['X_test'], snakes['Y_test'] + X_test = [one_hot_colors(x) for x in X_test] + Y_test_flat = [y_.ravel() for y_ in Y_test] + X_test_directions, X_test_edge_features = prepare_data(X_test) + Y_pred = ssvm.predict( convertToSingleTypeX(X_test_directions) ) + print("Results using only directional features for edges") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred))) + + # now, use more informative edge features: + crf = NodeTypeEdgeFeatureGraphCRF(1, [11], [45], [[180]], inference_method=inference) + ssvm = OneSlackSSVM(crf, inference_cache=50, C=.1, tol=.1, + # switch_to='ad3', + #verbose=1, + n_jobs=8) + ssvm.fit( convertToSingleTypeX(X_train_edge_features), Y_train_flat) + Y_pred2 = ssvm.predict( convertToSingleTypeX(X_test_edge_features) ) + print("Results using also input features for edges") + print("Test accuracy: %.3f" + % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) + +# if False: +# # plot stuff +# fig, axes = plt.subplots(2, 2) +# axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') +# axes[0, 0].set_title('Input') +# y = Y_test[0].astype(np.int) +# bg = 2 * (y != 0) # enhance contrast +# axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) +# axes[0, 1].set_title("Ground Truth") +# axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) +# axes[1, 0].set_title("Prediction w/o edge features") +# axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) +# axes[1, 1].set_title("Prediction with edge features") +# for a in axes.ravel(): +# a.set_xticks(()) +# a.set_yticks(()) +# plt.show() + +""" +Please be patient. Learning will take 5-20 minutes. +Results using only directional features for edges +Test accuracy: 0.847 +[[2750 0 0 0 0 0 0 0 0 0 0] + [ 0 99 0 0 1 0 0 0 0 0 0] + [ 0 2 68 3 9 4 6 4 3 1 0] + [ 0 4 11 45 8 14 5 6 0 6 1] + [ 0 1 22 18 31 2 14 4 3 5 0] + [ 0 3 7 38 12 22 5 4 2 7 0] + [ 0 2 19 16 26 8 16 2 9 2 0] + [ 0 6 14 26 10 15 5 12 2 10 0] + [ 0 0 12 15 16 4 16 2 18 4 13] + [ 0 2 5 18 6 8 5 3 2 50 1] + [ 0 1 11 4 13 1 2 0 2 2 64]] +Results using also input features for edges +Test accuracy: 0.998 +[[2749 0 0 0 0 0 0 0 1 0 0] + [ 0 100 0 0 0 0 0 0 0 0 0] + [ 0 0 100 0 0 0 0 0 0 0 0] + [ 0 0 0 99 0 0 0 0 0 1 0] + [ 0 0 0 0 99 0 1 0 0 0 0] + [ 0 0 0 1 0 98 0 1 0 0 0] + [ 0 0 0 0 1 0 99 0 0 0 0] + [ 0 0 0 0 0 1 0 99 0 0 0] + [ 0 0 0 0 0 0 0 0 100 0 0] + [ 0 0 0 0 0 0 0 1 0 99 0] + [ 0 0 0 0 0 0 0 0 0 0 100]] + +""" \ No newline at end of file diff --git a/pystruct/models/node_type_edge_feature_graph_crf.py b/pystruct/models/node_type_edge_feature_graph_crf.py new file mode 100644 index 00000000..de1e7709 --- /dev/null +++ b/pystruct/models/node_type_edge_feature_graph_crf.py @@ -0,0 +1,440 @@ +# -*- coding: utf-8 -*- + +""" + Pairwise CRF with features/strength associated to each edge and different + types of nodes + + JL. Meunier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943. + +""" +import numpy as np +import random + +from ..inference import inference_dispatch +from .utils import loss_augment_unaries + +from .typed_crf import TypedCRF, InconsistentLabel + + +class NodeTypeEdgeFeatureGraphCRF(TypedCRF): + """ + Pairwise CRF with features/strength associated to each edge and different + types of nodes + + Pairwise potentials are asymmetric and shared over all edges of same type. + They are weighted by an edge-specific features, though. + This allows for contrast sensitive potentials or directional potentials + (using a {-1, +1} encoding of the direction for example). + + More complicated interactions are also possible, of course. + + + Parameters + ---------- + n_types : number of node types + + l_n_states : list of int, default=None + Number of states per type of variables. + + l_n_features : list of int, default=None + Number of features per type of node. + + a_n_edge_features: an array of shape (n_types, n_types) giving the number + of features per pair of types + + NOTE: there should always be at least 1 feature for any pairs of types + which has some edge in the graph. + To mimic GraphCRF, pass 1 and make a constant feature of 1.0 for all + those edges. + + class_weight : None, or list of array-like (ndim=1) + Class weights. If a list of array-like is passed, the Ith one must have + length equal to l_n_states[i] + None means equal class weights (across node types) + + X and Y + ------- + Node features are given as a list of n_types arrays of shape + (n_type_nodes, n_type_features): + - n_type_nodes is the number of nodes of that type + - n_type_features is the number of features for this type of node + + Edges are given as a list of n_types x n_types arrays of shape + (n_type_edges, 2). + Columns are resp.: node index (in corresponding node type), node index + (in corresponding node type) + + Edge features are given as a list of n_types x n_types arrays of shape + (n_type_type_edge, n_type_type_edge_features) + - n_type_type_edge is the number of edges of type type_type + - n_type_type_edge_features is the number of features for edge of type + type_type + + An instance ``X`` is represented as a tuple ``([node_features, ..] + , [edges, ..], [edge_features, ..])`` + + Labels ``Y`` are given as one array of shape (n_nodes) + Labels are numbered from 0 so that each label across types is encoded + by a unique integer. + + Look at flattenY and unflattentY if you want to pass/obtain list of + labels per type, with first label of each type being encoded by 0 + + """ + + def __init__(self, + n_types, # how many node type? + l_n_states, # how many labels per node type? + l_n_features, # how many features per node type? + a_n_edge_features, # how many features per edge type? + inference_method="ad3", + l_class_weight=None): # class_weight per node type or None + # or None + + # how many features per node type X node type? + # (MUST be symmetric!) + self.a_n_edge_features = np.array(a_n_edge_features) + if self.a_n_edge_features.shape != (n_types, n_types): + raise ValueError("Expected a feature number matrix for edges of " + "shape (%d, %d), got " + "%s." % (n_types, n_types, + self.a_n_edge_features.shape)) + self.a_n_edge_features = self.a_n_edge_features.reshape(n_types, + n_types) + if not (self.a_n_edge_features == self.a_n_edge_features.T).all(): + raise ValueError("Expected a symmetric array of edge feature " + "numbers") + + # number of (edge) features per edge type + self.l_n_edge_features = self.a_n_edge_features.ravel() + # total number of (edge) features + self._n_edge_features = self.a_n_edge_features.sum(axis=None) + + TypedCRF.__init__(self, n_types, l_n_states, l_n_features, + inference_method=inference_method, + l_class_weight=l_class_weight) + + self._get_pairwise_potentials_initialize() + + def _set_size_joint_feature(self): + """ + We have: + - 1 weight per node feature per label per node type + - 1 weight per edge feature per label of node1 type, per label of node2 + type + + NOTE: for now, a typ1, typ2 type of edge with 0 features is simply + ignored. While it could get a state x state matrix of weights + """ + if self.l_n_features: + self.size_unaries = sum(n_states * n_features for n_states, + n_features in zip(self.l_n_states, + self.l_n_features)) + + # detailed non-optimized computation to make things clear + self.size_pairwise = 0 + for typ1, typ2 in self._iter_type_pairs(): + self.size_pairwise += self.a_n_edge_features[typ1, typ2]\ + * self.l_n_states[typ1]\ + * self.l_n_states[typ2] + + self.size_joint_feature = self.size_unaries + self.size_pairwise + + def __repr__(self): + return ("%s(n_states: %s, inference_method: %s, n_features: %s, " + "n_edge_features: %s)" + % (type(self).__name__, self.l_n_states, self.inference_method, + self.l_n_features, self.a_n_edge_features)) + + def _check_size_x(self, x): + l_edges = self._get_edges(x) + if len(l_edges) != self.n_types**2: + raise ValueError("Expected %d edge arrays " + "or None" % (self.n_types**2)) + l_edge_features = self._get_edge_features(x) + if len(l_edge_features) != self.n_types**2: + raise ValueError("Expected %d edge feature arrays " + "or None" % (self.n_types**2)) + + TypedCRF._check_size_x(self, x) + + # check that we have in total 1 feature vector per edge + for edges, edge_features in zip(l_edges, l_edge_features): + if edges is None or edge_features is None: + if edges is None and edge_features is None: + continue + if edges is None: + raise ValueError("Empty edge array but non empty " + "edge-feature array, for same type of " + "edge") + else: + raise ValueError("Empty edge-feature array but non empty " + "edge array, for same type of edge") + if edge_features.ndim != 2: + raise ValueError("Expected a 2 dimensions edge feature arrays") + if len(edges) != len(edge_features): + raise ValueError("Edge and edge feature matrices must have " + "same size in 1st dimension") + + # check edge feature size + for typ1, typ2 in self._iter_type_pairs(): + edge_features = l_edge_features[typ1*self.n_types+typ2] + if edge_features is None: + continue + if edge_features.shape[1] != self.a_n_edge_features[typ1, typ2]: + raise ValueError("Types %d x %d: bad number of edge features. " + "expected %d " + "got %d" % (typ1, typ2, + self.a_n_edge_features[typ1, + typ2], + edge_features.shape[1])) + return True + + def _get_edge_features(self, x): + # we replace None by empty array with proper shape + return [np.empty((0, _n_feat)) + if _ef is None + else _ef + for _ef, _n_feat in zip(x[2], self.l_n_edge_features)] + + def _get_pairwise_potentials_initialize(self): + """ + Putting in cache the params required to build the pairwise potentials + given x and w + """ + self._cache_pairwise_potentials = list() + + i_w, n_states1, i_states1 = 0, 0, 0 + + for typ1 in range(self.n_types): + n_states1 = self.l_n_states[typ1] + i_states1_stop = i_states1 + n_states1 + n_states2, i_states2 = 0, 0 + for typ2 in range(self.n_types): + n_features = self.a_n_edge_features[typ1, typ2] + n_states2 = self.l_n_states[typ2] + i_w_stop = i_w + n_features * n_states1 * n_states2 + i_states2_stop = i_states2 + n_states2 + + self._cache_pairwise_potentials.append((n_features, + n_states1, n_states2, + i_states1, + i_states1_stop, + i_states2, + i_states2_stop, + i_w, i_w_stop)) + + i_w, i_states2 = i_w_stop, i_states2_stop + i_states1 = i_states1_stop + + def _get_pairwise_potentials(self, x, w): + """Computes pairwise potentials for x and w. + + Parameters + ---------- + x : tuple + Instance Representation. + + w : ndarray, shape=(size_joint_feature,) + Weight vector for CRF instance. + + Returns + ------- + pairwise: list of pairwise weights of shape: + (n_edges, n_states_typA, n_states_typB) + + """ + self._check_size_w(w) + + l_edge_features = self._get_edge_features(x) + wpw = w[self.size_unaries:] + + l_pairwise_potentials = [] + + i_w = 0 + for (typ1, typ2), edge_features in zip(self._iter_type_pairs(), + l_edge_features): + n_edges, n_features = edge_features.shape + n_states1 = self.l_n_states[typ1] + n_states2 = self.l_n_states[typ2] + n_w = n_features * n_states1 * n_states2 + if n_w: + # n_states1*n_states2 x nb_feat + pw_typ_typ = wpw[i_w:i_w + n_w].reshape(n_features, -1) + l_pairwise_potentials.append(np.dot(edge_features, + pw_typ_typ + ).reshape(n_edges, + n_states1, + n_states2)) + else: + # first reshaping above complains: "ValueError: total size of + # new array must be unchanged" + l_pairwise_potentials.append(np.array([])) + i_w += n_w + + return l_pairwise_potentials + + def joint_feature(self, x, y): + """Feature vector associated with instance (x, y). + + Feature representation joint_feature, such that the energy of the + configuration + (x, y) and a weight vector w is given by np.dot(w,joint_feature(x, y)). + + Parameters + ---------- + x : tuple + Input representation. + + y : list of ndarrays or some tuple (internal use!) + Either y is a list of a integral ndarrays, giving a complete + labeling for x. + Or it is the result of a linear programming relaxation. In this + case, ``y=(unary_marginals, pariwise_marginals)``. + + Returns + ------- + p : ndarray, shape (size_joint_feature,) + Feature vector associated with state (x, y). + + """ + self._check_size_x(x) # call initialize once! + l_node_features = self._get_node_features(x) + l_edges, l_edge_features = (self._get_edges(x), + self._get_edge_features(x)) + l_n_nodes = [len(nf) for nf in self._get_node_features(x)] + l_n_edges = [len(ef) for ef in self._get_edges(x)] + + if isinstance(y, tuple): + # y is result of relaxation, tuple of unary and pairwise marginals + unary_marginals, pw = y + + if isinstance(unary_marginals, list): + # ad3+ returns a list of unaries, nothing to do here!! :) + l_unary_marginals = unary_marginals + else: + # in case we use someother method (not supported for now + # actually) + l_unary_marginals = [] + i, j = 0, 0 + # iteration by type + for (_n_nodes, _n_states) in zip(l_n_nodes, self.l_n_states): + _n_binaries = _n_nodes * _n_states + _unary_marginals = unary_marginals[i:i+_n_nodes, + j:j+_n_states] + i += _n_nodes + j += _n_states + l_unary_marginals.append(_unary_marginals) + + if isinstance(pw, list): + # ad3+ returns a list of pairwise + l_pw = pw + else: + # until we do better in ad3+ inference, but we cannot I think + # without touching the learners... + l_pw = [] + i_start = 0 + for _n_edges, (typ1, typ2) in zip(l_n_edges, + self._iter_type_pairs()): + n = self.l_n_states[typ1] * self.l_n_states[typ2] + i_stop = i_start + _n_edges + i_state_start = self.a_startindex_by_typ_typ[typ1, typ2] + _edge_marginals = pw[i_start:i_stop, + i_state_start:i_state_start+n] + i_start = i_stop + l_pw.append(_edge_marginals) + else: + self._check_size_xy(x, y) + # make one hot encoding per type + l_unary_marginals = [] + i_start = 0 + for (_n_nodes, + _n_states, + typ_start_index) in zip(l_n_nodes, + self.l_n_states, + self._l_type_startindex): + i_stop = i_start + _n_nodes + _unary_marginals = np.zeros((_n_nodes, _n_states), + dtype=np.int) + gx = np.ogrid[:_n_nodes] + _unary_marginals[gx, y[i_start:i_stop]-typ_start_index] = 1 + l_unary_marginals.append(_unary_marginals) + i_start = i_stop + + # pairwise + # same thing, but the type of an edge is a pair of node types + l_pw = [] + node_offset_by_typ = np.cumsum([0]+[0 if n is None + else n.shape[0] for n in x[0]]) + for _n_edges, (typ1, typ2), edges in zip(l_n_edges, + self._iter_type_pairs(), + l_edges): + _n_states_typ1 = self.l_n_states[typ1] + _n_states_typ2 = self.l_n_states[typ2] + _pw = np.zeros((_n_edges, _n_states_typ1 * _n_states_typ2)) + if _n_edges: + y1 = y[node_offset_by_typ[typ1] + edges[:, 0]]\ + - self._l_type_startindex[typ1] + y2 = y[node_offset_by_typ[typ2] + edges[:, 1]]\ + - self._l_type_startindex[typ2] + assert (0 <= y1).all() and (y1 <= + self.l_n_states[typ1]).all() + assert (0 <= y2).all() and (y2 <= + self.l_n_states[typ2]).all() + # set the 1s where they should + class_pair_ind = (y2 + _n_states_typ2 * y1) + _pw[np.arange(_n_edges), class_pair_ind] = 1 + l_pw.append(_pw) + + # UNARY + l_unary_acc_ravelled = [np.dot(unary_marginals.T, features).ravel() + for (unary_marginals, features) + in zip(l_unary_marginals, l_node_features)] + unaries_acc_ravelled = np.hstack(l_unary_acc_ravelled) + + # PW + l_pw_ravelled = [np.dot(ef.T, pw).ravel() for (ef, pw) + in zip(l_edge_features, l_pw)] + pairwise_acc_ravelled = np.hstack(l_pw_ravelled) + + joint_feature_vector = np.hstack([unaries_acc_ravelled, + pairwise_acc_ravelled]) + + return joint_feature_vector + + def loss_augment_unaries(self, l_unary_potentials, y): + """ + we do it type-wise + """ + i_start = 0 + a_y = np.asarray(y) + + for typ, (unary_potentials, class_weight) in enumerate( + zip(l_unary_potentials, self.l_class_weight)): + n_y = unary_potentials.shape[0] + # label 0 must correspond to 1st weight + y_typ = a_y[i_start:i_start+n_y] - self._l_type_startindex[typ] + loss_augment_unaries(unary_potentials, y_typ, class_weight) + i_start += n_y diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py new file mode 100644 index 00000000..5c3e87ce --- /dev/null +++ b/pystruct/models/typed_crf.py @@ -0,0 +1,342 @@ +# -*- coding: utf-8 -*- + +""" + CRF with different types of nodes + + NOTE: this is an abstract class. Do not use directly. + + JL. Meunier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + Developed for the EU project READ. The READ project has received funding + from the European Union's Horizon 2020 research and innovation programme + under grant agreement No 674943. + +""" +import numpy as np + +from .crf import CRF +from ..inference import get_installed + + +class InconsistentLabel(Exception): + pass + + +class TypedCRF(CRF): + """Abstract base class""" + def __init__(self, + n_types, # how many node type? + l_n_states, # how many labels per node type? + l_n_features, # how many features per node type? + inference_method="ad3", + l_class_weight=None): # class_weight per node type or None + # or None + + if inference_method is None: + # get first in list that is installed + inference_method = get_installed(['ad3+', 'ad3'])[0] + self.setInferenceMethod(inference_method) + + self.inference_calls = 0 + # if inference cannot be done, raises an exception + self.inference_exception = False + + if len(l_n_states) != n_types: + raise ValueError("Expected 1 number of states per node type.") + if l_n_features is not None and len(l_n_features) != n_types: + raise ValueError("Expected 1 number pf features per node type.") + self.n_types = n_types + self.l_n_states = l_n_states + self._n_states = sum(l_n_states) # total number of states + self.l_n_features = l_n_features + self._n_features = sum(self.l_n_features) # total number of node feat. + + # number of typextype states, or number of states per type of edge + self.l_n_edge_states = [n1 * n2 + for n1 in self.l_n_states + for n2 in self.l_n_states] + + # class weights: + # either we get class weights for all types of nodes + # , or for none of them! + if l_class_weight: + if len(l_class_weight) != self.n_types: + raise ValueError("Expected 1 class weight list per node type.") + for i, n_states in enumerate(self.l_n_states): + if len(l_class_weight[i]) != n_states: + raise ValueError("Expected 1 class weight per state" + " per node type. Wrong for type %d" % i) + + # class weights are computed by type and simply concatenated + self.l_class_weight = [np.asarray(class_weight) + for class_weight in l_class_weight] + else: + self.l_class_weight = [np.ones(n) for n in self.l_n_states] + self.class_weight = np.hstack(self.l_class_weight) + + self._set_size_joint_feature() + + # internal stuff + # when putting node states in a single sequence, index of 1st state + # for type i + self._l_type_startindex = [sum(self.l_n_states[:i]) + for i in range(self.n_types+1)] + + # when putting edge states in a single sequence, index of 1st state of + # an edge of type (typ1, typ2) + self.a_startindex_by_typ_typ = np.zeros((self.n_types, self.n_types), + dtype=np.uint32) + i_state_start = 0 + for typ1, typ1_n_states in enumerate(self.l_n_states): + for typ2, typ2_n_states in enumerate(self.l_n_states): + self.a_startindex_by_typ_typ[typ1, typ2] = i_state_start + i_state_start += typ1_n_states*typ2_n_states + + # -------------- CONVENIENCE -------------------------- + def setInferenceMethod(self, inference_method): + if inference_method in ["ad3", "ad3+"]: + self.inference_method = inference_method + else: + raise Exception("You must use ad3 or ad3+ as inference method") + + def flattenY(self, lY_by_typ): + """ + It is more convenient to have the Ys grouped by type, as the Xs are, + and to have the first label of each type encoded as 0. + + This method does the job. It returns a flat Y array, with unique code + per class label, which can be passed to 'fit' + """ + lY = list() + for n_start_state, Y_typ in zip(self._l_type_startindex, lY_by_typ): + lY.append(np.asarray(Y_typ) + n_start_state) + return np.hstack(lY) + + def unflattenY(self, X, flatY): + """ + predict returns a flat array of Y (same structure as for 'fit') + This method structures the Y as a list of Y_per_type, where the first + label of any type is 0 + """ + lY = list() + i_start_node = 0 + (l_node_features, l_edges, l_edge_features) = X + for n_start_state, nf in zip(self._l_type_startindex, l_node_features): + n_nodes = nf.shape[0] + Y = flatY[i_start_node: i_start_node+n_nodes] - n_start_state + lY.append(Y) + i_start_node += n_nodes + if flatY.shape != (i_start_node,): + raise ValueError("The total number of label does not match the" + " total number of nodes:" + " %d != %d" % (flatY.shape[0], i_start_node)) + return lY + + def initialize(self, X, Y=None): + """ + It is optional to call it. Does data checking only! + """ + if isinstance(X, list): + map(self._check_size_x, X) + if not (Y is None): + map(self._check_size_xy, X, Y) + else: + self._check_size_x(X) + self._check_size_xy(X, Y) + + def setInferenceException(self, bRaiseExceptionWhenInferenceNotSuccessful): + """ + set exception on or off when inference canoot be done. + """ + self.inference_exception = bRaiseExceptionWhenInferenceNotSuccessful + return self.inference_exception + + # -------------- INTERNAL STUFF -------------------------- + def _set_size_joint_feature(self): + """ + We have: + - 1 weight per node feature per label per node type + """ + self.size_unaries = sum(n_states * n_features for n_states, n_features + in zip(self.l_n_states, self.l_n_features) + ) + self.size_joint_feature = self.size_unaries + + def __repr__(self): + return ("%s(n_states: %s, inference_method: %s)" + % (type(self).__name__, self.l_n_states, + self.inference_method)) + + def _check_size_x(self, x): + # node_features are [ i_in_typ -> features ] + l_node_features = self._get_node_features(x) + if len(l_node_features) != self.n_types: + raise ValueError("Expected one node feature array per node type.") + + for typ, typ_features in enumerate(l_node_features): + if typ_features.shape[1] != self.l_n_features[typ]: + raise ValueError("Expected %d features for type" + " %d" % (self.l_n_features[typ], typ)) + + # edges + l_edges = self._get_edges(x) + for edges in l_edges: + if edges is None: + continue + if edges.ndim != 2: + raise ValueError("Expected a 2 dimensions edge arrays") + if edges.shape[1] != 2: + raise ValueError("Expected 2 columns in edge arrays") + + for typ1, typ2 in self._iter_type_pairs(): + edges = self._get_edges_by_type(x, typ1, typ2) + + if edges is None or len(edges) == 0: + continue + # edges should point to valid node indices + nodes1, nodes2 = edges[:, 0], edges[:, 1] + if min(nodes1) < 0 or min(nodes2) < 0: + raise ValueError("At least one edge points to negative and" + " therefore invalid node index:" + " type %d to type %d" % (typ1, typ2)) + if max(nodes1) >= l_node_features[typ1].shape[0]: + raise ValueError("At least one edge starts from a non-existing" + " node index:" + " type %d to type %d" % (typ1, typ2)) + if max(nodes2) >= l_node_features[typ2].shape[0]: + raise ValueError("At least one edge points to a non-existing" + " node index:" + " type %d to type %d" % (typ1, typ2)) + return True + + def _check_size_xy(self, X, Y): + if Y is None: + return + + # make sure Y has the proper length and acceptable labels + l_node_features = self._get_node_features(X) + + nb_nodes = sum(nf.shape[0] for nf in l_node_features) + if Y.shape[0] != nb_nodes: + raise ValueError("Expected 1 label for each of the %d nodes. Got" + " %d labels." % (nb_nodes, Y.shape[0])) + + i_start = 0 + for typ, nf, n_states in zip(range(self.n_types), + l_node_features, + self.l_n_states): + nb_nodes = nf.shape[0] + if nb_nodes == 0: + continue + Y_typ = Y[i_start:i_start+nb_nodes] + if np.min(Y_typ) < 0: + raise ValueError("Got a negative label for type %d" % typ) + if np.min(Y_typ) < self._l_type_startindex[typ]: + raise InconsistentLabel("labels of type %d start at %d" + "" % (typ, + self._l_type_startindex[typ])) + if np.max(Y_typ) >= self._l_type_startindex[typ+1]: + raise InconsistentLabel("labels of type %d end at %d" + "" % (typ, + self._l_type_startindex[typ+1]-1) + ) + i_start = i_start + nb_nodes + return True + + def _get_node_features(self, x): + # we replace None by empty array with proper shape + return [np.empty((0, _n_feat)) if node_features is None + else node_features + for (node_features, _n_feat) in zip(x[0], self.l_n_features)] + + def _get_edges(self, x): + return [np.empty((0, 2)) if edges is None or len(edges) == 0 + else edges for edges in x[1]] + + def _get_edges_by_type(self, x, typ1, typ2): + return x[1][typ1 * self.n_types+typ2] + + def _iter_type_pairs(self): + for typ1 in range(self.n_types): + for typ2 in range(self.n_types): + yield (typ1, typ2) + raise StopIteration + + def _get_unary_potentials(self, x, w): + """Computes unary potentials for x and w. + + Parameters + ---------- + x : tuple + Instance Representation. + + w : ndarray, shape=(size_joint_feature,) + Weight vector for CRF instance. + + Returns + ------- + unaries : list of ndarray, shape=( n_nodes_typ, n_states_typ ) + Unary weights. + """ + self._check_size_w(w) + l_node_features = self._get_node_features(x) + + l_unary_potentials = [] + + i_w = 0 + for (features, n_states, n_features) in zip(l_node_features, + self.l_n_states, + self.l_n_features): + n_w = n_states*n_features + l_unary_potentials.append( + np.dot(features, + w[i_w:i_w+n_w].reshape(n_states, + n_features).T + ) + ) + i_w += n_w + assert i_w == self.size_unaries + + # nodes x features . features x states --> nodes x states + return l_unary_potentials + + def continuous_loss(self, y, l_y_hat): + # continuous version of the loss + # y is the result of linear programming + # BUT, in multitype mode, y_hat is a list of unaries + l_result = list() + cum_n_node = 0 + cum_n_state = 0 + for y_hat in l_y_hat: + n_node, n_state = y_hat.shape + # all entries minus correct ones + # select the correct range of labels and make the labels start at 0 + y_type = y[cum_n_node:cum_n_node+n_node] - cum_n_state + gx = np.indices(y_type.shape) + result = 1 - y_hat[gx, y_type] + l_result.append(result) + cum_n_node += n_node + cum_n_state += n_state + result = np.hstack(l_result) + + if hasattr(self, 'class_weight'): + return np.sum(self.class_weight[y] * result) + return np.sum(result) diff --git a/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py new file mode 100644 index 00000000..7919817a --- /dev/null +++ b/pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py @@ -0,0 +1,872 @@ +import pytest +import numpy as np +from numpy.testing import (assert_array_equal, assert_array_almost_equal, + assert_almost_equal, assert_equal) +from nose.tools import assert_raises + +from pystruct.models import NodeTypeEdgeFeatureGraphCRF, EdgeFeatureGraphCRF + +from pystruct.inference.linear_programming import lp_general_graph +from pystruct.inference import compute_energy, get_installed +from pystruct.utils import make_grid_edges, edge_list_to_features +from pystruct.datasets import generate_blocks_multinomial + + + +def test_checks(): + g = NodeTypeEdgeFeatureGraphCRF( + 1 #how many node type? + , [4] #how many labels per node type? + , [3] #how many features per node type? + , np.array([[3]]) #how many features per node type X node type? + ) + + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3 ] #how many labels per node type? + , [4, 5] #how many features per node type? + , np.array([[1, 2], [2,4]]) #how many features per node type X node type? + ) + + with pytest.raises(ValueError): + g = NodeTypeEdgeFeatureGraphCRF( + 3 #how many node type? + , [2, 3 ] #how many labels per node type? + , [4, 5] #how many features per node type? + , np.array([[1, 2], [2,4]]) #how many features per node type X node type? + ) + + with pytest.raises(ValueError): + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3 ] #how many labels per node type? + , [4, 5, 3] #how many features per node type? + , np.array([[1, 2], [2,4]]) #how many features per node type X node type? + ) + + with pytest.raises(ValueError): + g = NodeTypeEdgeFeatureGraphCRF( + 3 #how many node type? + , [2, 3 ] #how many labels per node type? + , [4, 5] #how many features per node type? + , np.array([[1, 2], [2,4]]) #how many features per node type X node type? + ) + + with pytest.raises(ValueError): + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3 ] #how many labels per node type? + , [4, 5] #how many features per node type? + , np.array([[1, 2, 3], [2,3,4]]) #how many features per node type X node type? + ) + + with pytest.raises(ValueError): + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3 ] #how many labels per node type? + , [4, 5] #how many features per node type? + , np.array([[1, 2], [99,4]]) #how many features per node type X node type? + ) + +def debug_joint_feature(): + # ------------------------------------------------------------------------------------------- + #print "---MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3] #how many possible labels per node type? + , [3, 4] #how many features per node type? + , np.array([ [1, 2] + , [2, 3]]) #how many features per node type X node type? + ) + + l_node_f = [ np.array([ [1,1,1], [2,2,2] ]) + , np.array([ [.11, .12, .13, .14], [.21, .22, .23, .24], [.31, .32, .33, .34]]) + ] + l_edges = [ np.array([[0, 1]]) #type 0 node 0 to type 0 node 0 + , np.array([[0, 1]]) + , None + , None + ] + l_edge_f = [ np.array([[.111]]) + , np.array([[.221, .222]]) + , None + , None + ] + + x = (l_node_f, l_edges, l_edge_f) + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = np.hstack([ np.array([0, 1]), + np.array([0, 1, 2]) + ]) + #print y + g.initialize(x, y) + jf = g.joint_feature(x,y) + #print "joint_feature = \n", `jf` + #print + assert_array_equal(jf, jf) + assert_array_almost_equal(jf + , np.array( + [ 1. , 1., 1. , 2., 2., 2. + , 0.11 , 0.12 , 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 , 0.33 , 0.34 + + , 0. , 0.111, 0. , 0. , 0. , 0.221, + 0. , 0. , 0. , 0. , 0. , 0.222, 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. + ])) + + +def get_simple_graph_structure(): + g = NodeTypeEdgeFeatureGraphCRF( + 1 #how many node type? + , [4] #how many labels per node type? + , [3] #how many features per node type? + , np.array([[3]]) #how many features per node type X node type? + ) + return g + +def get_simple_graph(): + node_f = [ np.array([[1,1,1], + [2,2,2]]) + ] + edges = [ np.array([[0,1]]) + ] #an edge from 0 to 1 + edge_f = [ np.array([[3,3,3]]) + ] + return (node_f, edges, edge_f) + +def get_simple_graph2(): + node_f = [ np.array([ [1,1,1] + , [2,2,2]]) ] + edges = [ np.array( [[0,1], #an edge from 0 to 1 + [0,0] #an edge from 0 to 0 + ]) ] + edge_f = [ np.array([ + [3,3,3], + [4,4,4] + ]) ] + return (node_f, edges, edge_f) + +def test_flatten_unflattenY(): + + g, (node_f, edges, edge_f) = get_simple_graph_structure(), get_simple_graph() + y = np.array([1,2]) + l_nf = [ np.zeros((2,3)) ] #list of node feature , per type + X = (l_nf, None, None) #we give no edge + y_ref = [ np.array([1,2]) ] + assert all( [ (y_typ1 == y_typ2).all() for y_typ1, y_typ2 in zip(g.unflattenY(X, y), y_ref) ]) + + assert (y == g.flattenY(g.unflattenY(X, y))).all() + + #============================================ + g, x, y = more_complex_graph() + + Y = [ np.array([0, 0]) + , np.array([0, 0, 0]) #we start again at zero on 2nd type + ] + + y = np.hstack([ np.array([0, 0]) + , 2+np.array([0, 0, 0]) + ]) + l_nf = [ np.zeros( (2,3) ), np.zeros( (3, 4) )] #2 node with 3 features, 3 node with 4 features + X = (l_nf, None, None) #we give no edge + assert (g.flattenY(Y) == y).all() + #print g.unflattenY(X, y) + assert all( [ (y_typ1 == y_typ2).all() for y_typ1, y_typ2 in zip(g.unflattenY(X, y), Y) ]) + + l_nf = [ np.zeros( (1,3) ), np.zeros( (3, 4) )] #2 node with 3 features, 3 node with 4 features + X = (l_nf, None, None) #we give no edge + assert_raises(ValueError, g.unflattenY, X, y) + +def test_joint_feature(): + + #print "---SIMPLE---------------------------------------------------------------------" + g, (node_f, edges, edge_f) = get_simple_graph_structure(), get_simple_graph() + + x = (node_f, edges, edge_f) + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = np.array([1,2]) + +# y = np.array([1,0]) + #print y + g.initialize(x, y) + jf = g.joint_feature(x,y) + #print "joint_feature = \n", `jf` + #print + assert_array_equal(g.joint_feature(x,y) + , np.array([ 0., 0., 0., 1., 1., 1., 2., 2., 2., 0., 0., 0. + , 0., + 0., 0., 0., 0., 0., 3., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0., 3., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 3., 0., + 0., 0., 0., 0., 0., 0., 0., 0.]) + ) + + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = np.array([0,0]) + #print y + g.initialize(x, y) + jf = g.joint_feature(x,y) + #print "joint_feature = \n", `jf` + #print + assert_array_equal(g.joint_feature(x,y) + , np.array([ 3., 3., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 3., + 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 3., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0.]) + ) + + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = np.array([0,1]) + node_f = [ np.array([[1.1,1.2,1.3], [2.1,2.2,2.3]]) ] + edge_f = [ np.array([[3.1,3.2,3.3]]) ] + x = (node_f, edges, edge_f) + g.initialize(x, y) + jf = g.joint_feature(x,y) + #print "joint_feature = \n", `jf` + + assert_array_equal(g.joint_feature(x,y) + , np.array([ 1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 3.1, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 3.2, 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 3.3, 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. ]) + ) + #print "---SIMPLE + 2nd EDGE--------------------------------------------------------" + node_f, edges, edge_f = get_simple_graph2() + + x = (node_f, edges, edge_f) + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = np.array([1,2]) + #print y + g.initialize(x, y) + jf = g.joint_feature(x,y) + #print "joint_feature = \n", `jf` + #print + assert_array_equal(jf + , np.array([ 0., 0., 0., 1., 1., 1., 2., 2., 2., 0., 0., 0., 0., + 0., 0., 0., 0., 4., 3., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 4., 3., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 4., 3., 0., + 0., 0., 0., 0., 0., 0., 0., 0.]) + ) + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = np.array([0,0]) + #print y + g.initialize(x, y) + #print "joint_feature = \n", `g.joint_feature(x,y)` + #print + assert_array_equal(g.joint_feature(x,y) + , np.array([ 3., 3., 3., 0., 0., 0., 0., 0., 0., 0., 0., 0., 7., + 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 7., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 7., 0., 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0.]) + ) + +def more_complex_graph(): + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3] #how many labels per node type? + , [3, 4] #how many features per node type? + , np.array([ [1, 2] + , [2, 3]]) #how many features per node type X node type? + ) + +# nodes = np.array( [[0,0], [0,1], [1, 0], [1, 1], [1, 2]] ) + node_f = [ np.array([ [1,1,1], [2,2,2] ]) + , np.array([ [.11, .12, .13, .14], [.21, .22, .23, .24], [.31, .32, .33, .34]]) + ] + edges = [ np.array( [ [0,1] #an edge from 0 to 1 + ]) + , np.array( [ + [0,0] #an edge from typ0:0 to typ1:0 + ]) + , None + , None + ] + edge_f = [ np.array([[.111]]) + , np.array([[.221, .222]]) + , None + , None + ] + + x = (node_f, edges, edge_f) + y = np.hstack([ np.array([0, 0]) + , 2+np.array([0, 0, 0]) + ]) + return g, x, y + +def test_joint_feature2(): + + # ------------------------------------------------------------------------------------------- + #print "---MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" + g, x, y = more_complex_graph() + #print y + + + g.initialize(x, y) + jf = g.joint_feature(x,y) + #print "joint_feature = \n", `jf` + #print + assert_array_equal(jf, jf) + assert_array_almost_equal(jf + , np.array([ 3. , 3. , 3. , 0. , 0. , 0. , 0.63 , 0.66 , + 0.69 , 0.72 , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0.111, 0. , 0. , 0. , 0.221, 0. , + 0. , 0. , 0. , 0. , 0.222, 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ])) + + #print "---MORE COMPLEX GRAPH :) -- BIS -------------------------------------------------------------------" + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3] #how many labels per node type? + , [3, 4] #how many features per node type? + , np.array([ [1, 2] + , [2, 3]]) #how many features per node type X node type? + ) + + node_f = [ np.array([ [1,1,1], [2,2,2] ]) + , np.array([ [.11, .12, .13, .14], [.21, .22, .23, .24], [.31, .32, .33, .34]]) + ] + edges = [ np.array( [ [0,1]] ), #an edge from 0 to 1 + np.array( [ [0,2]] ) #an edge from 0 to 2 + , None, None + ] + edge_f = [ np.array([[.111]]) + , np.array([[.221, .222]]) + , None + , None + ] + + x = ( node_f, edges, edge_f) + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = np.hstack([np.array([0, 1]), + 2+np.array([0, 1, 2])]) + #print y + g.initialize(x, y) + jf = g.joint_feature(x,y) + #print "joint_feature = \n", `jf` + #print + assert_array_equal(jf, jf) + assert_array_almost_equal(jf + , np.array([ 1. , 1. , 1. , 2. , 2. , 2. , 0.11 , 0.12 , + 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 , + 0.33 , 0.34 , 0. , 0.111, 0. , 0. , 0. , 0. , + 0.221, 0. , 0. , 0. , 0. , 0. , 0.222, 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ])) + + #print "MORE COMPLEX GRAPH :) -- BIS OK" + #print "--- REORDERED MORE COMPLEX GRAPH :) ---------------------------------------------------------------------" + node_f = [ np.array([ [2,2,2], [1,1,1] ]) + , np.array([ [.31, .32, .33, .34], [.11, .12, .13, .14], [.21, .22, .23, .24]]) + ] + edges = [ np.array( [ [1, 0]] ), + np.array( [ [1,0]] ) #an edge from 0 to 2 + , None, None + ] + edge_f = [ np.array([[.111]]) + , np.array([[.221, .222]]) + , None + , None + ] + + x = ( node_f, edges, edge_f) + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = np.hstack([np.array([1, 0]), + 2+np.array([2, 0, 1])]) + #print y + g.initialize(x, y) + jf = g.joint_feature(x,y) + #print "joint_feature = \n", `jf` + #print + assert_array_equal(jf, jf) + assert_array_almost_equal(jf + , np.array([ 1. , 1. , 1. , 2. , 2. , 2. , 0.11 , 0.12 , + 0.13 , 0.14 , 0.21 , 0.22 , 0.23 , 0.24 , 0.31 , 0.32 , + 0.33 , 0.34 , 0. , 0.111, 0. , 0. , 0. , 0. , + 0.221, 0. , 0. , 0. , 0. , 0. , 0.222, 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , + 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ])) + +def test_joint_feature3(): + + # ------------------------------------------------------------------------------------------- + #print "---MORE COMPLEX GRAPH AGAIN :) ---------------------------------------------------------------------" + g = NodeTypeEdgeFeatureGraphCRF( + 2 #how many node type? + , [2, 3] #how many labels per node type? + , [3, 4] #how many features per node type? + , np.array([ [0, 2] + , [2, 3]]) #how many features per node type X node type? + ) + +# nodes = np.array( [[0,0], [0,1], [1, 0], [1, 1], [1, 2]] ) + node_f = [ np.array([ [1,1,1], [2,2,2] ]) + , np.array([ [.11, .12, .13, .14], [.21, .22, .23, .24], [.31, .32, .33, .34]]) + ] + edges = [ None + , np.array( [ + [0,1] #an edge from typ0:0 to typ1:1 + ]) + , None + , np.array( [ + [0,1], #an edge from typ0:0 to typ1:1 + [1,2] #an edge from typ1:1 to typ1:2 + ]) + ] + edge_f = [ None + , np.array([[.221, .222]]) + , None + , np.array([[.01, .02, .03 ], + [.001, .002, .003]]) + ] + + x = (node_f, edges, edge_f) + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = np.hstack([ np.array([0, 0]) + , 2+np.array([0, 0, 0]) + ]) + #print y + g.initialize(x, y) + #print g.size_unaries + #print g.size_pairwise + jf = g.joint_feature(x,y) + #print "joint_feature = \n", `jf` + #print + assert_array_equal(jf, jf) + assert_array_almost_equal(jf + , np.array([ 3. , 3. , 3. , 0. , 0. , 0. , + 0.63 , 0.66 , 0.69 , 0.72 , 0. , 0., 0., 0. , 0., 0., 0. , 0., + #edges 0 to 0 2x2 states + #typ0 typ0 EMPTY + #typ0 typ1 + .221, 0., 0., 0., 0., 0., + .222, 0., 0., 0., 0., 0., + #typ1 typ0 + 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., + #typ1 typ1 + 0.011, 0., 0., 0., 0., 0., 0., 0., 0., + 0.022, 0., 0., 0., 0., 0., 0., 0., 0., + 0.033, 0., 0., 0., 0., 0., 0., 0., 0. + ]) + ) + + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = np.hstack([ np.array([0, 1]) + , 2+np.array([1, 1, 0]) + ]) + #print y + g.initialize(x, y) + jf = g.joint_feature(x,y) + #print "joint_feature = \n", `jf` + #print + assert_array_equal(jf, jf) + assert_array_almost_equal(jf + , np.array([ 1. , 1. , 1. , 2. , 2. , 2. , + .31, .32, .33, .34 , .32, .34, .36, .38 , 0., 0., 0. , 0., + #edges 0 to 0 2x2 states + #typ0 typ0 EMPTY + #typ0 typ1 + 0., .221, 0., 0., 0., 0., + 0., .222, 0., 0., 0., 0., + #typ1 typ0 + 0., 0., 0., 0., 0., 0., + 0., 0., 0., 0., 0., 0., + #typ1 typ1 + 0., 0., 0., 0.001, 0.01, 0., 0., 0., 0., + 0., 0., 0., 0.002, 0.02, 0., 0., 0., 0., + 0., 0., 0., 0.003, 0.03, 0., 0., 0., 0. + ]) + ) + + w = np.array([ 1,1,1, 2,2,2, 10,10,10,10, 20,20,20,20, 30,30,30,30 ] + +[1.0]*51, dtype=np.float64 + ) + #print `w` + ret_u = g._get_unary_potentials(x, w) + #print `ret_u` + assert len(ret_u) == 2 + assert_array_almost_equal(ret_u[0], np.array([ #n_nodes x n_states + [3, 6], + [6, 12]])) + + assert_array_almost_equal(ret_u[1], np.array([ #n_nodes x n_states + [5, 10, 15], + [9, 18, 27], + [13, 26, 39]])) + + assert len(w) == g.size_joint_feature + ret_pw = g._get_pairwise_potentials(x, w) + # for _pw in ret_pw: + # print "_pw ", `_pw` + pw00, pw01, pw10, pw11 = ret_pw + assert len(pw00) == 0 + assert_array_almost_equal(pw01,np.array([ #n_edges, n_states, n_states + [[0.443, 0.443, 0.443], + [0.443, 0.443, 0.443]] + ])) + assert len(pw10) == 0 + + assert_array_almost_equal(pw11,np.array([ #n_edges, n_states, n_states + [[0.06 , 0.06 , 0.06], + [0.06 , 0.06 , 0.06], + [0.06 , 0.06 , 0.06]] + , + [[0.006, 0.006, 0.006], + [0.006, 0.006, 0.006], + [0.006, 0.006, 0.006]] + ])) + + + +def test_unary_potentials(): + #print "---SIMPLE---------------------------------------------------------------------" + #g, (node_f, edges, edge_f) = get_simple_graph_structure(), get_simple_graph() + + g = NodeTypeEdgeFeatureGraphCRF( + 1 #how many node type? + , [4] #how many labels per node type? + , [3] #how many features per node type? + , np.array([[3]]) #how many features per node type X node type? + ) + node_f = [ np.array([[1,1,1], + [2,2,2]]) + ] + edges = [ np.array([[0,1]]) + ] #an edge from 0 to 1 + edge_f = [ np.array([[3,3,3]]) + ] + x = (node_f, edges, edge_f) + #print "- - - - - - - - - - - - - - - - - - - - - - - - - - - " + y = np.hstack([ np.array([1,2])]) +# y = np.array([1,0]) + #print y + g.initialize(x, y) + + gref = EdgeFeatureGraphCRF(4,3,3) + xref = (node_f[0], edges[0], edge_f[0]) + wref = np.arange(gref.size_joint_feature) + potref = gref._get_unary_potentials(xref, wref) + #print `potref` + + w = np.arange(g.size_joint_feature) + pot = g._get_unary_potentials(x, w) + #print `pot` + assert_array_equal(pot, [potref]) + + pwpotref = gref._get_pairwise_potentials(xref, wref) + #print `pwpotref` + pwpot = g._get_pairwise_potentials(x, w) + #print `pwpot` + assert_array_equal(pwpot, [pwpotref]) + +# def test_inference_util(): +# g = NodeTypeEdgeFeatureGraphCRF( +# 3 #how many node type? +# , [2, 3, 1] #how many labels per node type? +# , [3, 4, 1] #how many features per node type? +# , np.array([ [1, 2, 2] +# , [2, 3, 2] +# , [2, 2, 1]]) #how many features per node type X node type? +# ) +# node_f = [ np.array([ [2,2,2], [1,1,1] ]) +# , np.array([ [.31, .32, .33, .34], [.11, .12, .13, .14], [.21, .22, .23, .24]]) +# , np.array([ [77], [88], [99]]) +# ] +# edges = [ np.array( [ [1, 0]] ), +# np.array( [ [1,0]] ) #an edge from 0 to 2 +# , None +# +# , None +# , None +# , None +# +# , np.array( [[1,1]] ) +# , None +# , None ] +# +# x = ( node_f, edges, None) +# +# reindexed_exdges = g._index_all_edges(x) +# #print `reindexed_exdges` +# assert_array_equal(reindexed_exdges, +# np.array( [[1,0], +# [1,2], +# [6,1]])) +# + +# def report_model_config(crf): +# print crf.n_states +# print crf.n_features +# print crf.n_edge_features + +def inference_data(): + """ + Testing with a single type of nodes. Must do as well as EdgeFeatureGraphCRF + """ + # Test inference with different weights in different directions + + X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1) + x, y = X[0], Y[0] + n_states = x.shape[-1] + + edge_list = make_grid_edges(x, 4, return_lists=True) + edges = np.vstack(edge_list) + + pw_horz = -1 * np.eye(n_states) + xx, yy = np.indices(pw_horz.shape) + # linear ordering constraint horizontally + pw_horz[xx > yy] = 1 + + # high cost for unequal labels vertically + pw_vert = -1 * np.eye(n_states) + pw_vert[xx != yy] = 1 + pw_vert *= 10 + + # generate edge weights + edge_weights_horizontal = np.repeat(pw_horz[np.newaxis, :, :], + edge_list[0].shape[0], axis=0) + edge_weights_vertical = np.repeat(pw_vert[np.newaxis, :, :], + edge_list[1].shape[0], axis=0) + edge_weights = np.vstack([edge_weights_horizontal, edge_weights_vertical]) + + # do inference + res = lp_general_graph(-x.reshape(-1, n_states), edges, edge_weights) + + edge_features = edge_list_to_features(edge_list) + x = ([x.reshape(-1, n_states)], [edges], [edge_features]) + y = y.ravel() + return x, y, pw_horz, pw_vert, res, n_states + +def test_inference_ad3plus(): + + x, y, pw_horz, pw_vert, res, n_states = inference_data() + # same inference through CRF inferface + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]] + , inference_method="ad3+") + crf.initialize(x, y) + #crf.initialize([x], [y]) + w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) + y_pred = crf.inference(x, w, relaxed=True) + if isinstance(y_pred, tuple): + # ad3 produces an integer result if it found the exact solution + #np.set_printoptions(precision=2, threshold=9999) + assert_array_almost_equal(res[0], y_pred[0][0].reshape(-1, n_states), 5) + assert_array_almost_equal(res[1], y_pred[1][0], 5) + assert_array_equal(y, np.argmax(y_pred[0][0], axis=-1), 5) + + # again, this time discrete predictions only + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]] + , inference_method="ad3+") + #crf.initialize([x], [y]) + w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) + crf.initialize(x) + y_pred = crf.inference(x, w, relaxed=False) + assert_array_equal(y, y_pred) + +def test_inference_ad3(): + + x, y, pw_horz, pw_vert, res, n_states = inference_data() + # same inference through CRF inferface + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]] + , inference_method="ad3") + crf.initialize(x, y) + #crf.initialize([x], [y]) + w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) + y_pred = crf.inference(x, w, relaxed=True) + if isinstance(y_pred, tuple): + # ad3 produces an integer result if it found the exact solution + #np.set_printoptions(precision=2, threshold=9999) + assert_array_almost_equal(res[0], y_pred[0][0].reshape(-1, n_states), 5) + assert_array_almost_equal(res[1], y_pred[1][0], 5) + assert_array_equal(y, np.argmax(y_pred[0][0], axis=-1), 5) + + # again, this time discrete predictions only + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]] + , inference_method="ad3") + #crf.initialize([x], [y]) + w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) + crf.initialize(x) + y_pred = crf.inference(x, w, relaxed=False) + assert_array_equal(y, y_pred) + +def test_joint_feature_discrete(): + """ + Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF + """ + X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1) + x, y = X[0], Y[0] + edge_list = make_grid_edges(x, 4, return_lists=True) + edges = np.vstack(edge_list) + edge_features = edge_list_to_features(edge_list) + x = ([x.reshape(-1, 3)], [edges], [edge_features]) + y_flat = y.ravel() + #for inference_method in get_installed(["lp", "ad3", "qpbo"]): + if True: + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) + joint_feature_y = crf.joint_feature(x, y_flat) + assert_equal(joint_feature_y.shape, (crf.size_joint_feature,)) + # first horizontal, then vertical + # we trust the unaries ;) + n_states = crf.l_n_states[0] + n_features = crf.l_n_features[0] + pw_joint_feature_horz, pw_joint_feature_vert = joint_feature_y[n_states * + n_features:].reshape( + 2, n_states, n_states) + assert_array_equal(pw_joint_feature_vert, np.diag([9 * 4, 9 * 4, 9 * 4])) + vert_joint_feature = np.diag([10 * 3, 10 * 3, 10 * 3]) + vert_joint_feature[0, 1] = 10 + vert_joint_feature[1, 2] = 10 + assert_array_equal(pw_joint_feature_horz, vert_joint_feature) + +def test_joint_feature_continuous(): + """ + Testing with a single type of nodes. Must de aw well as EdgeFeatureGraphCRF + """ + # FIXME + # first make perfect prediction, including pairwise part + X, Y = generate_blocks_multinomial(noise=2, n_samples=1, seed=1) + x, y = X[0], Y[0] + n_states = x.shape[-1] + edge_list = make_grid_edges(x, 4, return_lists=True) + edges = np.vstack(edge_list) + edge_features = edge_list_to_features(edge_list) + #x = (x.reshape(-1, 3), edges, edge_features) + x = ([x.reshape(-1, 3)], [edges], [edge_features]) + y = y.ravel() + + pw_horz = -1 * np.eye(n_states) + xx, yy = np.indices(pw_horz.shape) + # linear ordering constraint horizontally + pw_horz[xx > yy] = 1 + + # high cost for unequal labels vertically + pw_vert = -1 * np.eye(n_states) + pw_vert[xx != yy] = 1 + pw_vert *= 10 + + # create crf, assemble weight, make prediction +# for inference_method in get_installed(["lp", "ad3"]): +# crf = EdgeFeatureGraphCRF(inference_method=inference_method) + if True: + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) + + w = np.hstack([np.eye(3).ravel(), -pw_horz.ravel(), -pw_vert.ravel()]) + #crf.initialize([x], [y]) + #report_model_config(crf) + crf.initialize(x, y) + + y_pred = crf.inference(x, w, relaxed=True) + + # compute joint_feature for prediction + joint_feature_y = crf.joint_feature(x, y_pred) + assert_equal(joint_feature_y.shape, (crf.size_joint_feature,)) + # FIXME + # first horizontal, then vertical + # we trust the unaries ;) + #pw_joint_feature_horz, pw_joint_feature_vert = joint_feature_y[crf.n_states * + #crf.n_features:].reshape(2, + #crf.n_states, + #crf.n_states) + +def test_energy_continuous(): + # make sure that energy as computed by ssvm is the same as by lp + np.random.seed(0) + #for inference_method in get_installed(["lp", "ad3"]): + if True: + found_fractional = False + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) + + while not found_fractional: + x = np.random.normal(size=(7, 8, 3)) + edge_list = make_grid_edges(x, 4, return_lists=True) + edges = np.vstack(edge_list) + edge_features = edge_list_to_features(edge_list) + x = ([x.reshape(-1, 3)], [edges], [edge_features]) + + unary_params = np.random.normal(size=(3, 3)) + pw1 = np.random.normal(size=(3, 3)) + pw2 = np.random.normal(size=(3, 3)) + w = np.hstack([unary_params.ravel(), pw1.ravel(), pw2.ravel()]) + crf.initialize(x) + res, energy = crf.inference(x, w, relaxed=True, return_energy=True) + found_fractional = np.any(np.max(res[0], axis=-1) != 1) + joint_feature = crf.joint_feature(x, res) + energy_svm = np.dot(joint_feature, w) + + assert_almost_equal(energy, -energy_svm) + +def test_energy_discrete(): +# for inference_method in get_installed(["qpbo", "ad3"]): +# crf = EdgeFeatureGraphCRF(n_states=3, +# inference_method=inference_method, +# n_edge_features=2, n_features=3) + crf = NodeTypeEdgeFeatureGraphCRF(1, [3], [3], [[2]]) + + for i in range(10): + x = np.random.normal(size=(7, 8, 3)) + edge_list = make_grid_edges(x, 4, return_lists=True) + edges = np.vstack(edge_list) + edge_features = edge_list_to_features(edge_list) + x = ([x.reshape(-1, 3)], [edges], [edge_features]) + + unary_params = np.random.normal(size=(3, 3)) + pw1 = np.random.normal(size=(3, 3)) + pw2 = np.random.normal(size=(3, 3)) + w = np.hstack([unary_params.ravel(), pw1.ravel(), pw2.ravel()]) + crf.initialize(x) + y_hat = crf.inference(x, w, relaxed=False) + #flat_edges = crf._index_all_edges(x) + energy = compute_energy(crf._get_unary_potentials(x, w)[0], + crf._get_pairwise_potentials(x, w)[0], edges, #CAUTION: pass the flatened edges!! + y_hat) + + joint_feature = crf.joint_feature(x, y_hat) + energy_svm = np.dot(joint_feature, w) + + assert_almost_equal(energy, energy_svm) + + +if __name__ == "__main__": + np.set_printoptions(precision=3, linewidth=9999) + + if 0: + debug_joint_feature() + if 1: + test_flatten_unflattenY() + + if 1: + test_joint_feature() + if 1: + test_joint_feature2() + if 1: + test_joint_feature3() + + if 1: test_unary_potentials() +# if 1: test_inference_util() + if 1: test_inference_ad3() + if 1: test_inference_ad3plus() + if 1: test_joint_feature_discrete() + if 1: test_joint_feature_continuous() + if 1: test_energy_continuous() + if 1: test_energy_discrete() + + #print "OK" From 863ad155d3bae35f6f6c827b8654e3dadaff9483 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Thu, 26 Jul 2018 11:33:12 +0200 Subject: [PATCH 148/155] Python 3, logical constraint in predict, new tests, extended snake example --- .travis.yml | 11 +- CHANGELOG | 7 + README.md | 2 + READ_Contribution.md | 123 +++++++++++ continuous_integration/install.sh | 47 +++- continuous_integration/test_script.sh | 3 + examples/plot_snakes.py | 33 +-- pystruct/__init__.py | 2 +- pystruct/inference/__init__.py | 6 +- pystruct/inference/inference_methods.py | 225 +++++++++++++++++--- pystruct/learners/one_slack_ssvm.py | 38 +++- pystruct/learners/ssvm.py | 22 +- pystruct/models/__init__.py | 5 +- pystruct/models/base.py | 11 +- pystruct/models/crf.py | 32 ++- pystruct/models/latent_graph_crf.py | 2 +- pystruct/tests/test_libraries.py | 11 +- pystruct/tests/test_models/test_grid_crf.py | 4 + pystruct/utils/inference.py | 7 +- requirements.txt | 3 +- setup.py | 5 +- 21 files changed, 511 insertions(+), 88 deletions(-) create mode 100644 READ_Contribution.md diff --git a/.travis.yml b/.travis.yml index 02fd194a..3673eff9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -26,10 +26,13 @@ env: ## ubuntu without opengm - DISTRIB="ubuntu" PYTHON_VERSION="2.7" OPENGM="false" ## This environment tests the newest supported anaconda env - - DISTRIB="conda" PYTHON_VERSION="2.7" - NUMPY_VERSION="1.11" SCIPY_VERSION="0.17.0" - - DISTRIB="conda" PYTHON_VERSION="3.6" OPENGM="false" - NUMPY_VERSION="1.14.2" SCIPY_VERSION="1.0.0" + - DISTRIB="conda" PYTHON_VERSION="2.7" OPENGM="false" + NUMPY_VERSION="1.13.3" SCIPY_VERSION="0.19.1" + # python3.5 only because of cvxopt? + - DISTRIB="conda3" PYTHON_VERSION="3.5" OPENGM="false" + NUMPY_VERSION="1.13" SCIPY_VERSION="1.0" + - DISTRIB="conda3" PYTHON_VERSION="3.6" OPENGM="false" + NUMPY_VERSION="1.14" SCIPY_VERSION="1.1" install: source continuous_integration/install.sh script: bash continuous_integration/test_script.sh after_success: diff --git a/CHANGELOG b/CHANGELOG index 2f68e86e..1440dcf0 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,9 @@ +0.3.1 +===== +- Added new model NodeTypeEdgeFeatureGraphCRF +- all tests are passing, CIok +- Python3 compatibility + 0.3 === - Removed libdai bindings that were very experimental. @@ -15,3 +21,4 @@ - Speed improvements in loss-augmented inference. - Renamed psi to joint_feature, as the joint feature function is sometimes also called phi, with psi referring to the energy. - Removed the GLPK dependency: now cvxopt is used to solve linear programs. + diff --git a/README.md b/README.md index c7216a73..49471dea 100644 --- a/README.md +++ b/README.md @@ -31,3 +31,5 @@ You can contact the authors either via the [mailing list](https://groups.google. or on [github](https://github.com/pystruct/pystruct). Currently the project is mostly maintained by Andreas Mueller, but contributions are very welcome. + +Jean-Luc Meunier (Naver Labs Europe) contributed a new model and did some maintenance, in the course of the EU READ project. See [READ_Contribution.md](https://github.com/pystruct/pystruct/blob/master/READ_Contribution.md) diff --git a/READ_Contribution.md b/READ_Contribution.md new file mode 100644 index 00000000..c7a4f537 --- /dev/null +++ b/READ_Contribution.md @@ -0,0 +1,123 @@ +# Contribution by EU READ Project +During the course of the EU READ project, Naver Labs Europe made two contributions to the pystruct and AD3 projects: + - **supporting nodes of different nature in CRF graphs** + - **supporting hard-logic constraints when predicting** + +In practice: + * a new CRF model is proposed, __*NodeTypeEdgeFeatureGraphCRF*__ + * the __*predict*__ method accepts now an optional constraint parameter + + More details are given in next sections. + + You can contact the author at jean-luc.meunier@naverlabs.com + + +## Credit +Developed for the EU project READ. The READ project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. + +## Tests +To test your install, run the test of the new CRF model: +> python pystruct/tests/test_models/test_node_type_edge_feature_graph_crf.py + +(You should see a "OK" displayed at the end of the script execution.) + +## Example +Building on the [Snakes](https://pystruct.github.io/auto_examples/plot_snakes.html#sphx-glr-auto-examples-plot-snakes-py) example, there is now a new example called "HiddenSnakes". (Code in examples/plot_hidden_short_snakes_typed.py ) + +The idea is that some picture do not contain any snake despite 10 pixels have a Snake body colour. Why? Because they do not form a valid 10-long snake, as 1 pixel has a wrong colour destroying the continuity of the snake. + +The original task remains but is more difficult: some non-blue pixels are now labelled 'background'. An additional task consists in labeling the picture as Snake or NoSnake. + +This double task is solved by the use of an additional type of node that represents the picture itself, with 7 simplistic features. There are additional edges, from each pixel to the picture node. That's all. And it improves a lot from the results of the *EdgeFeatureGraphCRF*-based model. + +In addition, we injected some more domain knowledge to illustrate the use of the hard logic constraints. In this case we enforce *at most one pixel of label L per picture, for L in [1, 10]*. This gives an extra accuracy bonus. + +## Prediction with Hard-Logic Constraints + +You can now pass a __list of logical constraints__ to the predict method, with a *constraints=* named parameter. + + Each constraint is tuple like *( operator, nodes, labels, negated )* + where: + - *operator* is one of 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - *nodes* is the list of the index of each node involved in this constraint + - *labels* is the list of node label. If the labels are the same for all nodes, you can pass it directly as a scalar value. + - *negated* is a list of boolean indicating if the corresponding argument must be negated. Again, if all values are the same, pass a single boolean value instead of a list. + +The operators whose name ends with 'OUT' impose that the operator applied on the all-but-last arguments yields the truth value of the last one. +>For instance XOROUT(a,b,c) <=> XOR(a,b) = c + +When used jointly with the new *NodeTypeEdgeFeatureGraphCRF* model, the structure of the constraints list slightly differs. See in next section. + + +## CRF Graph with Nodes of Different Nature +Pystruct CRF graphs assumes that the nodes of the graph all have the same nature. In consequence, all nodes share the same weights and the same set of possible labels. Similarly, all edges have the same nature and share the same edge weights. +This was a limitation with regards to our needs (for a Document Understanding task). So we propose a new CRF model called *NodeTypeEdgeFeatureGraphCRF*. + +*NodeTypeEdgeFeatureGraphCRF* supports multiple node of multiple nature, which we call **node types**. Each type has its own weights and own set of possible labels. Similarly, edges have different nature depending on the type of their sources and target-nodes. In a graph with N types, there are N^2 types of edges. + +*NodeTypeEdgeFeatureGraphCRF* generalizes *EdgeFeatureGraphCRF*, so edges have features. NOTE: I think that you can mimics the absence opf feature on edges (as in *GraphCRF* model) by specifying one feature per edge, whose value is 1 for all edges. + +**This extension has an impact on:** + * the constructor + * the structure of the label weights, if not uniform + * the structure of the Xs + * the values in Ys + * the structure of the optional constraint list at prediction + +### Class Constructor +You need now to define the number of node types and the number of features per type (of node, and of edge) when instantiating *NodeTypeEdgeFeatureGraphCRF*. + + def __init__(self + , n_types #how many node type? + , l_n_states #how many labels per node type? + , l_n_features #how many features per node type? + , a_n_edge_features #how many features per edge type? (array-like) shape=(n_type, n_type) -> n_feature_per_type_pair + , inference_method="ad3" + , l_class_weight=None): #class_weight per node type or None or None + + +### Xs and Ys +In single type CRF, like *EdgeFeatureGraphCRF*, an instance *X* is represented as a tuple + + (*node_features*, *edges*, *edge_features*) representing the graph. + +* *node_feature*s is of shape (*n_node*, *n_features*) +* *edges* is an array of shape (*n_edges*, 2) +* *edge_features* is of shape (*n_edges*, *n_edge_features*) + + Labels y are given as array of shape (*n_nodes*,) + +In multiple type graphs, with *_n_types* types, an instance *X* is represented as a tuple + + (*l_node_features*, *l_edges*, *l_edge_features*) representing the graph. +* *l_node_feature*s is a list of length *n_types* containing arrays of shape (*n_typ_node*, *n_typ_features*), where *n_typ_node* is the number of nodes of that type, while *n_typ_features* is the number of features for this type of nodes. +* *l_edges* is a list of length *n_types*^2 . Each of its elements contains an array of shape (*n_typ_edge, 2) defining the edges from nodes of type *i* to nodes of type *j*, with *i* and *j* in [0, *n_types*-1], *j* being the secondary index (inner loop). The index of the nodes in each type starts at 0. +* *l_edge_features* is a list of length *n_types*^2. It contains the features of the edges for each pair of types, in same order as in previous parameter. Each item is an array of shape (*n_typ_edges*, *n_typ_edge_features*). if *n_typ_edge_features* is 0, then *n_typ_edges* should be 0 as well for all instances of graph! If you want an edge without features, set *n_typ_edge_features* to 1 and pass 1.0 as feature for all edges (of that type). + +Each *Y* remains a vector array. While the label could start at 0 for all types, we have chosen not to do so. (Essentially,to make clear that types do not blend into each other, which is clear when you show a confusion matrix). So the labels of the first type start at 0, while labels of next type starts right after the value of the last label of previous type. +*NodeTypeEdgeFeatureGraphCRF* provides 2 convenience methods: +* *flattenY*( [ [2,0,0], [3,3,4] ] ) --> [ 2,0,0, 5,5,7] (assuming type 0 has 3 labels) +* *unflattenY*(Xs, [ 2,0,0, 5,5,7] ) --> [ [2,0,0], [3,3,4] ] (you'll also need to pass the Xs) + +### Constraints on Multitype Graphs +As for the Xs and Ys, the constraint must be partitioned by type. + + The constraints must be a list of tuples like: + +Either + + ( *operator*, *l_nodes*, *l_labels*, *l_negated* ) + with operator being one 'XOR' 'ATMOSTONE' 'OR' + +Or + + ( *operator*, *l_nodes*, *l_labels*, *l_negated* , (*type*, *node*, *label*, *negated*)) + with operator being one 'XOROUT' 'OROUT' 'ANDOUT' 'IMPLY' + +- *l_nodes* is a list of nodes per type. Each item is a list of the index of the node of that type involved in this constraint +- *l_labels* is a list of labels per type. Each item is a list of the label of the involved node. If the labels are all the same for a type, you can pass it directly as a scalar value. +- *l_negate*d is a list of "negated" per type. Each item is a list of booleans indicating if the node must be negated. Again, if all values are the same for a type, pass a single boolean value instead of a list + +- the last (*type*, *nod*e, *label*, *negated*) allows to refer to the outcome of an 'OUT' operator. + + diff --git a/continuous_integration/install.sh b/continuous_integration/install.sh index 7a21e435..83b853b3 100644 --- a/continuous_integration/install.sh +++ b/continuous_integration/install.sh @@ -21,8 +21,10 @@ export PIP=pip if [[ "$OPENGM" == "true" ]]; then git clone https://github.com/opengm/opengm.git cd opengm - cmake . -DCMAKE_INSTALL_PREFIX=/home/travis/.local -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_EXAMPLES=FALSE -DBUILD_TESTING=FALSE - make -j2 --quiet + # old cmake . -DCMAKE_INSTALL_PREFIX=/home/travis/.local -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_EXAMPLES=FALSE -DBUILD_TESTING=FALSE + # old make -j2 --quiet + cmake . -DCMAKE_INSTALL_PREFIX=/home/travis/.local -DWITH_BOOST=TRUE -DWITH_HDF5=TRUE -DWITH_AD3=FALSE -DWITH_TRWS=FALSE -DWITH_QPBO=FALSE -DWITH_MRF=FALSE -DWITH_GCO=FALSE -DWITH_CONICBUNDLE=FALSE -DWITH_MAXFLOW=FALSE -DWITH_MAXFLOW_IBFS=FALSE -DBUILD_PYTHON_WRAPPER=TRUE -DBUILD_COMMANDLINE=FALSE -DCI=TRUE + make -j1 --quiet make install cd .. fi @@ -34,18 +36,40 @@ if [[ "$DISTRIB" == "conda" ]]; then # Use the miniconda installer for faster download / install of conda # itself - wget http://repo.continuum.io/miniconda/Miniconda-3.6.0-Linux-x86_64.sh \ + wget https://repo.continuum.io/miniconda/Miniconda2-4.3.31-Linux-x86_64.sh \ -O miniconda.sh - chmod +x miniconda.sh && ./miniconda.sh -b - export PATH=/home/travis/miniconda/bin:$PATH + chmod +x miniconda.sh && ./miniconda.sh -b -p $HOME/miniconda2 + export PATH=$HOME/miniconda2/bin:$PATH conda update --yes conda # Configure the conda environment and put it in the path using the # provided versions - conda create -n testenv --yes python=$PYTHON_VERSION pip nose cython scikit-learn cvxopt\ + conda create -n testenv --yes python=$PYTHON_VERSION pip nose cython\ + scikit-learn cvxopt pytest future \ numpy=$NUMPY_VERSION scipy=$SCIPY_VERSION + source activate testenv + +elif [[ "$DISTRIB" == "conda3" ]]; then + # Deactivate the travis-provided virtual environment and setup a + # conda-based environment instead + deactivate + + # Use the miniconda installer for faster download / install of conda + # itself + wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh \ + -O miniconda.sh + chmod +x miniconda.sh && ./miniconda.sh -b -p $HOME/miniconda3 + export PATH=$HOME/miniconda3/bin:$PATH + conda update --yes conda + + # Configure the conda environment and put it in the path using the + # provided versions + + conda create -n testenv --yes python=$PYTHON_VERSION pip nose cython\ + scikit-learn cvxopt pytest future \ + numpy=$NUMPY_VERSION scipy=$SCIPY_VERSION source activate testenv @@ -53,6 +77,7 @@ elif [[ "$DISTRIB" == "ubuntu" ]]; then # Use standard ubuntu packages in their default version # except for cython :-/ $PIP install --user cvxopt + $PIP install --user future # for AD3 fi if [[ "$COVERAGE" == "true" ]]; then @@ -63,7 +88,8 @@ python --version python -c "import numpy; print('numpy %s' % numpy.__version__)" python -c "import scipy; print('scipy %s' % scipy.__version__)" # install our favorite inference packages -$PIP install pyqpbo ad3 scikit-learn +# Need Transkribus/AD3 for now $PIP install pyqpbo ad3 scikit-learn +$PIP install pyqpbo scikit-learn # Build scikit-learn in the install.sh script to collapse the verbose # build output in the travis output when it succeeds. @@ -71,3 +97,10 @@ python --version python -c "import numpy; print('numpy %s' % numpy.__version__)" python -c "import scipy; print('scipy %s' % scipy.__version__)" python setup.py build_ext --inplace + +#get Transkribus/AD3 +git clone https://github.com/andre-martins/AD3 +pushd AD3 +python setup.py install +popd +python -c "import ad3; print(ad3.__version__)" diff --git a/continuous_integration/test_script.sh b/continuous_integration/test_script.sh index 2f7f3b7b..325c01e0 100644 --- a/continuous_integration/test_script.sh +++ b/continuous_integration/test_script.sh @@ -12,6 +12,9 @@ python --version python -c "import numpy; print('numpy %s' % numpy.__version__)" python -c "import scipy; print('scipy %s' % scipy.__version__)" python -c "import sklearn; print('sklearn %s' % sklearn.__version__)" +python -c "import ad3; print(ad3.__version__)" +python -c "import pystruct; print(pystruct.__version__)" + python -c "from pystruct.inference import get_installed; print('pystruct inference algorithms: %s' % get_installed())" diff --git a/examples/plot_snakes.py b/examples/plot_snakes.py index 60710a9f..f56f42d5 100644 --- a/examples/plot_snakes.py +++ b/examples/plot_snakes.py @@ -137,19 +137,20 @@ def prepare_data(X): % accuracy_score(np.hstack(Y_test_flat), np.hstack(Y_pred2))) print(confusion_matrix(np.hstack(Y_test_flat), np.hstack(Y_pred2))) - # plot stuff - fig, axes = plt.subplots(2, 2) - axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') - axes[0, 0].set_title('Input') - y = Y_test[0].astype(np.int) - bg = 2 * (y != 0) # enhance contrast - axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) - axes[0, 1].set_title("Ground Truth") - axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 0].set_title("Prediction w/o edge features") - axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) - axes[1, 1].set_title("Prediction with edge features") - for a in axes.ravel(): - a.set_xticks(()) - a.set_yticks(()) - plt.show() +# if True: +# # plot stuff +# fig, axes = plt.subplots(2, 2) +# axes[0, 0].imshow(snakes['X_test'][0], interpolation='nearest') +# axes[0, 0].set_title('Input') +# y = Y_test[0].astype(np.int) +# bg = 2 * (y != 0) # enhance contrast +# axes[0, 1].matshow(y + bg, cmap=plt.cm.Greys) +# axes[0, 1].set_title("Ground Truth") +# axes[1, 0].matshow(Y_pred[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) +# axes[1, 0].set_title("Prediction w/o edge features") +# axes[1, 1].matshow(Y_pred2[0].reshape(y.shape) + bg, cmap=plt.cm.Greys) +# axes[1, 1].set_title("Prediction with edge features") +# for a in axes.ravel(): +# a.set_xticks(()) +# a.set_yticks(()) +# plt.show() diff --git a/pystruct/__init__.py b/pystruct/__init__.py index fe404ae5..260c070a 100644 --- a/pystruct/__init__.py +++ b/pystruct/__init__.py @@ -1 +1 @@ -__version__ = "0.2.5" +__version__ = "0.3.1" diff --git a/pystruct/inference/__init__.py b/pystruct/inference/__init__.py index b8a9f1e4..041432ee 100644 --- a/pystruct/inference/__init__.py +++ b/pystruct/inference/__init__.py @@ -1,8 +1,10 @@ from .inference_methods import (inference_qpbo, inference_lp, inference_ad3, inference_ogm, - inference_dispatch, get_installed) + inference_dispatch, get_installed, + inference_ad3plus, InferenceException) from .common import compute_energy __all__ = ["inference_qpbo", "inference_lp", "inference_ad3", "inference_dispatch", "get_installed", "compute_energy", - "inference_ogm"] + "inference_ogm", + "inference_ad3plus", "InferenceException"] \ No newline at end of file diff --git a/pystruct/inference/inference_methods.py b/pystruct/inference/inference_methods.py index 8087ed20..1b85793c 100644 --- a/pystruct/inference/inference_methods.py +++ b/pystruct/inference/inference_methods.py @@ -4,10 +4,9 @@ from .maxprod import inference_max_product from .common import _validate_params - def get_installed(method_filter=None): if method_filter is None: - method_filter = ["max-product", 'ad3', 'qpbo', 'ogm', 'lp'] + method_filter = ["max-product", 'ad3', 'ad3+', 'qpbo', 'ogm', 'lp'] installed = [] unary = np.zeros((1, 1)) @@ -15,16 +14,31 @@ def get_installed(method_filter=None): edges = np.empty((0, 2), dtype=np.int) for method in method_filter: try: - inference_dispatch(unary, pw, edges, inference_method=method) + if method != 'ad3+': + inference_dispatch(unary, pw, edges, inference_method=method) + else: + inference_dispatch(unary, np.zeros((0,1,1)) + , np.zeros((0,2), dtype=np.int) + , inference_method=method) installed.append(method) except ImportError: pass return installed +class InferenceException(Exception): + """ + When inference status is fractional or unsolved, this exception can be + raised. + (If relaxed is not True and if an inference exception is requested by the + calling code) + The exception message is the solver status. + """ + pass def inference_dispatch(unary_potentials, pairwise_potentials, edges, inference_method, return_energy=False, **kwargs): - """Computes the maximizing assignment of a pairwise discrete energy function. + """ + Computes the maximizing assignment of a pairwise discrete energy function. Wrapper function to dispatch between inference method by string. @@ -33,9 +47,11 @@ def inference_dispatch(unary_potentials, pairwise_potentials, edges, unary_potentials : nd-array, shape (n_nodes, n_states) Unary potentials of energy function. - pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). Pairwise potentials of energy function. - If the first case, edge potentials are assumed to be the same for all edges. + If the first case, edge potentials are assumed to be the same for all + edges. In the second case, the sequence needs to correspond to the edges. edges : nd-array, shape (n_edges, 2) @@ -89,6 +105,9 @@ def inference_dispatch(unary_potentials, pairwise_potentials, edges, elif inference_method == "ad3": return inference_ad3(unary_potentials, pairwise_potentials, edges, return_energy=return_energy, **kwargs) + elif inference_method == "ad3+": + return inference_ad3plus(unary_potentials, pairwise_potentials, edges, + return_energy=return_energy, **kwargs) elif inference_method == "ogm": return inference_ogm(unary_potentials, pairwise_potentials, edges, return_energy=return_energy, **kwargs) @@ -113,9 +132,11 @@ def inference_ogm(unary_potentials, pairwise_potentials, edges, unary_potentials : nd-array, shape (n_nodes, n_states) Unary potentials of energy function. - pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). Pairwise potentials of energy function. - If the first case, edge potentials are assumed to be the same for all edges. + If the first case, edge potentials are assumed to be the same for all + edges. In the second case, the sequence needs to correspond to the edges. edges : nd-array, shape (n_edges, 2) @@ -228,9 +249,11 @@ def inference_qpbo(unary_potentials, pairwise_potentials, edges, **kwargs): unary_potentials : nd-array, shape (n_nodes, n_states) Unary potentials of energy function. - pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). Pairwise potentials of energy function. - If the first case, edge potentials are assumed to be the same for all edges. + If the first case, edge potentials are assumed to be the same for all + edges. In the second case, the sequence needs to correspond to the edges. edges : nd-array, shape (n_edges, 2) @@ -267,9 +290,11 @@ def inference_lp(unary_potentials, pairwise_potentials, edges, relaxed=False, unary_potentials : nd-array, shape (n_nodes, n_states) Unary potentials of energy function. - pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). Pairwise potentials of energy function. - If the first case, edge potentials are assumed to be the same for all edges. + If the first case, edge potentials are assumed to be the same for all + edges. In the second case, the sequence needs to correspond to the edges. edges : nd-array, shape (n_edges, 2) @@ -311,7 +336,8 @@ def inference_lp(unary_potentials, pairwise_potentials, edges, relaxed=False, def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, - verbose=0, return_energy=False, branch_and_bound=False): + verbose=0, return_energy=False, branch_and_bound=False, + inference_exception=None): """Inference with AD3 dual decomposition subgradient solver. Parameters @@ -319,9 +345,11 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, unary_potentials : nd-array, shape (n_nodes, n_states) Unary potentials of energy function. - pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). Pairwise potentials of energy function. - If the first case, edge potentials are assumed to be the same for all edges. + If the first case, edge potentials are assumed to be the same for all + edges. In the second case, the sequence needs to correspond to the edges. edges : nd-array, shape (n_edges, 2) @@ -350,30 +378,170 @@ def inference_ad3(unary_potentials, pairwise_potentials, edges, relaxed=False, labels : nd-array Approximate (usually) MAP variable assignment. If relaxed=False, this is a tuple of unary and edge 'marginals'. + + Code updated on Feb 2017 to deal with multiple node types, by JL Meunier + , for the EU READ project (grant agreement No 674943) + """ import ad3 - n_states, pairwise_potentials = \ - _validate_params(unary_potentials, pairwise_potentials, edges) - - unaries = unary_potentials.reshape(-1, n_states) - res = ad3.general_graph(unaries, edges, pairwise_potentials, verbose=verbose, - n_iterations=4000, exact=branch_and_bound) + bMultiType = isinstance(unary_potentials, list) + if bMultiType: + res = ad3.general_graph(unary_potentials, edges, pairwise_potentials + , verbose=verbose + , n_iterations=4000, exact=branch_and_bound) + else: + #usual code + n_states, pairwise_potentials = \ + _validate_params(unary_potentials, pairwise_potentials, edges) + unaries = unary_potentials.reshape(-1, n_states) + res = ad3.general_graph(unaries, edges, pairwise_potentials + , verbose=verbose, n_iterations=4000 + , exact=branch_and_bound) + unary_marginals, pairwise_marginals, energy, solver_status = res if verbose: - print(solver_status[0]) + print(solver_status) if solver_status in ["fractional", "unsolved"] and relaxed: - unary_marginals = unary_marginals.reshape(unary_potentials.shape) - y = (unary_marginals, pairwise_marginals) + if bMultiType: + y = (unary_marginals, pairwise_marginals) #those two are lists + else: + #usual code + unary_marginals = unary_marginals.reshape(unary_potentials.shape) + y = (unary_marginals, pairwise_marginals) + #print solver_status, pairwise_marginals else: - y = np.argmax(unary_marginals, axis=-1) + if bMultiType: + #we now get a list of unary marginals + if inference_exception and solver_status in ["fractional" + , "unsolved"]: + raise InferenceException(solver_status) + ly = list() + _cum_n_states = 0 + for unary_marg in unary_marginals: + ly.append( _cum_n_states + np.argmax(unary_marg, axis=-1) ) + # number of states for that type + _cum_n_states += unary_marg.shape[1] + y = np.hstack(ly) + else: + #usual code + y = np.argmax(unary_marginals, axis=-1) + if return_energy: return y, -energy return y -def inference_unaries(unary_potentials, pairwise_potentials, edges, verbose=0, - **kwargs): +def inference_ad3plus(l_unary_potentials, l_pairwise_potentials, l_edges + , relaxed=False + , verbose=0, return_energy=False, branch_and_bound=False + , constraints=None, inference_exception=None): + """ + Inference with AD3 dual decomposition subgradient solver. + + Parameters + ---------- + unary_potentials : nd-array, shape (n_nodes, n_states) + Unary potentials of energy function. + + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). + Pairwise potentials of energy function. + If the first case, edge potentials are assumed to be the same for all + edges. + In the second case, the sequence needs to correspond to the edges. + + edges : nd-array, shape (n_edges, 2) + Graph edges for pairwise potentials, given as pair of node indices. As + pairwise potentials are not assumed to be symmetric, the direction of + the edge matters. + + relaxed : bool (default=False) + Whether to return the relaxed solution (``True``) or round to the next + integer solution (``False``). + + verbose : int (default=0) + Degree of verbosity for solver. + + return_energy : bool (default=False) + Additionally return the energy of the returned solution (according to + the solver). If relaxed=False, this is the energy of the relaxed, not + the rounded solution. + + branch_and_bound : bool (default=False) + Whether to attempt to produce an integral solution using + branch-and-bound. + + constraints : list of logical constraints or None (default:=None) + A logical constraint is tuple like + ( , , , ) + where: + - operator is one of: + 'XOR' 'XOROUT' 'ATMOSTONE' 'OR' 'OROUT' 'ANDOUT' 'IMPLY' + - unaries is a list of the index of each unary involved in this + constraint + - states is a list of unary states (class), 1 per involved unary. If the + states are all the same, you can pass it directly as a scalar value. + - negated is a list of boolean indicating if the unary must be negated. + Again, if all values are the same, pass a single boolean value instead + of a list + + NOTE: this hard logic constraint mechanism has been developed for the + EU project READ, by JL Meunier (Xerox), in November 2016. + The READ project has received funding from the European Union's Horizon + 2020 research and innovation programme under grant agreement No 674943. + + Returns + ------- + labels : nd-array + Approximate (usually) MAP variable assignment. + If relaxed=False, this is a tuple of unary and edge 'marginals'. + + """ + import ad3 +# n_states, pairwise_potentials = \ +# _validate_params(unary_potentials, pairwise_potentials, edges) +# unaries = unary_potentials.reshape(-1, n_states) + bMultiType = isinstance(l_unary_potentials, list) + + res = ad3.general_constrained_graph(l_unary_potentials, l_edges + , l_pairwise_potentials, constraints + , verbose=verbose + , n_iterations=4000 + , exact=branch_and_bound) + + l_unary_marginals, l_pairwise_marginals, energy, solver_status = res + if verbose: + print(solver_status) + + if relaxed and solver_status in ["fractional", "unsolved"]: + y = (l_unary_marginals, l_pairwise_marginals) + else: + if inference_exception and solver_status in ["fractional", "unsolved"]: + raise InferenceException(solver_status) + if bMultiType: + #we now get a list of unary marginals + ly = list() + _cum_n_states = 0 + for unary_marg in l_unary_marginals: + ly.append( _cum_n_states + np.argmax(unary_marg, axis=-1) ) + #number of states for that type + _cum_n_states += unary_marg.shape[1] + y = np.hstack(ly) + # when we will simplify y: + #y = [_cum_n_statesnp.argmax(unary_marg, axis=-1) for unary_marg + # in l_unary_marginals] + else: + y = np.argmax(l_unary_marginals, axis=-1) + + if return_energy: + return y, -energy + return y + + + +def inference_unaries(unary_potentials, pairwise_potentials, edges, verbose=0 + , **kwargs): """Inference that only uses unary potentials. This methods can be used as a sanity check, as acceleration if no @@ -384,7 +552,8 @@ def inference_unaries(unary_potentials, pairwise_potentials, edges, verbose=0, unary_potentials : nd-array, shape (n_nodes, n_states) Unary potentials of energy function. - pairwise_potentials : nd-array, shape (n_states, n_states) or (n_states, n_states, n_edges). + pairwise_potentials : nd-array, shape (n_states, n_states) + or (n_states, n_states, n_edges). Pairwise potentials of energy function. These will be ignored. diff --git a/pystruct/learners/one_slack_ssvm.py b/pystruct/learners/one_slack_ssvm.py index c5f6a162..65dd43da 100644 --- a/pystruct/learners/one_slack_ssvm.py +++ b/pystruct/learners/one_slack_ssvm.py @@ -171,7 +171,7 @@ def _solve_1_slack_qp(self, constraints, n_samples): tmp1 = np.zeros(n_constraints) # positivity constraints: if self.negativity_constraint is None: - #empty constraints + # empty constraints zero_constr = np.zeros(0) joint_features_constr = np.zeros((0, n_constraints)) else: @@ -277,6 +277,35 @@ def _check_bad_constraint(self, violation, djoint_feature_mean, loss, return True return False + @classmethod + def constraint_equal(cls, y_1, y_2): + """ + This now more complex. y_1 and/or y_2 (I think) can be: array, pair of + arrays, pair of list of arrays (multitype) + We need to compare those! + """ + if isinstance(y_1, tuple): + # y_1 is relaxed Y + # y_1 and y_2 might be lists of ndarray (multitype) instead of + # ndarray (single type) + u_m_1, pw_m_1 = y_1 + if isinstance(y_2, tuple): # we then compare two relaxed Ys + u_m_2, pw_m_2 = y_2 + # now, do we multitype or single type relaxed marginals?? + if isinstance(u_m_1, list): + return all(np.all(_um1 == _um2) for _um1, _um2 + in zip( u_m_1, u_m_2)) \ + and all(np.all(_pw1 == _pw2) for _pw1, _pw2 + in zip(pw_m_1, pw_m_2)) + else: + return np.all(u_m_1 == u_m_2) and np.all(pw_m_1, pw_m_2) + else: + # NOTE original code was possibly comparing array and scalar + # return np.all(y_1[0] == y_2[0]) and np.all(y_1[1] == y_2[1]) + return False + # might compare array and tuple... :-/ Was like that, I keep + return np.all(y_1 == y_2) + def _update_cache(self, X, Y, Y_hat): """Updated cached constraints.""" if self.inference_cache == 0: @@ -285,13 +314,8 @@ def _update_cache(self, X, Y, Y_hat): or self.inference_cache_ is None): self.inference_cache_ = [[] for y in Y_hat] - def constraint_equal(y_1, y_2): - if isinstance(y_1, tuple): - return np.all(y_1[0] == y_2[0]) and np.all(y_1[1] == y_2[1]) - return np.all(y_1 == y_2) - for sample, x, y, y_hat in zip(self.inference_cache_, X, Y, Y_hat): - already_there = [constraint_equal(y_hat, cache[2]) + already_there = [self.constraint_equal(y_hat, cache[2]) for cache in sample] if np.any(already_there): continue diff --git a/pystruct/learners/ssvm.py b/pystruct/learners/ssvm.py index 224754f8..308ecdb8 100644 --- a/pystruct/learners/ssvm.py +++ b/pystruct/learners/ssvm.py @@ -18,7 +18,7 @@ def __init__(self, model, max_iter=100, C=1.0, verbose=0, self.n_jobs = n_jobs self.logger = logger - def predict(self, X): + def predict(self, X, constraints=None): """Predict output on examples in X. Parameters @@ -26,6 +26,8 @@ def predict(self, X): X : iterable Traing instances. Contains the structured input objects. + constraints : None or a list of hard logic constraints + Returns ------- Y_pred : list @@ -34,12 +36,24 @@ def predict(self, X): """ verbose = max(0, self.verbose - 3) if self.n_jobs != 1: - prediction = Parallel(n_jobs=self.n_jobs, verbose=verbose)( - delayed(inference)(self.model, x, self.w) for x in X) + if constraints: + prediction = Parallel(n_jobs=self.n_jobs, verbose=verbose)( + delayed(inference)(self.model, x, self.w, constraints=c) + for x, c in zip(X, constraints)) + else: + prediction = Parallel(n_jobs=self.n_jobs, verbose=verbose)( + delayed(inference)(self.model, x, self.w) for x in X) return prediction else: if hasattr(self.model, 'batch_inference'): - return self.model.batch_inference(X, self.w) + if constraints: + return self.model.batch_inference(X, self.w, + constraints=constraints) + else: + return self.model.batch_inference(X, self.w) + if constraints: + return [self.model.inference(x, self.w, constraints=c) + for x, c in zip(X, constraints)] return [self.model.inference(x, self.w) for x in X] def score(self, X, Y): diff --git a/pystruct/models/__init__.py b/pystruct/models/__init__.py index d1632d4f..8b02ab64 100644 --- a/pystruct/models/__init__.py +++ b/pystruct/models/__init__.py @@ -9,9 +9,12 @@ from .unstructured_svm import BinaryClf, MultiClassClf from .multilabel_svm import MultiLabelClf from .edge_feature_graph_crf import EdgeFeatureGraphCRF +from .typed_crf import TypedCRF +from .node_type_edge_feature_graph_crf import NodeTypeEdgeFeatureGraphCRF __all__ = ["StructuredModel", "CRF", "GridCRF", "GraphCRF", "DirectionalGridCRF", "BinaryClf", "LatentGridCRF", "LatentDirectionalGridCRF", "MultiClassClf", "LatentGraphCRF", "MultiLabelClf", "ChainCRF", "LatentNodeCRF", "EdgeFeatureGraphCRF", - "EdgeFeatureLatentNodeCRF"] + "EdgeFeatureLatentNodeCRF", + "TypedCRF", "NodeTypeEdgeFeatureGraphCRF"] diff --git a/pystruct/models/base.py b/pystruct/models/base.py index c63fcdaf..8e3fa44a 100644 --- a/pystruct/models/base.py +++ b/pystruct/models/base.py @@ -13,8 +13,8 @@ def __repr__(self): def __init__(self): """Initialize the model. - Needs to set self.size_joint_feature, the dimensionalty of the joint features for - an instance with labeling (x, y). + Needs to set self.size_joint_feature, the dimensionality of the joint + features for an instance with labeling (x, y). """ self.size_joint_feature = None @@ -46,11 +46,14 @@ def _loss_augmented_djoint_feature(self, x, y, y_hat, w): return (self.joint_feature(x_loss_augmented, y) - self.joint_feature(x_loss_augmented, y_hat)) - def inference(self, x, w, relaxed=None): + def inference(self, x, w, relaxed=None, constraints=None): raise NotImplementedError() - def batch_inference(self, X, w, relaxed=None): + def batch_inference(self, X, w, relaxed=None, constraints=None): # default implementation of batch inference + if constraints: + return [self.inference(x, w, relaxed=relaxed, constraints=c) + for x, c in zip(X, constraints)] return [self.inference(x, w, relaxed=relaxed) for x in X] diff --git a/pystruct/models/crf.py b/pystruct/models/crf.py index 18dc7437..ba466829 100644 --- a/pystruct/models/crf.py +++ b/pystruct/models/crf.py @@ -52,6 +52,13 @@ def _check_size_x(self, x): " got %s instead." % (self.n_features, features.shape[1])) + def loss_augment_unaries(self, unary_potentials, y): + """ + we define it as a method so that subclasses can specialize it. + """ + loss_augment_unaries(unary_potentials, np.asarray(y), + self.class_weight) + def loss_augmented_inference(self, x, y, w, relaxed=False, return_energy=False): """Loss-augmented Inference for x relative to y using parameters w. @@ -103,13 +110,15 @@ def loss_augmented_inference(self, x, y, w, relaxed=False, unary_potentials = self._get_unary_potentials(x, w) pairwise_potentials = self._get_pairwise_potentials(x, w) edges = self._get_edges(x) - loss_augment_unaries(unary_potentials, np.asarray(y), self.class_weight) + + self.loss_augment_unaries(unary_potentials, y) return inference_dispatch(unary_potentials, pairwise_potentials, edges, self.inference_method, relaxed=relaxed, return_energy=return_energy) - def inference(self, x, w, relaxed=False, return_energy=False): + def inference(self, x, w, relaxed=False, return_energy=False, + constraints=None): """Inference for x using parameters w. Finds (approximately) @@ -137,6 +146,9 @@ def inference(self, x, w, relaxed=False, return_energy=False): return_energy : bool, default=False Whether to return the energy of the solution (x, y) that was found. + constraints : None or list, default=False + hard logic constraints, if any + Returns ------- y_pred : ndarray or tuple @@ -156,6 +168,16 @@ def inference(self, x, w, relaxed=False, return_energy=False): pairwise_potentials = self._get_pairwise_potentials(x, w) edges = self._get_edges(x) - return inference_dispatch(unary_potentials, pairwise_potentials, edges, - self.inference_method, relaxed=relaxed, - return_energy=return_energy) + if constraints: + return inference_dispatch(unary_potentials, pairwise_potentials, + edges, + self.inference_method, + relaxed=relaxed, + return_energy=return_energy, + constraints=constraints) + else: + return inference_dispatch(unary_potentials, pairwise_potentials, + edges, + self.inference_method, + relaxed=relaxed, + return_energy=return_energy) diff --git a/pystruct/models/latent_graph_crf.py b/pystruct/models/latent_graph_crf.py index c62788e7..c77e5b69 100644 --- a/pystruct/models/latent_graph_crf.py +++ b/pystruct/models/latent_graph_crf.py @@ -114,7 +114,7 @@ def _set_size_joint_feature(self): "or array-like of length n_labels. Got %s" % str(n_states_per_label)) self.n_states_per_label = n_states_per_label - self.n_states = np.sum(n_states_per_label) + self.n_states = int(np.sum(n_states_per_label)) # compute mapping from latent states to labels ranges = np.cumsum(n_states_per_label) diff --git a/pystruct/tests/test_libraries.py b/pystruct/tests/test_libraries.py index 6d89afc5..1591c4c8 100644 --- a/pystruct/tests/test_libraries.py +++ b/pystruct/tests/test_libraries.py @@ -4,10 +4,17 @@ def test_pyqpbo(): import pyqpbo pyqpbo - assert 'qpbo' in get_installed() + assert 'qpbo' in get_installed(['qpbo']) def test_ad3(): import ad3 ad3 - assert 'ad3' in get_installed() + assert 'ad3' in get_installed(['ad3']) + +def test_ad3plus(): + import ad3 + ad3 + assert 'ad3+' in get_installed(['ad3+']) + + diff --git a/pystruct/tests/test_models/test_grid_crf.py b/pystruct/tests/test_models/test_grid_crf.py index cc953a9f..6705554d 100644 --- a/pystruct/tests/test_models/test_grid_crf.py +++ b/pystruct/tests/test_models/test_grid_crf.py @@ -121,6 +121,8 @@ def test_blocks_multinomial_crf(): -.3, .3, -.5, -.1, .3]) for inference_method in get_installed(): + #NOTE: ad3+ fails because it requires a different data structure + if inference_method == 'ad3+': continue crf = GridCRF(inference_method=inference_method) crf.initialize(X, Y) y_hat = crf.inference(x, w) @@ -133,6 +135,8 @@ def test_binary_grid_unaries(): X, Y = ds(n_samples=1) x, y = X[0], Y[0] for inference_method in get_installed(): + #NOTE: ad3+ fails because it requires a different data structure + if inference_method == 'ad3+': continue crf = GridCRF(inference_method=inference_method) crf.initialize(X, Y) w_unaries_only = np.zeros(7) diff --git a/pystruct/utils/inference.py b/pystruct/utils/inference.py index 89b14f64..e21c6561 100644 --- a/pystruct/utils/inference.py +++ b/pystruct/utils/inference.py @@ -100,8 +100,11 @@ def find_constraint_latent(model, x, y, w, relaxed=True): return h_hat, delta_joint_feature, slack, loss -def inference(model, x, w): - return model.inference(x, w) +def inference(model, x, w, constraints=None): + if constraints: + return model.inference(x, w, constraints=constraints) + else: + return model.inference(x, w) def loss_augmented_inference(model, x, y, w, relaxed=True): diff --git a/requirements.txt b/requirements.txt index 29a24a97..b3ac4911 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ numpy scipy cvxopt +future Cython>=0.19.1 scikit-learn>=0.11 -ad3 +ad3>=2.2.2 diff --git a/setup.py b/setup.py index f03f837d..24e81060 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ include_dirs = [np.get_include()] setup(name="pystruct", - version="0.2.5", + version="0.3.1", install_requires=["ad3", "numpy"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', @@ -39,9 +39,8 @@ 'Operating System :: Unix', 'Operating System :: MacOS', 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.3', + 'Programming Language :: Python :: 3.6', ], ) From c61e6cabb961e8c386706289d579b263993b0eba Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 2 Oct 2018 16:04:19 +0200 Subject: [PATCH 149/155] fix for the bug reported by Wladimir Sidorenko on 12/9/2018 --- pystruct/models/latent_node_crf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pystruct/models/latent_node_crf.py b/pystruct/models/latent_node_crf.py index 94d61673..14cbd84a 100644 --- a/pystruct/models/latent_node_crf.py +++ b/pystruct/models/latent_node_crf.py @@ -493,7 +493,7 @@ def _get_unary_potentials(self, x, w): if self.latent_node_features: unaries = np.dot(features, unary_params.T) - n_hidden = x[2] + n_hidden = x[-1] n_visible = features.shape[0] - n_hidden else: # we only have features for visible nodes From 649326d047000c9b3e6fb3a6b36c37d8c63a18f2 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 2 Oct 2018 16:04:33 +0200 Subject: [PATCH 150/155] StopIteration is deprecated. Fixed by doing 'return'. --- pystruct/models/typed_crf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pystruct/models/typed_crf.py b/pystruct/models/typed_crf.py index 5c3e87ce..1c0d9407 100644 --- a/pystruct/models/typed_crf.py +++ b/pystruct/models/typed_crf.py @@ -278,7 +278,7 @@ def _iter_type_pairs(self): for typ1 in range(self.n_types): for typ2 in range(self.n_types): yield (typ1, typ2) - raise StopIteration + return def _get_unary_potentials(self, x, w): """Computes unary potentials for x and w. From fd70c981b4c1d484595542ea04fedea2d9dd16c2 Mon Sep 17 00:00:00 2001 From: Jean-Luc Meunier Date: Tue, 2 Oct 2018 16:21:26 +0200 Subject: [PATCH 151/155] 0.3.2 --- CHANGELOG | 4 ++++ pystruct/__init__.py | 2 +- setup.py | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 1440dcf0..0b762fd8 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,7 @@ +0.3.2 +===== +- 2 bug fixes + 0.3.1 ===== - Added new model NodeTypeEdgeFeatureGraphCRF diff --git a/pystruct/__init__.py b/pystruct/__init__.py index 260c070a..f9aa3e11 100644 --- a/pystruct/__init__.py +++ b/pystruct/__init__.py @@ -1 +1 @@ -__version__ = "0.3.1" +__version__ = "0.3.2" diff --git a/setup.py b/setup.py index 24e81060..6bca86c2 100644 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ include_dirs = [np.get_include()] setup(name="pystruct", - version="0.3.1", + version="0.3.2", install_requires=["ad3", "numpy"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', From a9504940a31c856adb7ef18434dfde92b683cd94 Mon Sep 17 00:00:00 2001 From: lison Date: Mon, 20 Sep 2021 02:40:37 -0400 Subject: [PATCH 152/155] changed sklearn.external.joblib to joblib for import --- pystruct/learners/n_slack_ssvm.py | 2 +- pystruct/learners/one_slack_ssvm.py | 2 +- pystruct/learners/ssvm.py | 2 +- pystruct/learners/structured_perceptron.py | 2 +- pystruct/learners/subgradient_latent_ssvm.py | 2 +- pystruct/learners/subgradient_ssvm.py | 2 +- pystruct/utils/inference.py | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/pystruct/learners/n_slack_ssvm.py b/pystruct/learners/n_slack_ssvm.py index f7418305..675ca702 100644 --- a/pystruct/learners/n_slack_ssvm.py +++ b/pystruct/learners/n_slack_ssvm.py @@ -12,7 +12,7 @@ import cvxopt import cvxopt.solvers -from sklearn.externals.joblib import Parallel, delayed +from joblib import Parallel, delayed from sklearn.utils import gen_even_slices from .ssvm import BaseSSVM diff --git a/pystruct/learners/one_slack_ssvm.py b/pystruct/learners/one_slack_ssvm.py index 65dd43da..4944b28f 100644 --- a/pystruct/learners/one_slack_ssvm.py +++ b/pystruct/learners/one_slack_ssvm.py @@ -11,7 +11,7 @@ import cvxopt import cvxopt.solvers -from sklearn.externals.joblib import Parallel, delayed +from joblib import Parallel, delayed from .ssvm import BaseSSVM from ..utils import loss_augmented_inference diff --git a/pystruct/learners/ssvm.py b/pystruct/learners/ssvm.py index 308ecdb8..35a1d56f 100644 --- a/pystruct/learners/ssvm.py +++ b/pystruct/learners/ssvm.py @@ -1,6 +1,6 @@ import numpy as np -from sklearn.externals.joblib import Parallel, delayed +from joblib import Parallel, delayed from sklearn.base import BaseEstimator from ..utils import inference, objective_primal diff --git a/pystruct/learners/structured_perceptron.py b/pystruct/learners/structured_perceptron.py index 56c51e3a..e130fc58 100644 --- a/pystruct/learners/structured_perceptron.py +++ b/pystruct/learners/structured_perceptron.py @@ -1,5 +1,5 @@ import numpy as np -from sklearn.externals.joblib import Parallel, delayed +from joblib import Parallel, delayed from .ssvm import BaseSSVM diff --git a/pystruct/learners/subgradient_latent_ssvm.py b/pystruct/learners/subgradient_latent_ssvm.py index b5809fc6..1522e76d 100644 --- a/pystruct/learners/subgradient_latent_ssvm.py +++ b/pystruct/learners/subgradient_latent_ssvm.py @@ -6,7 +6,7 @@ from time import time import numpy as np -from sklearn.externals.joblib import Parallel, delayed, cpu_count +from joblib import Parallel, delayed, cpu_count from sklearn.utils import gen_even_slices from .subgradient_ssvm import SubgradientSSVM diff --git a/pystruct/learners/subgradient_ssvm.py b/pystruct/learners/subgradient_ssvm.py index 28cd5519..ed4ce466 100644 --- a/pystruct/learners/subgradient_ssvm.py +++ b/pystruct/learners/subgradient_ssvm.py @@ -1,7 +1,7 @@ from time import time import numpy as np -from sklearn.externals.joblib import Parallel, delayed, cpu_count +from joblib import Parallel, delayed, cpu_count from sklearn.utils import gen_even_slices, shuffle from .ssvm import BaseSSVM diff --git a/pystruct/utils/inference.py b/pystruct/utils/inference.py index e21c6561..9265d99f 100644 --- a/pystruct/utils/inference.py +++ b/pystruct/utils/inference.py @@ -1,5 +1,5 @@ import itertools -from sklearn.externals.joblib import Parallel, delayed +from joblib import Parallel, delayed import numpy as np From 8229451f22cead5e0c81fb3bdaaa1a66c22608ac Mon Sep 17 00:00:00 2001 From: lison Date: Tue, 21 Sep 2021 21:08:08 -0400 Subject: [PATCH 153/155] Changed requirements in setup.py and applied a patch in src/utils.c --- setup.py | 3 +- src/utils.c | 18316 +++++++++++++++++++++++++++++++------------------- 2 files changed, 11380 insertions(+), 6939 deletions(-) diff --git a/setup.py b/setup.py index 6bca86c2..0d1d7b4d 100644 --- a/setup.py +++ b/setup.py @@ -11,7 +11,7 @@ setup(name="pystruct", version="0.3.2", - install_requires=["ad3", "numpy"], + install_requires=["ad3", "numpy", "cvxopt", "future", "Cython", "scikit-learn"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', 'pystruct.tests', 'pystruct.tests.test_learners', @@ -42,5 +42,6 @@ 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.8' ], ) diff --git a/src/utils.c b/src/utils.c index 225afcc7..5e514253 100644 --- a/src/utils.c +++ b/src/utils.c @@ -1,28 +1,17 @@ -/* Generated by Cython 0.21.1 */ +/* Generated by Cython 0.27.3 */ #define PY_SSIZE_T_CLEAN -#ifndef CYTHON_USE_PYLONG_INTERNALS -#ifdef PYLONG_BITS_IN_DIGIT -#define CYTHON_USE_PYLONG_INTERNALS 0 -#else -#include "pyconfig.h" -#ifdef PYLONG_BITS_IN_DIGIT -#define CYTHON_USE_PYLONG_INTERNALS 1 -#else -#define CYTHON_USE_PYLONG_INTERNALS 0 -#endif -#endif -#endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. -#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) - #error Cython requires Python 2.6+ or Python 3.2+. +#elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) + #error Cython requires Python 2.6+ or Python 3.3+. #else -#define CYTHON_ABI "0_21_1" +#define CYTHON_ABI "0_27_3" +#define CYTHON_FUTURE_DIVISION 0 #include #ifndef offsetof -#define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) + #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall @@ -41,6 +30,12 @@ #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif +#define __PYX_COMMA , +#ifndef HAVE_LONG_LONG + #if PY_VERSION_HEX >= 0x02070000 + #define HAVE_LONG_LONG + #endif +#endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif @@ -48,63 +43,267 @@ #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION -#define CYTHON_COMPILING_IN_PYPY 1 -#define CYTHON_COMPILING_IN_CPYTHON 0 + #define CYTHON_COMPILING_IN_PYPY 1 + #define CYTHON_COMPILING_IN_PYSTON 0 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #undef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 0 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #if PY_VERSION_HEX < 0x03050000 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #elif !defined(CYTHON_USE_ASYNC_SLOTS) + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #undef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #undef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 1 + #undef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 0 + #undef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 0 + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 +#elif defined(PYSTON_VERSION) + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_PYSTON 1 + #define CYTHON_COMPILING_IN_CPYTHON 0 + #ifndef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #undef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 0 + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #undef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 0 + #undef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 0 + #undef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT 0 + #undef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE 0 #else -#define CYTHON_COMPILING_IN_PYPY 0 -#define CYTHON_COMPILING_IN_CPYTHON 1 + #define CYTHON_COMPILING_IN_PYPY 0 + #define CYTHON_COMPILING_IN_PYSTON 0 + #define CYTHON_COMPILING_IN_CPYTHON 1 + #ifndef CYTHON_USE_TYPE_SLOTS + #define CYTHON_USE_TYPE_SLOTS 1 + #endif + #if PY_VERSION_HEX < 0x02070000 + #undef CYTHON_USE_PYTYPE_LOOKUP + #define CYTHON_USE_PYTYPE_LOOKUP 0 + #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) + #define CYTHON_USE_PYTYPE_LOOKUP 1 + #endif + #if PY_MAJOR_VERSION < 3 + #undef CYTHON_USE_ASYNC_SLOTS + #define CYTHON_USE_ASYNC_SLOTS 0 + #elif !defined(CYTHON_USE_ASYNC_SLOTS) + #define CYTHON_USE_ASYNC_SLOTS 1 + #endif + #if PY_VERSION_HEX < 0x02070000 + #undef CYTHON_USE_PYLONG_INTERNALS + #define CYTHON_USE_PYLONG_INTERNALS 0 + #elif !defined(CYTHON_USE_PYLONG_INTERNALS) + #define CYTHON_USE_PYLONG_INTERNALS 1 + #endif + #ifndef CYTHON_USE_PYLIST_INTERNALS + #define CYTHON_USE_PYLIST_INTERNALS 1 + #endif + #ifndef CYTHON_USE_UNICODE_INTERNALS + #define CYTHON_USE_UNICODE_INTERNALS 1 + #endif + #if PY_VERSION_HEX < 0x030300F0 + #undef CYTHON_USE_UNICODE_WRITER + #define CYTHON_USE_UNICODE_WRITER 0 + #elif !defined(CYTHON_USE_UNICODE_WRITER) + #define CYTHON_USE_UNICODE_WRITER 1 + #endif + #ifndef CYTHON_AVOID_BORROWED_REFS + #define CYTHON_AVOID_BORROWED_REFS 0 + #endif + #ifndef CYTHON_ASSUME_SAFE_MACROS + #define CYTHON_ASSUME_SAFE_MACROS 1 + #endif + #ifndef CYTHON_UNPACK_METHODS + #define CYTHON_UNPACK_METHODS 1 + #endif + #ifndef CYTHON_FAST_THREAD_STATE + #define CYTHON_FAST_THREAD_STATE 1 + #endif + #ifndef CYTHON_FAST_PYCALL + #define CYTHON_FAST_PYCALL 1 + #endif + #ifndef CYTHON_PEP489_MULTI_PHASE_INIT + #define CYTHON_PEP489_MULTI_PHASE_INIT (0 && PY_VERSION_HEX >= 0x03050000) + #endif + #ifndef CYTHON_USE_TP_FINALIZE + #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) + #endif #endif -#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 -#define Py_OptimizeFlag 0 +#if !defined(CYTHON_FAST_PYCCALL) +#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) +#endif +#if CYTHON_USE_PYLONG_INTERNALS + #include "longintrepr.h" + #undef SHIFT + #undef BASE + #undef MASK +#endif +#if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) + #define Py_OptimizeFlag 0 #endif #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" - #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ + #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyType_Type #endif -#if PY_MAJOR_VERSION >= 3 +#ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 +#endif +#ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 +#endif +#ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif -#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) +#ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif +#if PY_VERSION_HEX < 0x030700A0 || !defined(METH_FASTCALL) + #ifndef METH_FASTCALL + #define METH_FASTCALL 0x80 + #endif + typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject **args, Py_ssize_t nargs); + typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject **args, + Py_ssize_t nargs, PyObject *kwnames); +#else + #define __Pyx_PyCFunctionFast _PyCFunctionFast + #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords +#endif +#if CYTHON_FAST_PYCCALL +#define __Pyx_PyFastCFunction_Check(func)\ + ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS))))) +#else +#define __Pyx_PyFastCFunction_Check(func) 0 +#endif +#if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#elif PY_VERSION_HEX >= 0x03060000 + #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() +#elif PY_VERSION_HEX >= 0x03000000 + #define __Pyx_PyThreadState_Current PyThreadState_GET() +#else + #define __Pyx_PyThreadState_Current _PyThreadState_Current +#endif +#if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) +#define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) +#else +#define __Pyx_PyDict_NewPresized(n) PyDict_New() +#endif +#if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION + #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) +#else + #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) + #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) +#endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 - #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ + #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #else #define CYTHON_PEP393_ENABLED 0 + #define PyUnicode_1BYTE_KIND 1 + #define PyUnicode_2BYTE_KIND 2 + #define PyUnicode_4BYTE_KIND 4 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) + #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) + #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) + #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) - #define __Pyx_PyFrozenSet_Size(s) PyObject_Size(s) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) - #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ + #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) - #define __Pyx_PyFrozenSet_Size(s) PySet_Size(s) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) + #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) + #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) + #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) +#endif +#if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) + #define PyObject_Malloc(s) PyMem_Malloc(s) + #define PyObject_Free(p) PyMem_Free(p) + #define PyObject_Realloc(p) PyMem_Realloc(p) +#endif +#if CYTHON_COMPILING_IN_PYSTON + #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) +#else + #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) + #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) @@ -113,6 +312,9 @@ #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif +#if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) + #define PyObject_ASCII(o) PyObject_Repr(o) +#endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject @@ -130,7 +332,7 @@ #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif -#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type @@ -169,16 +371,28 @@ #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif -#ifndef CYTHON_INLINE - #if defined(__GNUC__) - #define CYTHON_INLINE __inline__ - #elif defined(_MSC_VER) - #define CYTHON_INLINE __inline - #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L - #define CYTHON_INLINE inline +#ifndef __has_attribute + #define __has_attribute(x) 0 +#endif +#ifndef __has_cpp_attribute + #define __has_cpp_attribute(x) 0 +#endif +#if CYTHON_USE_ASYNC_SLOTS + #if PY_VERSION_HEX >= 0x030500B1 + #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods + #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) #else - #define CYTHON_INLINE + #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #endif +#else + #define __Pyx_PyType_AsAsync(obj) NULL +#endif +#ifndef __Pyx_PyAsyncMethodsStruct + typedef struct { + unaryfunc am_await; + unaryfunc am_aiter; + unaryfunc am_anext; + } __Pyx_PyAsyncMethodsStruct; #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) @@ -191,33 +405,110 @@ #define CYTHON_RESTRICT #endif #endif +#ifndef CYTHON_UNUSED +# if defined(__GNUC__) +# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) +# define CYTHON_UNUSED __attribute__ ((__unused__)) +# else +# define CYTHON_UNUSED +# endif +#endif +#ifndef CYTHON_MAYBE_UNUSED_VAR +# if defined(__cplusplus) + template void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } +# else +# define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) +# endif +#endif +#ifndef CYTHON_NCP_UNUSED +# if CYTHON_COMPILING_IN_CPYTHON +# define CYTHON_NCP_UNUSED +# else +# define CYTHON_NCP_UNUSED CYTHON_UNUSED +# endif +#endif +#define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) +#ifdef _MSC_VER + #ifndef _MSC_STDINT_H_ + #if _MSC_VER < 1300 + typedef unsigned char uint8_t; + typedef unsigned int uint32_t; + #else + typedef unsigned __int8 uint8_t; + typedef unsigned __int32 uint32_t; + #endif + #endif +#else + #include +#endif +#ifndef CYTHON_FALLTHROUGH + #if defined(__cplusplus) && __cplusplus >= 201103L + #if __has_cpp_attribute(fallthrough) + #define CYTHON_FALLTHROUGH [[fallthrough]] + #elif __has_cpp_attribute(clang::fallthrough) + #define CYTHON_FALLTHROUGH [[clang::fallthrough]] + #elif __has_cpp_attribute(gnu::fallthrough) + #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] + #endif + #endif + #ifndef CYTHON_FALLTHROUGH + #if __has_attribute(fallthrough) + #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) + #else + #define CYTHON_FALLTHROUGH + #endif + #endif + #if defined(__clang__ ) && defined(__apple_build_version__) + #if __apple_build_version__ < 7000000 + #undef CYTHON_FALLTHROUGH + #define CYTHON_FALLTHROUGH + #endif + #endif +#endif + +#ifndef CYTHON_INLINE + #if defined(__clang__) + #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) + #elif defined(__GNUC__) + #define CYTHON_INLINE __inline__ + #elif defined(_MSC_VER) + #define CYTHON_INLINE __inline + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define CYTHON_INLINE inline + #else + #define CYTHON_INLINE + #endif +#endif + +#if defined(WIN32) || defined(MS_WINDOWS) + #define _USE_MATH_DEFINES +#endif +#include #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { - /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and - a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is - a quiet NaN. */ float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif -#ifdef __cplusplus -template -void __Pyx_call_destructor(T* x) { - x->~T(); -} +#if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) +#define __Pyx_truncl trunc +#else +#define __Pyx_truncl truncl #endif -#if PY_MAJOR_VERSION >= 3 - #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) -#else - #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) - #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) -#endif +#define __PYX_ERR(f_index, lineno, Ln_error) \ +{ \ + __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \ +} #ifndef __PYX_EXTERN_C #ifdef __cplusplus @@ -227,39 +518,22 @@ void __Pyx_call_destructor(T* x) { #endif #endif -#if defined(WIN32) || defined(MS_WINDOWS) -#define _USE_MATH_DEFINES -#endif -#include #define __PYX_HAVE__utils #define __PYX_HAVE_API__utils #include "pythread.h" -#include "string.h" -#include "stdlib.h" -#include "stdio.h" +#include +#include +#include #include "pystate.h" #ifdef _OPENMP #include #endif /* _OPENMP */ -#ifdef PYREX_WITHOUT_ASSERTIONS +#if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) #define CYTHON_WITHOUT_ASSERTIONS #endif -#ifndef CYTHON_UNUSED -# if defined(__GNUC__) -# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) -# define CYTHON_UNUSED __attribute__ ((__unused__)) -# else -# define CYTHON_UNUSED -# endif -#endif -typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; +typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 @@ -267,18 +541,36 @@ typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize -#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ - (sizeof(type) < sizeof(Py_ssize_t)) || \ - (sizeof(type) > sizeof(Py_ssize_t) && \ - likely(v < (type)PY_SSIZE_T_MAX || \ - v == (type)PY_SSIZE_T_MAX) && \ - (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ - v == (type)PY_SSIZE_T_MIN))) || \ - (sizeof(type) == sizeof(Py_ssize_t) && \ - (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ +#define __Pyx_uchar_cast(c) ((unsigned char)c) +#define __Pyx_long_cast(x) ((long)x) +#define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ + (sizeof(type) < sizeof(Py_ssize_t)) ||\ + (sizeof(type) > sizeof(Py_ssize_t) &&\ + likely(v < (type)PY_SSIZE_T_MAX ||\ + v == (type)PY_SSIZE_T_MAX) &&\ + (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ + v == (type)PY_SSIZE_T_MIN))) ||\ + (sizeof(type) == sizeof(Py_ssize_t) &&\ + (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX))) ) -static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); -static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); +#if defined (__cplusplus) && __cplusplus >= 201103L + #include + #define __Pyx_sst_abs(value) std::abs(value) +#elif SIZEOF_INT >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) abs(value) +#elif SIZEOF_LONG >= SIZEOF_SIZE_T + #define __Pyx_sst_abs(value) labs(value) +#elif defined (_MSC_VER) + #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) +#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L + #define __Pyx_sst_abs(value) llabs(value) +#elif defined (__GNUC__) + #define __Pyx_sst_abs(value) __builtin_llabs(value) +#else + #define __Pyx_sst_abs(value) ((value<0) ? -value : value) +#endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString @@ -291,38 +583,51 @@ static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif -#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) -#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((const char*)s) -#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((const char*)s) -#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((const char*)s) -#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((const char*)s) -#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((const char*)s) -#if PY_MAJOR_VERSION < 3 -static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) -{ +#define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) +#define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) +#define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) +#define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) +#define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) +#define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) +#define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) +static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return (size_t)(u_end - u - 1); } -#else -#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen -#endif #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode -#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) -#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) +#define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) +#define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) +#define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); -static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); +static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); +#define __Pyx_PySequence_Tuple(obj)\ + (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); -#if CYTHON_COMPILING_IN_CPYTHON +#if CYTHON_ASSUME_SAFE_MACROS #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) +#else +#define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) +#endif +#define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { @@ -333,7 +638,7 @@ static int __Pyx_init_sys_getdefaultencoding_params(void) { const char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; - default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); + default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); @@ -407,12 +712,15 @@ static int __Pyx_init_sys_getdefaultencoding_params(void) { #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ +static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } -static PyObject *__pyx_m; +static PyObject *__pyx_m = NULL; static PyObject *__pyx_d; static PyObject *__pyx_b; +static PyObject *__pyx_cython_runtime; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; +static PyObject *__pyx_empty_unicode; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; @@ -423,6 +731,7 @@ static const char *__pyx_f[] = { "utils.pyx", "stringsource", }; +/* MemviewSliceStruct.proto */ struct __pyx_memoryview_obj; typedef struct { struct __pyx_memoryview_obj *memview; @@ -431,62 +740,30 @@ typedef struct { Py_ssize_t strides[8]; Py_ssize_t suboffsets[8]; } __Pyx_memviewslice; +#define __Pyx_MemoryView_Len(m) (m.shape[0]) -#define IS_UNSIGNED(type) (((type) -1) > 0) -struct __Pyx_StructField_; -#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) -typedef struct { - const char* name; - struct __Pyx_StructField_* fields; - size_t size; - size_t arraysize[8]; - int ndim; - char typegroup; - char is_unsigned; - int flags; -} __Pyx_TypeInfo; -typedef struct __Pyx_StructField_ { - __Pyx_TypeInfo* type; - const char* name; - size_t offset; -} __Pyx_StructField; -typedef struct { - __Pyx_StructField* field; - size_t parent_offset; -} __Pyx_BufFmt_StackElem; -typedef struct { - __Pyx_StructField root; - __Pyx_BufFmt_StackElem* head; - size_t fmt_offset; - size_t new_count, enc_count; - size_t struct_alignment; - int is_complex; - char enc_type; - char new_packmode; - char enc_packmode; - char is_valid_array; -} __Pyx_BufFmt_Context; - +/* Atomics.proto */ #include #ifndef CYTHON_ATOMICS #define CYTHON_ATOMICS 1 #endif #define __pyx_atomic_int_type int -#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \ - (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \ +#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 ||\ + (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) &&\ !defined(__i386__) #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) #ifdef __PYX_DEBUG_ATOMICS #warning "Using GNU atomics" #endif -#elif CYTHON_ATOMICS && MSC_VER +#elif CYTHON_ATOMICS && defined(_MSC_VER) && 0 #include + #undef __pyx_atomic_int_type #define __pyx_atomic_int_type LONG #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) #ifdef __PYX_DEBUG_ATOMICS - #warning "Using MSVC atomics" + #pragma message ("Using MSVC atomics") #endif #elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) @@ -503,17 +780,65 @@ typedef struct { #endif typedef volatile __pyx_atomic_int_type __pyx_atomic_int; #if CYTHON_ATOMICS - #define __pyx_add_acquisition_count(memview) \ + #define __pyx_add_acquisition_count(memview)\ __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) - #define __pyx_sub_acquisition_count(memview) \ + #define __pyx_sub_acquisition_count(memview)\ __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) #else - #define __pyx_add_acquisition_count(memview) \ + #define __pyx_add_acquisition_count(memview)\ __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) - #define __pyx_sub_acquisition_count(memview) \ + #define __pyx_sub_acquisition_count(memview)\ __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) #endif +/* ForceInitThreads.proto */ +#ifndef __PYX_FORCE_INIT_THREADS + #define __PYX_FORCE_INIT_THREADS 0 +#endif + +/* NoFastGil.proto */ +#define __Pyx_PyGILState_Ensure PyGILState_Ensure +#define __Pyx_PyGILState_Release PyGILState_Release +#define __Pyx_FastGIL_Remember() +#define __Pyx_FastGIL_Forget() +#define __Pyx_FastGilFuncInit() + +/* BufferFormatStructs.proto */ +#define IS_UNSIGNED(type) (((type) -1) > 0) +struct __Pyx_StructField_; +#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) +typedef struct { + const char* name; + struct __Pyx_StructField_* fields; + size_t size; + size_t arraysize[8]; + int ndim; + char typegroup; + char is_unsigned; + int flags; +} __Pyx_TypeInfo; +typedef struct __Pyx_StructField_ { + __Pyx_TypeInfo* type; + const char* name; + size_t offset; +} __Pyx_StructField; +typedef struct { + __Pyx_StructField* field; + size_t parent_offset; +} __Pyx_BufFmt_StackElem; +typedef struct { + __Pyx_StructField root; + __Pyx_BufFmt_StackElem* head; + size_t fmt_offset; + size_t new_count, enc_count; + size_t struct_alignment; + int is_complex; + char enc_type; + char new_packmode; + char enc_packmode; + char is_valid_array; +} __Pyx_BufFmt_Context; + /*--- Type declarations ---*/ struct __pyx_array_obj; @@ -521,7 +846,7 @@ struct __pyx_MemviewEnum_obj; struct __pyx_memoryview_obj; struct __pyx_memoryviewslice_obj; -/* "View.MemoryView":99 +/* "View.MemoryView":103 * * @cname("__pyx_array") * cdef class array: # <<<<<<<<<<<<<< @@ -530,6 +855,7 @@ struct __pyx_memoryviewslice_obj; */ struct __pyx_array_obj { PyObject_HEAD + struct __pyx_vtabstruct_array *__pyx_vtab; char *data; Py_ssize_t len; char *format; @@ -545,7 +871,7 @@ struct __pyx_array_obj { }; -/* "View.MemoryView":269 +/* "View.MemoryView":277 * * @cname('__pyx_MemviewEnum') * cdef class Enum(object): # <<<<<<<<<<<<<< @@ -558,7 +884,7 @@ struct __pyx_MemviewEnum_obj { }; -/* "View.MemoryView":302 +/* "View.MemoryView":328 * * @cname('__pyx_memoryview') * cdef class memoryview(object): # <<<<<<<<<<<<<< @@ -581,7 +907,7 @@ struct __pyx_memoryview_obj { }; -/* "View.MemoryView":922 +/* "View.MemoryView":953 * * @cname('__pyx_memoryviewslice') * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< @@ -598,7 +924,21 @@ struct __pyx_memoryviewslice_obj { -/* "View.MemoryView":302 +/* "View.MemoryView":103 + * + * @cname("__pyx_array") + * cdef class array: # <<<<<<<<<<<<<< + * + * cdef: + */ + +struct __pyx_vtabstruct_array { + PyObject *(*get_memview)(struct __pyx_array_obj *); +}; +static struct __pyx_vtabstruct_array *__pyx_vtabptr_array; + + +/* "View.MemoryView":328 * * @cname('__pyx_memoryview') * cdef class memoryview(object): # <<<<<<<<<<<<<< @@ -618,7 +958,7 @@ struct __pyx_vtabstruct_memoryview { static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; -/* "View.MemoryView":922 +/* "View.MemoryView":953 * * @cname('__pyx_memoryviewslice') * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< @@ -630,6 +970,9 @@ struct __pyx_vtabstruct__memoryviewslice { struct __pyx_vtabstruct_memoryview __pyx_base; }; static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; + +/* --- Runtime support code (head) --- */ +/* Refnanny.proto */ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif @@ -646,19 +989,19 @@ static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD - #define __Pyx_RefNannySetupContext(name, acquire_gil) \ - if (acquire_gil) { \ - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ - PyGILState_Release(__pyx_gilstate_save); \ - } else { \ - __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ + if (acquire_gil) {\ + PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ + PyGILState_Release(__pyx_gilstate_save);\ + } else {\ + __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ } #else - #define __Pyx_RefNannySetupContext(name, acquire_gil) \ + #define __Pyx_RefNannySetupContext(name, acquire_gil)\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif - #define __Pyx_RefNannyFinishContext() \ + #define __Pyx_RefNannyFinishContext()\ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) @@ -681,18 +1024,19 @@ static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif -#define __Pyx_XDECREF_SET(r, v) do { \ - PyObject *tmp = (PyObject *) r; \ - r = v; __Pyx_XDECREF(tmp); \ +#define __Pyx_XDECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_XDECREF(tmp);\ } while (0) -#define __Pyx_DECREF_SET(r, v) do { \ - PyObject *tmp = (PyObject *) r; \ - r = v; __Pyx_DECREF(tmp); \ +#define __Pyx_DECREF_SET(r, v) do {\ + PyObject *tmp = (PyObject *) r;\ + r = v; __Pyx_DECREF(tmp);\ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) -#if CYTHON_COMPILING_IN_CPYTHON +/* PyObjectGetAttrStr.proto */ +#if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) @@ -707,28 +1051,29 @@ static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif +/* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); +/* RaiseArgTupleInvalid.proto */ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); +/* RaiseDoubleKeywords.proto */ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); -static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ - PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ +/* ParseKeywords.proto */ +static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ + PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ const char* function_name); -static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); -static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); - -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); - -static CYTHON_INLINE int __Pyx_PyDict_Contains(PyObject* item, PyObject* dict, int eq) { +/* PyDictContains.proto */ +static CYTHON_INLINE int __Pyx_PyDict_ContainsTF(PyObject* item, PyObject* dict, int eq) { int result = PyDict_Contains(dict, item); return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); } -#if PY_MAJOR_VERSION >= 3 +/* DictGetItem.proto */ +#if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { PyObject *value; value = PyDict_GetItemWithError(d, key); @@ -748,61 +1093,186 @@ static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) #endif +/* PyObjectCall.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); #else #define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); - -static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); - -#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ - __Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) : \ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) : \ - __Pyx_SetItemInt_Generic(o, to_py_func(i), v))) -static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); -static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, - int is_list, int wraparound, int boundscheck); - -static CYTHON_INLINE int __Pyx_IterFinish(void); - -#if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +/* PyThreadStateGet.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; +#define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; +#define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type +#else +#define __Pyx_PyThreadState_declare +#define __Pyx_PyThreadState_assign +#define __Pyx_PyErr_Occurred() PyErr_Occurred() #endif +/* PyErrFetchRestore.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) +#define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #if CYTHON_COMPILING_IN_CPYTHON -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); +#define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) #else -#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#endif +#else +#define __Pyx_PyErr_Clear() PyErr_Clear() +#define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) +#define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) +#define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) +#define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif -static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); +/* RaiseException.proto */ +static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); -static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); +/* UnicodeAsUCS4.proto */ +static CYTHON_INLINE Py_UCS4 __Pyx_PyUnicode_AsPy_UCS4(PyObject*); -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); +/* object_ord.proto */ +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyObject_Ord(c)\ + (likely(PyUnicode_Check(c)) ? (long)__Pyx_PyUnicode_AsPy_UCS4(c) : __Pyx__PyObject_Ord(c)) +#else +#define __Pyx_PyObject_Ord(c) __Pyx__PyObject_Ord(c) +#endif +static long __Pyx__PyObject_Ord(PyObject* c); + +/* IncludeStringH.proto */ +#include + +/* BytesEquals.proto */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); + +/* UnicodeEquals.proto */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); +/* StrEquals.proto */ +#if PY_MAJOR_VERSION >= 3 +#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals +#else +#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals +#endif + +/* RaiseTooManyValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); +/* RaiseNeedMoreValuesToUnpack.proto */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); + +/* IterFinish.proto */ +static CYTHON_INLINE int __Pyx_IterFinish(void); + +/* UnpackItemEndCheck.proto */ static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); +/* SetItemInt.proto */ +#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) :\ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) :\ + __Pyx_SetItemInt_Generic(o, to_py_func(i), v))) +static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, + int is_list, int wraparound, int boundscheck); + +/* PyFunctionFastCall.proto */ +#if CYTHON_FAST_PYCALL +#define __Pyx_PyFunction_FastCall(func, args, nargs)\ + __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) +#if 1 || PY_VERSION_HEX < 0x030600B1 +static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, int nargs, PyObject *kwargs); +#else +#define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) +#endif +#endif + +/* PyObjectCallMethO.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); +#endif + +/* PyObjectCallNoArg.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); +#else +#define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) +#endif + +/* PyCFunctionFastCall.proto */ +#if CYTHON_FAST_PYCCALL +static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); +#else +#define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) +#endif + +/* PyObjectCallOneArg.proto */ +static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); + +/* PyObjectCallMethod0.proto */ +static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); + +/* RaiseNoneIterError.proto */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); +/* UnpackTupleError.proto */ static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); -static CYTHON_INLINE int __Pyx_unpack_tuple2(PyObject* tuple, PyObject** value1, PyObject** value2, - int is_tuple, int has_known_size, int decref_tuple); - +/* UnpackTuple2.proto */ +#define __Pyx_unpack_tuple2(tuple, value1, value2, is_tuple, has_known_size, decref_tuple)\ + (likely(is_tuple || PyTuple_Check(tuple)) ?\ + (likely(has_known_size || PyTuple_GET_SIZE(tuple) == 2) ?\ + __Pyx_unpack_tuple2_exact(tuple, value1, value2, decref_tuple) :\ + (__Pyx_UnpackTupleError(tuple, 2), -1)) :\ + __Pyx_unpack_tuple2_generic(tuple, value1, value2, has_known_size, decref_tuple)) +static CYTHON_INLINE int __Pyx_unpack_tuple2_exact( + PyObject* tuple, PyObject** value1, PyObject** value2, int decref_tuple); +static int __Pyx_unpack_tuple2_generic( + PyObject* tuple, PyObject** value1, PyObject** value2, int has_known_size, int decref_tuple); + +/* dict_iter.proto */ static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* dict, int is_dict, PyObject* method_name, Py_ssize_t* p_orig_length, int* p_is_dict); static CYTHON_INLINE int __Pyx_dict_iter_next(PyObject* dict_or_iter, Py_ssize_t orig_length, Py_ssize_t* ppos, PyObject** pkey, PyObject** pvalue, PyObject** pitem, int is_dict); -#if CYTHON_COMPILING_IN_CPYTHON +/* GetItemInt.proto */ +#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ + (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ + __Pyx_GetItemInt_Generic(o, to_py_func(i)))) +#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ + (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ + (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ + __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ + (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + int wraparound, int boundscheck); +static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, + int is_list, int wraparound, int boundscheck); + +/* ListAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); @@ -818,10 +1288,7 @@ static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { #define __Pyx_PyList_Append(L,x) PyList_Append(L,x) #endif -static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, - __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); -static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); - +/* MemviewSliceInit.proto */ #define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d #define __Pyx_MEMVIEW_DIRECT 1 #define __Pyx_MEMVIEW_PTR 2 @@ -847,68 +1314,94 @@ static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); -static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact); +/* ArgTypeTest.proto */ +#define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ + ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\ + __Pyx__ArgTypeTest(obj, type, name, exact)) +static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); -#include - -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); - -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); - -#if PY_MAJOR_VERSION >= 3 -#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals -#else -#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals -#endif - -static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); /* proto */ - -#ifndef __PYX_FORCE_INIT_THREADS - #define __PYX_FORCE_INIT_THREADS 0 -#endif +/* None.proto */ +static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); -#define UNARY_NEG_WOULD_OVERFLOW(x) (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) +/* UnaryNegOverflows.proto */ +#define UNARY_NEG_WOULD_OVERFLOW(x)\ + (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *); /*proto*/ +/* GetAttr.proto */ static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); +/* decode_c_string_utf16.proto */ +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = 0; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16LE(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = -1; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} +static CYTHON_INLINE PyObject *__Pyx_PyUnicode_DecodeUTF16BE(const char *s, Py_ssize_t size, const char *errors) { + int byteorder = 1; + return PyUnicode_DecodeUTF16(s, size, errors, &byteorder); +} + +/* decode_c_string.proto */ static CYTHON_INLINE PyObject* __Pyx_decode_c_string( const char* cstring, Py_ssize_t start, Py_ssize_t stop, const char* encoding, const char* errors, PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); +/* PyErrExceptionMatches.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) +static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); +#else +#define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) +#endif + +/* GetAttr3.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); + +/* GetModuleGlobalName.proto */ +static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); + +/* ExtTypeTest.proto */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); +/* SaveResetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); +#else +#define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) +#define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) +#endif + +/* GetException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); +#endif + +/* SwapException.proto */ +#if CYTHON_FAST_THREAD_STATE +#define __Pyx_ExceptionSwap(type, value, tb) __Pyx__ExceptionSwap(__pyx_tstate, type, value, tb) +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); +#else static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); +#endif -#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ - __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ - (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ - __Pyx_GetItemInt_Generic(o, to_py_func(i)))) -#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ - __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ - (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ - (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ - __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ - (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, - int is_list, int wraparound, int boundscheck); +/* Import.proto */ +static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ -static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ -#if CYTHON_COMPILING_IN_CPYTHON +/* ListCompAppend.proto */ +#if CYTHON_USE_PYLIST_INTERNALS && CYTHON_ASSUME_SAFE_MACROS static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); @@ -924,12 +1417,15 @@ static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { #define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) #endif -static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ +/* PyIntBinop.proto */ +#if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace); +#else +#define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace)\ + (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) +#endif + +/* ListExtend.proto */ static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { #if CYTHON_COMPILING_IN_CPYTHON PyObject* none = _PyList_Extend((PyListObject*)L, v); @@ -942,31 +1438,45 @@ static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { #endif } +/* None.proto */ static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); -static CYTHON_INLINE long __Pyx_div_long(long, long); /* proto */ +/* None.proto */ +static CYTHON_INLINE long __Pyx_div_long(long, long); -static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ +/* WriteUnraisableException.proto */ static void __Pyx_WriteUnraisable(const char *name, int clineno, int lineno, const char *filename, - int full_traceback); + int full_traceback, int nogil); + +/* ImportFrom.proto */ +static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); +/* HasAttr.proto */ +static CYTHON_INLINE int __Pyx_HasAttr(PyObject *, PyObject *); + +/* SetVTable.proto */ static int __Pyx_SetVtable(PyObject *dict, void *vtable); +/* SetupReduce.proto */ +static int __Pyx_setup_reduce(PyObject* type_obj); + +/* FetchCommonType.proto */ static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); +/* CythonFunction.proto */ #define __Pyx_CyFunction_USED 1 #include #define __Pyx_CYFUNCTION_STATICMETHOD 0x01 #define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 #define __Pyx_CYFUNCTION_CCLASS 0x04 -#define __Pyx_CyFunction_GetClosure(f) \ +#define __Pyx_CyFunction_GetClosure(f)\ (((__pyx_CyFunctionObject *) (f))->func_closure) -#define __Pyx_CyFunction_GetClassObj(f) \ +#define __Pyx_CyFunction_GetClassObj(f)\ (((__pyx_CyFunctionObject *) (f))->func_classobj) -#define __Pyx_CyFunction_Defaults(type, f) \ +#define __Pyx_CyFunction_Defaults(type, f)\ ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) -#define __Pyx_CyFunction_SetDefaultsGetter(f, g) \ +#define __Pyx_CyFunction_SetDefaultsGetter(f, g)\ ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) typedef struct { PyCFunctionObject func; @@ -990,7 +1500,7 @@ typedef struct { PyObject *func_annotations; } __pyx_CyFunctionObject; static PyTypeObject *__pyx_CyFunctionType = 0; -#define __Pyx_CyFunction_NewEx(ml, flags, qualname, self, module, globals, code) \ +#define __Pyx_CyFunction_NewEx(ml, flags, qualname, self, module, globals, code)\ __Pyx_CyFunction_New(__pyx_CyFunctionType, ml, flags, qualname, self, module, globals, code) static PyObject *__Pyx_CyFunction_New(PyTypeObject *, PyMethodDef *ml, int flags, PyObject* qualname, @@ -1006,15 +1516,16 @@ static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, PyObject *dict); static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, PyObject *dict); -static int __Pyx_CyFunction_init(void); +static int __pyx_CyFunction_init(void); +/* FusedFunction.proto */ typedef struct { __pyx_CyFunctionObject func; PyObject *__signatures__; PyObject *type; PyObject *self; } __pyx_FusedFunctionObject; -#define __pyx_FusedFunction_NewEx(ml, flags, qualname, self, module, globals, code) \ +#define __pyx_FusedFunction_NewEx(ml, flags, qualname, self, module, globals, code)\ __pyx_FusedFunction_New(__pyx_FusedFunctionType, ml, flags, qualname, self, module, globals, code) static PyObject *__pyx_FusedFunction_New(PyTypeObject *type, PyMethodDef *ml, int flags, @@ -1026,9 +1537,17 @@ static PyTypeObject *__pyx_FusedFunctionType = NULL; static int __pyx_FusedFunction_init(void); #define __Pyx_FusedFunction_USED +/* CLineInTraceback.proto */ +#ifdef CYTHON_CLINE_IN_TRACEBACK +#define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) +#else +static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); +#endif + +/* CodeObjectCache.proto */ typedef struct { - int code_line; PyCodeObject* code_object; + int code_line; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; @@ -1040,11 +1559,57 @@ static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int co static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); +/* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); +#if PY_MAJOR_VERSION < 3 + static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); + static void __Pyx_ReleaseBuffer(Py_buffer *view); +#else + #define __Pyx_GetBuffer PyObject_GetBuffer + #define __Pyx_ReleaseBuffer PyBuffer_Release +#endif + + +/* BufferStructDeclare.proto */ +typedef struct { + Py_ssize_t shape, strides, suboffsets; +} __Pyx_Buf_DimInfo; +typedef struct { + size_t refcount; + Py_buffer pybuffer; +} __Pyx_Buffer; +typedef struct { + __Pyx_Buffer *rcbuffer; + char *data; + __Pyx_Buf_DimInfo diminfo[8]; +} __Pyx_LocalBuf_ND; + +/* MemviewSliceIsContig.proto */ +static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim); + +/* OverlappingSlices.proto */ +static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize); + +/* Capsule.proto */ +static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); + +/* IsLittleEndian.proto */ +static CYTHON_INLINE int __Pyx_Is_Little_Endian(void); + +/* BufferFormatCheck.proto */ +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); +static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type); + +/* TypeInfoCompare.proto */ static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); +/* MemviewSliceValidateAndInit.proto */ static int __Pyx_ValidateAndInit_memviewslice( int *axes_specs, int c_or_f_flag, @@ -1055,82 +1620,81 @@ static int __Pyx_ValidateAndInit_memviewslice( __Pyx_memviewslice *memviewslice, PyObject *original_obj); +/* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_short(PyObject *); +/* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int(PyObject *); +/* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_long(PyObject *); +/* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_PY_LONG_LONG(PyObject *); +/* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_char(PyObject *); +/* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_char(PyObject *); +/* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_int(PyObject *); -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); - -typedef struct { - Py_ssize_t shape, strides, suboffsets; -} __Pyx_Buf_DimInfo; -typedef struct { - size_t refcount; - Py_buffer pybuffer; -} __Pyx_Buffer; -typedef struct { - __Pyx_Buffer *rcbuffer; - char *data; - __Pyx_Buf_DimInfo diminfo[8]; -} __Pyx_LocalBuf_ND; - -#if PY_MAJOR_VERSION < 3 - static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); - static void __Pyx_ReleaseBuffer(Py_buffer *view); -#else - #define __Pyx_GetBuffer PyObject_GetBuffer - #define __Pyx_ReleaseBuffer PyBuffer_Release -#endif - - -static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; -static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; - +/* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_double(PyObject *); +/* ObjectToMemviewSlice.proto */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_double(PyObject *); +/* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); -static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); - -static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character); - -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); - +/* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); -static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, - char order, int ndim); - -static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, - __Pyx_memviewslice *slice2, - int ndim, size_t itemsize); - +/* MemviewSliceCopyTemplate.proto */ static __Pyx_memviewslice __pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, const char *mode, int ndim, size_t sizeof_dtype, int contig_flag, int dtype_is_object); -static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); +/* BytesContains.proto */ +static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character); +/* CIntFromPy.proto */ +static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); + +/* ImportNumPyArray.proto */ +static PyObject *__pyx_numpy_ndarray = NULL; +static PyObject* __Pyx_ImportNumPyArrayTypeIfAvailable(void); + +/* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); +/* CIntFromPy.proto */ +static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); + +/* FastTypeChecks.proto */ +#if CYTHON_COMPILING_IN_CPYTHON +#define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); +#else +#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) +#define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) +#define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) +#endif + +/* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); +/* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); +static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self); /* proto*/ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto*/ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj); /* proto*/ static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src); /* proto*/ @@ -1155,6 +1719,8 @@ static PyObject *strided = 0; static PyObject *indirect = 0; static PyObject *contiguous = 0; static PyObject *indirect_contiguous = 0; +static int __pyx_memoryview_thread_locks_used; +static PyThread_type_lock __pyx_memoryview_thread_locks[8]; static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ static void *__pyx_align_pointer(void *, size_t); /*proto*/ static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ @@ -1187,6 +1753,7 @@ static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ +static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *, PyObject *); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_short = { "short", NULL, sizeof(short), { 0 }, 0, IS_UNSIGNED(short) ? 'U' : 'I', IS_UNSIGNED(short), 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_long = { "long", NULL, sizeof(long), { 0 }, 0, IS_UNSIGNED(long) ? 'U' : 'I', IS_UNSIGNED(long), 0 }; @@ -1196,15 +1763,13 @@ static __Pyx_TypeInfo __Pyx_TypeInfo_char = { "char", NULL, sizeof(char), { 0 }, static __Pyx_TypeInfo __Pyx_TypeInfo_unsigned_int = { "unsigned int", NULL, sizeof(unsigned int), { 0 }, 0, IS_UNSIGNED(unsigned int) ? 'U' : 'I', IS_UNSIGNED(unsigned int), 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; #define __Pyx_MODULE_NAME "utils" +extern int __pyx_module_is_main_utils; int __pyx_module_is_main_utils = 0; /* Implementation of 'utils' */ -static PyObject *__pyx_builtin_ImportError; -static PyObject *__pyx_builtin_AttributeError; static PyObject *__pyx_builtin_TypeError; -static PyObject *__pyx_builtin_ord; static PyObject *__pyx_builtin_zip; -static PyObject *__pyx_builtin_xrange; +static PyObject *__pyx_builtin_reversed; static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_MemoryError; @@ -1212,173 +1777,140 @@ static PyObject *__pyx_builtin_enumerate; static PyObject *__pyx_builtin_Ellipsis; static PyObject *__pyx_builtin_id; static PyObject *__pyx_builtin_IndexError; -static PyObject *__pyx_pf_5utils_crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults); /* proto */ -static PyObject *__pyx_pf_5utils_4crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ -static PyObject *__pyx_pf_5utils_6crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ -static PyObject *__pyx_pf_5utils_8crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ -static PyObject *__pyx_pf_5utils_10crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ -static PyObject *__pyx_pf_5utils_12crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ -static PyObject *__pyx_pf_5utils_14crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ -static PyObject *__pyx_pf_5utils_16crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ -static PyObject *__pyx_pf_5utils_2loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults); /* proto */ -static PyObject *__pyx_pf_5utils_20loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ -static PyObject *__pyx_pf_5utils_22loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ -static PyObject *__pyx_pf_5utils_24loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ -static PyObject *__pyx_pf_5utils_26loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ -static PyObject *__pyx_pf_5utils_28loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ -static PyObject *__pyx_pf_5utils_30loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ -static PyObject *__pyx_pf_5utils_32loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ -static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ -static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ -static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ -static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ -static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ -static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ -static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ -static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ -static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ -static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ -static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ -static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ -static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ -static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ -static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ -static char __pyx_k_[] = "()"; -static char __pyx_k_O[] = "O"; -static char __pyx_k_X[] = "X"; -static char __pyx_k_Y[] = "Y"; -static char __pyx_k_c[] = "c"; -static char __pyx_k_i[] = "i"; -static char __pyx_k_j[] = "j"; -static char __pyx_k_s[] = "s"; -static char __pyx_k_y[] = "y"; -static char __pyx_k__3[] = "|"; -static char __pyx_k_id[] = "id"; -static char __pyx_k_int[] = "int"; -static char __pyx_k_obj[] = "obj"; -static char __pyx_k_ord[] = "ord"; -static char __pyx_k_out[] = "out"; -static char __pyx_k_zip[] = "zip"; -static char __pyx_k_args[] = "args"; -static char __pyx_k_base[] = "base"; -static char __pyx_k_char[] = "char"; -static char __pyx_k_kind[] = "kind"; -static char __pyx_k_long[] = "long"; -static char __pyx_k_main[] = "__main__"; -static char __pyx_k_mode[] = "mode"; -static char __pyx_k_name[] = "name"; -static char __pyx_k_ndim[] = "ndim"; -static char __pyx_k_pack[] = "pack"; -static char __pyx_k_size[] = "size"; -static char __pyx_k_step[] = "step"; -static char __pyx_k_stop[] = "stop"; -static char __pyx_k_test[] = "__test__"; -static char __pyx_k_class[] = "__class__"; -static char __pyx_k_dtype[] = "dtype"; -static char __pyx_k_error[] = "error"; -static char __pyx_k_flags[] = "flags"; -static char __pyx_k_numpy[] = "numpy"; -static char __pyx_k_range[] = "range"; -static char __pyx_k_shape[] = "shape"; -static char __pyx_k_short[] = "short"; -static char __pyx_k_split[] = "split"; -static char __pyx_k_start[] = "start"; -static char __pyx_k_strip[] = "strip"; -static char __pyx_k_utils[] = "utils"; -static char __pyx_k_format[] = "format"; -static char __pyx_k_import[] = "__import__"; -static char __pyx_k_kwargs[] = "kwargs"; -static char __pyx_k_name_2[] = "__name__"; -static char __pyx_k_struct[] = "struct"; -static char __pyx_k_unpack[] = "unpack"; -static char __pyx_k_xrange[] = "xrange"; -static char __pyx_k_fortran[] = "fortran"; -static char __pyx_k_memview[] = "memview"; -static char __pyx_k_ndarray[] = "ndarray"; -static char __pyx_k_Ellipsis[] = "Ellipsis"; -static char __pyx_k_defaults[] = "defaults"; -static char __pyx_k_itemsize[] = "itemsize"; -static char __pyx_k_n_states[] = "n_states"; -static char __pyx_k_TypeError[] = "TypeError"; -static char __pyx_k_enumerate[] = "enumerate"; -static char __pyx_k_long_long[] = "long long"; -static char __pyx_k_IndexError[] = "IndexError"; -static char __pyx_k_ValueError[] = "ValueError"; -static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; -static char __pyx_k_signatures[] = "signatures"; -static char __pyx_k_ImportError[] = "ImportError"; -static char __pyx_k_MemoryError[] = "MemoryError"; -static char __pyx_k_class_weight[] = "class_weight"; -static char __pyx_k_unsigned_int[] = "unsigned int"; -static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; -static char __pyx_k_unsigned_char[] = "unsigned char"; -static char __pyx_k_AttributeError[] = "AttributeError"; -static char __pyx_k_allocate_buffer[] = "allocate_buffer"; -static char __pyx_k_dtype_is_object[] = "dtype_is_object"; -static char __pyx_k_unary_potentials[] = "unary_potentials"; -static char __pyx_k_strided_and_direct[] = ""; -static char __pyx_k_loss_augment_unaries[] = "loss_augment_unaries"; -static char __pyx_k_strided_and_indirect[] = ""; -static char __pyx_k_contiguous_and_direct[] = ""; -static char __pyx_k_MemoryView_of_r_object[] = ""; -static char __pyx_k_MemoryView_of_r_at_0x_x[] = ""; -static char __pyx_k_contiguous_and_indirect[] = ""; -static char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; -static char __pyx_k_getbuffer_obj_view_flags[] = "getbuffer(obj, view, flags)"; -static char __pyx_k_Dimension_d_is_not_direct[] = "Dimension %d is not direct"; -static char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; -static char __pyx_k_Index_out_of_bounds_axis_d[] = "Index out of bounds (axis %d)"; -static char __pyx_k_No_matching_signature_found[] = "No matching signature found"; -static char __pyx_k_Step_may_not_be_zero_axis_d[] = "Step may not be zero (axis %d)"; -static char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; -static char __pyx_k_crammer_singer_joint_feature[] = "crammer_singer_joint_feature"; -static char __pyx_k_Expected_at_least_d_arguments[] = "Expected at least %d arguments"; -static char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; -static char __pyx_k_strided_and_direct_or_indirect[] = ""; -static char __pyx_k_home_andy_checkout_pystruct_blu[] = "/home/andy/checkout/pystruct_blub/src/utils.pyx"; -static char __pyx_k_All_dimensions_preceding_dimensi[] = "All dimensions preceding dimension %d must be indexed and not sliced"; -static char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; -static char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; -static char __pyx_k_Cannot_transpose_memoryview_with[] = "Cannot transpose memoryview with indirect dimensions"; -static char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; -static char __pyx_k_Function_call_with_ambiguous_arg[] = "Function call with ambiguous argument types"; -static char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; -static char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; -static char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; -static char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; -static char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; -static char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; +static const char __pyx_k_[] = "<"; +static const char __pyx_k_O[] = "O"; +static const char __pyx_k_X[] = "X"; +static const char __pyx_k_Y[] = "Y"; +static const char __pyx_k_c[] = "c"; +static const char __pyx_k_i[] = "i"; +static const char __pyx_k_j[] = "j"; +static const char __pyx_k_s[] = "s"; +static const char __pyx_k_y[] = "y"; +static const char __pyx_k__2[] = ">"; +static const char __pyx_k__3[] = "()"; +static const char __pyx_k__5[] = "|"; +static const char __pyx_k_id[] = "id"; +static const char __pyx_k_int[] = "int"; +static const char __pyx_k_new[] = "__new__"; +static const char __pyx_k_obj[] = "obj"; +static const char __pyx_k_out[] = "out"; +static const char __pyx_k_zip[] = "zip"; +static const char __pyx_k_args[] = "args"; +static const char __pyx_k_base[] = "base"; +static const char __pyx_k_char[] = "char"; +static const char __pyx_k_dict[] = "__dict__"; +static const char __pyx_k_kind[] = "kind"; +static const char __pyx_k_long[] = "long"; +static const char __pyx_k_main[] = "__main__"; +static const char __pyx_k_mode[] = "mode"; +static const char __pyx_k_name[] = "name"; +static const char __pyx_k_ndim[] = "ndim"; +static const char __pyx_k_pack[] = "pack"; +static const char __pyx_k_size[] = "size"; +static const char __pyx_k_step[] = "step"; +static const char __pyx_k_stop[] = "stop"; +static const char __pyx_k_test[] = "__test__"; +static const char __pyx_k_ASCII[] = "ASCII"; +static const char __pyx_k_class[] = "__class__"; +static const char __pyx_k_dtype[] = "dtype"; +static const char __pyx_k_error[] = "error"; +static const char __pyx_k_flags[] = "flags"; +static const char __pyx_k_numpy[] = "numpy"; +static const char __pyx_k_range[] = "range"; +static const char __pyx_k_shape[] = "shape"; +static const char __pyx_k_short[] = "short"; +static const char __pyx_k_split[] = "split"; +static const char __pyx_k_start[] = "start"; +static const char __pyx_k_strip[] = "strip"; +static const char __pyx_k_utils[] = "utils"; +static const char __pyx_k_encode[] = "encode"; +static const char __pyx_k_format[] = "format"; +static const char __pyx_k_import[] = "__import__"; +static const char __pyx_k_kwargs[] = "kwargs"; +static const char __pyx_k_name_2[] = "__name__"; +static const char __pyx_k_pickle[] = "pickle"; +static const char __pyx_k_reduce[] = "__reduce__"; +static const char __pyx_k_struct[] = "struct"; +static const char __pyx_k_unpack[] = "unpack"; +static const char __pyx_k_update[] = "update"; +static const char __pyx_k_fortran[] = "fortran"; +static const char __pyx_k_memview[] = "memview"; +static const char __pyx_k_strides[] = "strides"; +static const char __pyx_k_Ellipsis[] = "Ellipsis"; +static const char __pyx_k_defaults[] = "defaults"; +static const char __pyx_k_getstate[] = "__getstate__"; +static const char __pyx_k_itemsize[] = "itemsize"; +static const char __pyx_k_n_states[] = "n_states"; +static const char __pyx_k_pyx_type[] = "__pyx_type"; +static const char __pyx_k_reversed[] = "reversed"; +static const char __pyx_k_setstate[] = "__setstate__"; +static const char __pyx_k_TypeError[] = "TypeError"; +static const char __pyx_k_byteorder[] = "byteorder"; +static const char __pyx_k_enumerate[] = "enumerate"; +static const char __pyx_k_long_long[] = "long long"; +static const char __pyx_k_pyx_state[] = "__pyx_state"; +static const char __pyx_k_reduce_ex[] = "__reduce_ex__"; +static const char __pyx_k_utils_pyx[] = "utils.pyx"; +static const char __pyx_k_IndexError[] = "IndexError"; +static const char __pyx_k_ValueError[] = "ValueError"; +static const char __pyx_k_pyx_result[] = "__pyx_result"; +static const char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; +static const char __pyx_k_signatures[] = "signatures"; +static const char __pyx_k_MemoryError[] = "MemoryError"; +static const char __pyx_k_PickleError[] = "PickleError"; +static const char __pyx_k_class_weight[] = "class_weight"; +static const char __pyx_k_f_contiguous[] = "f_contiguous"; +static const char __pyx_k_pyx_checksum[] = "__pyx_checksum"; +static const char __pyx_k_stringsource[] = "stringsource"; +static const char __pyx_k_unsigned_int[] = "unsigned int"; +static const char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; +static const char __pyx_k_reduce_cython[] = "__reduce_cython__"; +static const char __pyx_k_unsigned_char[] = "unsigned char"; +static const char __pyx_k_View_MemoryView[] = "View.MemoryView"; +static const char __pyx_k_allocate_buffer[] = "allocate_buffer"; +static const char __pyx_k_dtype_is_object[] = "dtype_is_object"; +static const char __pyx_k_pyx_PickleError[] = "__pyx_PickleError"; +static const char __pyx_k_setstate_cython[] = "__setstate_cython__"; +static const char __pyx_k_unary_potentials[] = "unary_potentials"; +static const char __pyx_k_pyx_unpickle_Enum[] = "__pyx_unpickle_Enum"; +static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; +static const char __pyx_k_strided_and_direct[] = ""; +static const char __pyx_k_loss_augment_unaries[] = "loss_augment_unaries"; +static const char __pyx_k_strided_and_indirect[] = ""; +static const char __pyx_k_contiguous_and_direct[] = ""; +static const char __pyx_k_MemoryView_of_r_object[] = ""; +static const char __pyx_k_MemoryView_of_r_at_0x_x[] = ""; +static const char __pyx_k_contiguous_and_indirect[] = ""; +static const char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; +static const char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; +static const char __pyx_k_No_matching_signature_found[] = "No matching signature found"; +static const char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; +static const char __pyx_k_crammer_singer_joint_feature[] = "crammer_singer_joint_feature"; +static const char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; +static const char __pyx_k_strided_and_direct_or_indirect[] = ""; +static const char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; +static const char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; +static const char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; +static const char __pyx_k_Expected_at_least_d_argument_s_g[] = "Expected at least %d argument%s, got %d"; +static const char __pyx_k_Function_call_with_ambiguous_arg[] = "Function call with ambiguous argument types"; +static const char __pyx_k_Incompatible_checksums_s_vs_0xb0[] = "Incompatible checksums (%s vs 0xb068931 = (name))"; +static const char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; +static const char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; +static const char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; +static const char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; +static const char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; +static const char __pyx_k_no_default___reduce___due_to_non[] = "no default __reduce__ due to non-trivial __cinit__"; +static const char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; static PyObject *__pyx_kp_s_; -static PyObject *__pyx_n_s_AttributeError; +static PyObject *__pyx_n_s_ASCII; static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri; static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is; static PyObject *__pyx_kp_s_Cannot_index_with_type_s; static PyObject *__pyx_n_s_Ellipsis; static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; -static PyObject *__pyx_kp_s_Expected_at_least_d_arguments; +static PyObject *__pyx_kp_s_Expected_at_least_d_argument_s_g; static PyObject *__pyx_kp_s_Function_call_with_ambiguous_arg; -static PyObject *__pyx_n_s_ImportError; +static PyObject *__pyx_kp_s_Incompatible_checksums_s_vs_0xb0; static PyObject *__pyx_n_s_IndexError; static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; @@ -1389,34 +1921,43 @@ static PyObject *__pyx_kp_s_MemoryView_of_r_object; static PyObject *__pyx_kp_s_No_matching_signature_found; static PyObject *__pyx_n_b_O; static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; +static PyObject *__pyx_n_s_PickleError; static PyObject *__pyx_n_s_TypeError; static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; static PyObject *__pyx_n_s_ValueError; +static PyObject *__pyx_n_s_View_MemoryView; static PyObject *__pyx_n_s_X; static PyObject *__pyx_n_s_Y; +static PyObject *__pyx_kp_s__2; static PyObject *__pyx_kp_s__3; +static PyObject *__pyx_kp_s__5; static PyObject *__pyx_n_s_allocate_buffer; static PyObject *__pyx_n_s_args; static PyObject *__pyx_n_s_base; +static PyObject *__pyx_n_s_byteorder; static PyObject *__pyx_n_s_c; static PyObject *__pyx_n_u_c; static PyObject *__pyx_n_s_char; static PyObject *__pyx_n_s_class; static PyObject *__pyx_n_s_class_weight; +static PyObject *__pyx_n_s_cline_in_traceback; static PyObject *__pyx_kp_s_contiguous_and_direct; static PyObject *__pyx_kp_s_contiguous_and_indirect; static PyObject *__pyx_n_s_crammer_singer_joint_feature; static PyObject *__pyx_n_s_defaults; +static PyObject *__pyx_n_s_dict; static PyObject *__pyx_n_s_dtype; static PyObject *__pyx_n_s_dtype_is_object; +static PyObject *__pyx_n_s_encode; static PyObject *__pyx_n_s_enumerate; static PyObject *__pyx_n_s_error; +static PyObject *__pyx_n_s_f_contiguous; static PyObject *__pyx_n_s_flags; static PyObject *__pyx_n_s_format; static PyObject *__pyx_n_s_fortran; static PyObject *__pyx_n_u_fortran; +static PyObject *__pyx_n_s_getstate; static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; -static PyObject *__pyx_kp_s_home_andy_checkout_pystruct_blu; static PyObject *__pyx_n_s_i; static PyObject *__pyx_n_s_id; static PyObject *__pyx_n_s_import; @@ -1435,17 +1976,30 @@ static PyObject *__pyx_n_s_mode; static PyObject *__pyx_n_s_n_states; static PyObject *__pyx_n_s_name; static PyObject *__pyx_n_s_name_2; -static PyObject *__pyx_n_s_ndarray; static PyObject *__pyx_n_s_ndim; +static PyObject *__pyx_n_s_new; +static PyObject *__pyx_kp_s_no_default___reduce___due_to_non; static PyObject *__pyx_n_s_numpy; static PyObject *__pyx_n_s_obj; -static PyObject *__pyx_n_s_ord; static PyObject *__pyx_n_s_out; static PyObject *__pyx_n_s_pack; +static PyObject *__pyx_n_s_pickle; +static PyObject *__pyx_n_s_pyx_PickleError; +static PyObject *__pyx_n_s_pyx_checksum; static PyObject *__pyx_n_s_pyx_getbuffer; +static PyObject *__pyx_n_s_pyx_result; +static PyObject *__pyx_n_s_pyx_state; +static PyObject *__pyx_n_s_pyx_type; +static PyObject *__pyx_n_s_pyx_unpickle_Enum; static PyObject *__pyx_n_s_pyx_vtable; static PyObject *__pyx_n_s_range; +static PyObject *__pyx_n_s_reduce; +static PyObject *__pyx_n_s_reduce_cython; +static PyObject *__pyx_n_s_reduce_ex; +static PyObject *__pyx_n_s_reversed; static PyObject *__pyx_n_s_s; +static PyObject *__pyx_n_s_setstate; +static PyObject *__pyx_n_s_setstate_cython; static PyObject *__pyx_n_s_shape; static PyObject *__pyx_n_s_short; static PyObject *__pyx_n_s_signatures; @@ -1457,6 +2011,8 @@ static PyObject *__pyx_n_s_stop; static PyObject *__pyx_kp_s_strided_and_direct; static PyObject *__pyx_kp_s_strided_and_direct_or_indirect; static PyObject *__pyx_kp_s_strided_and_indirect; +static PyObject *__pyx_n_s_strides; +static PyObject *__pyx_kp_s_stringsource; static PyObject *__pyx_n_s_strip; static PyObject *__pyx_n_s_struct; static PyObject *__pyx_n_s_test; @@ -1466,23 +2022,86 @@ static PyObject *__pyx_n_s_unary_potentials; static PyObject *__pyx_n_s_unpack; static PyObject *__pyx_kp_s_unsigned_char; static PyObject *__pyx_kp_s_unsigned_int; +static PyObject *__pyx_n_s_update; static PyObject *__pyx_n_s_utils; -static PyObject *__pyx_n_s_xrange; +static PyObject *__pyx_kp_s_utils_pyx; static PyObject *__pyx_n_s_y; static PyObject *__pyx_n_s_zip; +static PyObject *__pyx_pf_5utils_crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults); /* proto */ +static PyObject *__pyx_pf_5utils_4crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ +static PyObject *__pyx_pf_5utils_6crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ +static PyObject *__pyx_pf_5utils_8crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ +static PyObject *__pyx_pf_5utils_10crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ +static PyObject *__pyx_pf_5utils_12crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ +static PyObject *__pyx_pf_5utils_14crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ +static PyObject *__pyx_pf_5utils_16crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X, __Pyx_memviewslice __pyx_v_Y, __Pyx_memviewslice __pyx_v_out); /* proto */ +static PyObject *__pyx_pf_5utils_2loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults); /* proto */ +static PyObject *__pyx_pf_5utils_20loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ +static PyObject *__pyx_pf_5utils_22loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ +static PyObject *__pyx_pf_5utils_24loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ +static PyObject *__pyx_pf_5utils_26loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ +static PyObject *__pyx_pf_5utils_28loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ +static PyObject *__pyx_pf_5utils_30loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ +static PyObject *__pyx_pf_5utils_32loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_unary_potentials, __Pyx_memviewslice __pyx_v_y, __Pyx_memviewslice __pyx_v_class_weight); /* proto */ +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ +static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ +static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ +static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state); /* proto */ +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ +static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ +static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state); /* proto */ +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ +static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; +static PyObject *__pyx_int_3; +static PyObject *__pyx_int_184977713; static PyObject *__pyx_int_neg_1; -static PyObject *__pyx_tuple__2; static PyObject *__pyx_tuple__4; -static PyObject *__pyx_tuple__5; static PyObject *__pyx_tuple__6; static PyObject *__pyx_tuple__7; static PyObject *__pyx_tuple__8; static PyObject *__pyx_tuple__9; -static PyObject *__pyx_slice__18; -static PyObject *__pyx_slice__19; -static PyObject *__pyx_slice__20; +static PyObject *__pyx_slice__26; +static PyObject *__pyx_slice__27; +static PyObject *__pyx_slice__28; static PyObject *__pyx_tuple__10; static PyObject *__pyx_tuple__11; static PyObject *__pyx_tuple__12; @@ -1491,23 +2110,35 @@ static PyObject *__pyx_tuple__14; static PyObject *__pyx_tuple__15; static PyObject *__pyx_tuple__16; static PyObject *__pyx_tuple__17; +static PyObject *__pyx_tuple__18; +static PyObject *__pyx_tuple__19; +static PyObject *__pyx_tuple__20; static PyObject *__pyx_tuple__21; static PyObject *__pyx_tuple__22; +static PyObject *__pyx_tuple__23; static PyObject *__pyx_tuple__24; -static PyObject *__pyx_tuple__26; -static PyObject *__pyx_tuple__27; -static PyObject *__pyx_tuple__28; +static PyObject *__pyx_tuple__25; static PyObject *__pyx_tuple__29; static PyObject *__pyx_tuple__30; -static PyObject *__pyx_codeobj__23; -static PyObject *__pyx_codeobj__25; +static PyObject *__pyx_tuple__31; +static PyObject *__pyx_tuple__32; +static PyObject *__pyx_tuple__34; +static PyObject *__pyx_tuple__36; +static PyObject *__pyx_tuple__37; +static PyObject *__pyx_tuple__38; +static PyObject *__pyx_tuple__39; +static PyObject *__pyx_tuple__40; +static PyObject *__pyx_tuple__41; +static PyObject *__pyx_codeobj__33; +static PyObject *__pyx_codeobj__35; +static PyObject *__pyx_codeobj__42; /* "utils.pyx":14 * cython.uint * * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): # <<<<<<<<<<<<<< * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): */ /* Python wrapper */ @@ -1518,9 +2149,6 @@ static PyObject *__pyx_pw_5utils_1crammer_singer_joint_feature(PyObject *__pyx_s PyObject *__pyx_v_args = 0; PyObject *__pyx_v_kwargs = 0; CYTHON_UNUSED PyObject *__pyx_v_defaults = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__pyx_fused_cpdef (wrapper)", 0); @@ -1532,9 +2160,13 @@ static PyObject *__pyx_pw_5utils_1crammer_singer_joint_feature(PyObject *__pyx_s const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -1543,24 +2175,27 @@ static PyObject *__pyx_pw_5utils_1crammer_singer_joint_feature(PyObject *__pyx_s case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_signatures)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_args)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 1); __PYX_ERR(0, 14, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kwargs)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 2); __PYX_ERR(0, 14, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_defaults)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 3); __PYX_ERR(0, 14, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_fused_cpdef") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_fused_cpdef") < 0)) __PYX_ERR(0, 14, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { goto __pyx_L5_argtuple_error; @@ -1577,7 +2212,7 @@ static PyObject *__pyx_pw_5utils_1crammer_singer_joint_feature(PyObject *__pyx_s } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 14, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -1592,817 +2227,879 @@ static PyObject *__pyx_pw_5utils_1crammer_singer_joint_feature(PyObject *__pyx_s static PyObject *__pyx_pf_5utils_crammer_singer_joint_feature(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults) { PyObject *__pyx_v_dest_sig = NULL; - PyObject *__pyx_v_ndarray = 0; - PyObject *__pyx_v_numpy = NULL; + Py_ssize_t __pyx_v_i; + PyTypeObject *__pyx_v_ndarray = 0; __Pyx_memviewslice __pyx_v_memslice; Py_ssize_t __pyx_v_itemsize; int __pyx_v_dtype_signed; char __pyx_v_kind; + int __pyx_v_arg_is_pythran_compatible; + int __pyx_v_short_is_signed; + int __pyx_v_int_is_signed; int __pyx_v_long_is_signed; int __pyx_v_long_long_is_signed; int __pyx_v_unsigned_char_is_signed; int __pyx_v_char_is_signed; int __pyx_v_unsigned_int_is_signed; - int __pyx_v_short_is_signed; - int __pyx_v_int_is_signed; PyObject *__pyx_v_arg = NULL; PyObject *__pyx_v_dtype = NULL; PyObject *__pyx_v_arg_base = NULL; + PyObject *__pyx_v_byteorder = NULL; + PyObject *__pyx_v_cur_stride = NULL; + PyObject *__pyx_v_dim = NULL; + PyObject *__pyx_v_stride = NULL; PyObject *__pyx_v_candidates = NULL; PyObject *__pyx_v_sig = NULL; int __pyx_v_match_found; - PyObject *__pyx_v_src_type = NULL; + PyObject *__pyx_v_src_sig = NULL; PyObject *__pyx_v_dst_type = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; + long __pyx_t_7; + int __pyx_t_8; PyObject *__pyx_t_9 = NULL; - Py_ssize_t __pyx_t_10; - char __pyx_t_11; - Py_ssize_t __pyx_t_12; - int __pyx_t_13; - Py_ssize_t __pyx_t_14; - PyObject *(*__pyx_t_15)(PyObject *); - PyObject *__pyx_t_16 = NULL; - PyObject *__pyx_t_17 = NULL; - PyObject *__pyx_t_18 = NULL; - PyObject *(*__pyx_t_19)(PyObject *); - int __pyx_t_20; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; + PyObject *(*__pyx_t_10)(PyObject *); + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + PyObject *(*__pyx_t_13)(PyObject *); + __Pyx_memviewslice __pyx_t_14; + Py_ssize_t __pyx_t_15; + int __pyx_t_16; + Py_ssize_t __pyx_t_17; + Py_ssize_t __pyx_t_18; + int __pyx_t_19; __Pyx_RefNannySetupContext("crammer_singer_joint_feature", 0); __Pyx_INCREF(__pyx_v_kwargs); - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(Py_None); - PyList_SET_ITEM(__pyx_t_1, 0, Py_None); __Pyx_GIVEREF(Py_None); + PyList_SET_ITEM(__pyx_t_1, 0, Py_None); __pyx_v_dest_sig = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_2 = (__pyx_v_kwargs == Py_None); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_kwargs, __pyx_t_1); - __pyx_t_1 = 0; - goto __pyx_L3; + __pyx_t_3 = (__pyx_v_kwargs != Py_None); + __pyx_t_4 = (__pyx_t_3 != 0); + if (__pyx_t_4) { + } else { + __pyx_t_2 = __pyx_t_4; + goto __pyx_L4_bool_binop_done; } - __pyx_L3:; - { - __Pyx_ExceptionSave(&__pyx_t_4, &__pyx_t_5, &__pyx_t_6); - __Pyx_XGOTREF(__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_5); - __Pyx_XGOTREF(__pyx_t_6); - /*try:*/ { - __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L4_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_numpy = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_numpy, __pyx_n_s_ndarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L4_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(PyType_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "type", Py_TYPE(__pyx_t_1)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L4_error;} - __pyx_v_ndarray = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - } - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - goto __pyx_L11_try_end; - __pyx_L4_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_7 = PyErr_ExceptionMatches(__pyx_builtin_ImportError) || PyErr_ExceptionMatches(__pyx_builtin_AttributeError) || PyErr_ExceptionMatches(__pyx_builtin_TypeError); - if (__pyx_t_7) { - __Pyx_AddTraceback("utils.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_8, &__pyx_t_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_8); - __Pyx_GOTREF(__pyx_t_9); - __Pyx_INCREF(Py_None); - __Pyx_XDECREF_SET(__pyx_v_ndarray, ((PyObject*)Py_None)); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L5_exception_handled; - } - goto __pyx_L6_except_error; - __pyx_L6_except_error:; - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_XGIVEREF(__pyx_t_6); - __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); - goto __pyx_L1_error; - __pyx_L5_exception_handled:; - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_XGIVEREF(__pyx_t_6); - __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); - __pyx_L11_try_end:; - } - __pyx_v_itemsize = -1; - __pyx_v_long_is_signed = (((long)-1) < 0); - __pyx_v_long_long_is_signed = (((PY_LONG_LONG)-1) < 0); - __pyx_v_unsigned_char_is_signed = (((unsigned char)-1) < 0); - __pyx_v_char_is_signed = (((char)-1) < 0); - __pyx_v_unsigned_int_is_signed = (((unsigned int)-1) < 0); - __pyx_v_short_is_signed = (((short)-1) < 0); - __pyx_v_int_is_signed = (((int)-1) < 0); + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_kwargs); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_t_3 = ((!__pyx_t_4) != 0); + __pyx_t_2 = __pyx_t_3; + __pyx_L4_bool_binop_done:; + if (__pyx_t_2) { + __Pyx_INCREF(Py_None); + __Pyx_DECREF_SET(__pyx_v_kwargs, Py_None); + } + __pyx_t_1 = ((PyObject *)__Pyx_ImportNumPyArrayTypeIfAvailable()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_ndarray = ((PyTypeObject*)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_v_itemsize = -1L; + __pyx_v_arg_is_pythran_compatible = 0; + __pyx_v_short_is_signed = (((short)-1L) < 0); + __pyx_v_int_is_signed = (((int)-1L) < 0); + __pyx_v_long_is_signed = (((long)-1L) < 0); + __pyx_v_long_long_is_signed = (((PY_LONG_LONG)-1L) < 0); + __pyx_v_unsigned_char_is_signed = (((unsigned char)-1L) < 0); + __pyx_v_char_is_signed = (((char)-1L) < 0); + __pyx_v_unsigned_int_is_signed = (((unsigned int)-1L) < 0); if (unlikely(__pyx_v_args == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 14, __pyx_L1_error) } - __pyx_t_10 = PyTuple_GET_SIZE(((PyObject*)__pyx_v_args)); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = ((1 < __pyx_t_10) != 0); - if (__pyx_t_3) { + __pyx_t_5 = PyTuple_GET_SIZE(((PyObject*)__pyx_v_args)); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_t_2 = ((1 < __pyx_t_5) != 0); + if (__pyx_t_2) { if (unlikely(__pyx_v_args == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 14, __pyx_L1_error) } - __pyx_t_9 = PyTuple_GET_ITEM(((PyObject*)__pyx_v_args), 1); - __Pyx_INCREF(__pyx_t_9); - __pyx_v_arg = __pyx_t_9; - __pyx_t_9 = 0; - goto __pyx_L14; + __pyx_t_1 = PyTuple_GET_ITEM(((PyObject*)__pyx_v_args), 1); + __Pyx_INCREF(__pyx_t_1); + __pyx_v_arg = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L6; + } + __pyx_t_3 = (__pyx_v_kwargs != Py_None); + __pyx_t_4 = (__pyx_t_3 != 0); + if (__pyx_t_4) { + } else { + __pyx_t_2 = __pyx_t_4; + goto __pyx_L7_bool_binop_done; } if (unlikely(__pyx_v_kwargs == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 14, __pyx_L1_error) } - __pyx_t_3 = (__Pyx_PyDict_Contains(__pyx_n_s_Y, ((PyObject*)__pyx_v_kwargs), Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = (__pyx_t_3 != 0); + __pyx_t_4 = (__Pyx_PyDict_ContainsTF(__pyx_n_s_Y, ((PyObject*)__pyx_v_kwargs), Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_t_3 = (__pyx_t_4 != 0); + __pyx_t_2 = __pyx_t_3; + __pyx_L7_bool_binop_done:; if (__pyx_t_2) { if (unlikely(__pyx_v_kwargs == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 14, __pyx_L1_error) } - __pyx_t_9 = __Pyx_PyDict_GetItem(((PyObject*)__pyx_v_kwargs), __pyx_n_s_Y); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_9); - __pyx_v_arg = __pyx_t_9; - __pyx_t_9 = 0; - goto __pyx_L14; + __pyx_t_1 = __Pyx_PyDict_GetItem(((PyObject*)__pyx_v_kwargs), __pyx_n_s_Y); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_arg = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L6; } /*else*/ { if (unlikely(__pyx_v_args == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 14, __pyx_L1_error) } - __pyx_t_10 = PyTuple_GET_SIZE(((PyObject*)__pyx_v_args)); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_9 = PyInt_FromSsize_t(__pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_8 = __Pyx_PyString_Format(__pyx_kp_s_Expected_at_least_d_arguments, __pyx_t_9); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_8); - __pyx_t_8 = 0; - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_L14:; - if (0) { - goto __pyx_L15; + __pyx_t_5 = PyTuple_GET_SIZE(((PyObject*)__pyx_v_args)); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_t_1 = PyInt_FromSsize_t(__pyx_t_5); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = PyTuple_New(3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_INCREF(__pyx_int_3); + __Pyx_GIVEREF(__pyx_int_3); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_int_3); + __Pyx_INCREF(__pyx_n_s_s); + __Pyx_GIVEREF(__pyx_n_s_s); + PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_n_s_s); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_Expected_at_least_d_argument_s_g, __pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_6, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 14, __pyx_L1_error) } - /*else*/ { - while (1) { - if (!1) break; - __pyx_t_2 = (__pyx_v_ndarray != ((PyObject*)Py_None)); + __pyx_L6:; + while (1) { + __pyx_t_2 = (__pyx_v_ndarray != ((PyTypeObject*)Py_None)); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + __pyx_t_3 = __Pyx_TypeCheck(__pyx_v_arg, __pyx_v_ndarray); + __pyx_t_2 = (__pyx_t_3 != 0); + if (__pyx_t_2) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_dtype); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_dtype = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_v_arg_is_pythran_compatible = 1; + goto __pyx_L12; + } + __pyx_t_2 = __pyx_memoryview_check(__pyx_v_arg); __pyx_t_3 = (__pyx_t_2 != 0); if (__pyx_t_3) { - __pyx_t_3 = __Pyx_TypeCheck(__pyx_v_arg, __pyx_v_ndarray); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_arg_base = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_TypeCheck(__pyx_v_arg_base, __pyx_v_ndarray); __pyx_t_2 = (__pyx_t_3 != 0); if (__pyx_t_2) { - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_v_dtype = __pyx_t_8; - __pyx_t_8 = 0; - goto __pyx_L19; - } - __pyx_t_2 = (__pyx_memoryview_check(__pyx_v_arg) != 0); - if (__pyx_t_2) { - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_base); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_v_arg_base = __pyx_t_8; - __pyx_t_8 = 0; - __pyx_t_2 = __Pyx_TypeCheck(__pyx_v_arg_base, __pyx_v_ndarray); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg_base, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_v_dtype = __pyx_t_8; - __pyx_t_8 = 0; - goto __pyx_L20; - } - /*else*/ { - __Pyx_INCREF(Py_None); - __pyx_v_dtype = Py_None; - } - __pyx_L20:; - goto __pyx_L19; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg_base, __pyx_n_s_dtype); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_dtype = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L13; } /*else*/ { __Pyx_INCREF(Py_None); __pyx_v_dtype = Py_None; } - __pyx_L19:; - __pyx_v_itemsize = -1; - __pyx_t_3 = (__pyx_v_dtype != Py_None); - __pyx_t_2 = (__pyx_t_3 != 0); + __pyx_L13:; + goto __pyx_L12; + } + /*else*/ { + __Pyx_INCREF(Py_None); + __pyx_v_dtype = Py_None; + } + __pyx_L12:; + __pyx_v_itemsize = -1L; + __pyx_t_2 = (__pyx_v_dtype != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_1); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_itemsize = __pyx_t_5; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyObject_Ord(__pyx_t_1); if (unlikely(__pyx_t_7 == ((long)(long)(Py_UCS4)-1))) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_kind = __pyx_t_7; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_byteorder); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_byteorder = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_t_2 = (__Pyx_PyString_Equals(__pyx_v_byteorder, __pyx_kp_s_, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L16_bool_binop_done; + } + __pyx_t_8 = __Pyx_Is_Little_Endian(); + __pyx_t_2 = ((!(__pyx_t_8 != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L16_bool_binop_done:; + if (__pyx_t_3) { + __pyx_v_arg_is_pythran_compatible = 0; + } + __pyx_t_2 = (__Pyx_PyString_Equals(__pyx_v_byteorder, __pyx_kp_s__2, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 14, __pyx_L1_error) if (__pyx_t_2) { - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_itemsize); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_v_itemsize = __pyx_t_10; - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; + } + __pyx_t_8 = __Pyx_Is_Little_Endian(); + __pyx_t_2 = (__pyx_t_8 != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L19_bool_binop_done:; + if (__pyx_t_3) { + __pyx_v_arg_is_pythran_compatible = 0; + } + __pyx_v_dtype_signed = (__pyx_v_kind == 'i'); + __pyx_t_3 = (__pyx_v_arg_is_pythran_compatible != 0); + if (__pyx_t_3) { + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_cur_stride = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_reversed, __pyx_t_6, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_strides); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_8); - __pyx_t_8 = 0; - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ord, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_reversed, __pyx_t_9, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_11 = __Pyx_PyInt_As_char(__pyx_t_8); if (unlikely((__pyx_t_11 == (char)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_v_kind = __pyx_t_11; - __pyx_v_dtype_signed = (__pyx_v_kind == 'i'); - switch (__pyx_v_kind) { - case 'i': - case 'u': - __pyx_t_3 = (((sizeof(short)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L23_bool_binop_done; - } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L23_bool_binop_done; - } - __pyx_t_3 = ((!((__pyx_v_short_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L23_bool_binop_done:; - if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_short, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - __pyx_t_3 = (((sizeof(int)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L27_bool_binop_done; - } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L27_bool_binop_done; - } - __pyx_t_3 = ((!((__pyx_v_int_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L27_bool_binop_done:; - if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - __pyx_t_3 = (((sizeof(long)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L31_bool_binop_done; - } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L31_bool_binop_done; - } - __pyx_t_3 = ((!((__pyx_v_long_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L31_bool_binop_done:; - if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - __pyx_t_3 = (((sizeof(PY_LONG_LONG)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L35_bool_binop_done; - } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L35_bool_binop_done; - } - __pyx_t_3 = ((!((__pyx_v_long_long_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L35_bool_binop_done:; - if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_long_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - __pyx_t_3 = (((sizeof(unsigned char)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L39_bool_binop_done; - } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); - if (__pyx_t_3) { + __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_t_6); + __pyx_t_1 = 0; + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_9, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (likely(PyList_CheckExact(__pyx_t_6)) || PyTuple_CheckExact(__pyx_t_6)) { + __pyx_t_9 = __pyx_t_6; __Pyx_INCREF(__pyx_t_9); __pyx_t_5 = 0; + __pyx_t_10 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_t_6); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = Py_TYPE(__pyx_t_9)->tp_iternext; if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 14, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + for (;;) { + if (likely(!__pyx_t_10)) { + if (likely(PyList_CheckExact(__pyx_t_9))) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_9)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_6 = PyList_GET_ITEM(__pyx_t_9, __pyx_t_5); __Pyx_INCREF(__pyx_t_6); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + #else + __pyx_t_6 = PySequence_ITEM(__pyx_t_9, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #endif + } else { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_9)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_6 = PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_5); __Pyx_INCREF(__pyx_t_6); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + #else + __pyx_t_6 = PySequence_ITEM(__pyx_t_9, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #endif + } } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L39_bool_binop_done; - } - __pyx_t_3 = ((!((__pyx_v_unsigned_char_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L39_bool_binop_done:; - if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; + __pyx_t_6 = __pyx_t_10(__pyx_t_9); + if (unlikely(!__pyx_t_6)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 14, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_6); } - __pyx_t_3 = (((sizeof(char)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { + if ((likely(PyTuple_CheckExact(__pyx_t_6))) || (PyList_CheckExact(__pyx_t_6))) { + PyObject* sequence = __pyx_t_6; + #if !CYTHON_COMPILING_IN_PYPY + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 14, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_11 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_1 = PyList_GET_ITEM(sequence, 0); + __pyx_t_11 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx_t_11); + #else + __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_11 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + #endif + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L43_bool_binop_done; + Py_ssize_t index = -1; + __pyx_t_12 = PyObject_GetIter(__pyx_t_6); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_13 = Py_TYPE(__pyx_t_12)->tp_iternext; + index = 0; __pyx_t_1 = __pyx_t_13(__pyx_t_12); if (unlikely(!__pyx_t_1)) goto __pyx_L24_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + index = 1; __pyx_t_11 = __pyx_t_13(__pyx_t_12); if (unlikely(!__pyx_t_11)) goto __pyx_L24_unpacking_failed; + __Pyx_GOTREF(__pyx_t_11); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_13(__pyx_t_12), 2) < 0) __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_t_13 = NULL; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + goto __pyx_L25_unpacking_done; + __pyx_L24_unpacking_failed:; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_t_13 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_L25_unpacking_done:; } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); + __Pyx_XDECREF_SET(__pyx_v_dim, __pyx_t_1); + __pyx_t_1 = 0; + __Pyx_XDECREF_SET(__pyx_v_stride, __pyx_t_11); + __pyx_t_11 = 0; + __pyx_t_6 = PyObject_RichCompare(__pyx_v_stride, __pyx_v_cur_stride, Py_NE); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_3 < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L43_bool_binop_done; + __pyx_v_arg_is_pythran_compatible = 0; + goto __pyx_L23_break; } - __pyx_t_3 = ((!((__pyx_v_char_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L43_bool_binop_done:; + __pyx_t_6 = PyNumber_InPlaceMultiply(__pyx_v_cur_stride, __pyx_v_dim); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF_SET(__pyx_v_cur_stride, __pyx_t_6); + __pyx_t_6 = 0; + } + /*else*/ { + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_flags); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_11 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_f_contiguous); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_11); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - __pyx_t_3 = (((sizeof(unsigned int)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L47_bool_binop_done; + __pyx_t_3 = __pyx_t_2; + goto __pyx_L28_bool_binop_done; } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L47_bool_binop_done; - } - __pyx_t_3 = ((!((__pyx_v_unsigned_int_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L47_bool_binop_done:; - if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - break; - case 'f': - break; - case 'c': - break; - case 'O': - break; - default: break; + __pyx_t_11 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_11, __pyx_int_1, Py_GT); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_3 = __pyx_t_2; + __pyx_L28_bool_binop_done:; + __pyx_v_arg_is_pythran_compatible = (!__pyx_t_3); } - goto __pyx_L21; - } - __pyx_L21:; - goto __pyx_L18; - } - __pyx_L18:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L51_bool_binop_done; - } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(short))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L51_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_short(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_short, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; + __pyx_L23_break:; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } - /*else*/ { - PyErr_Clear(); + switch (__pyx_v_kind) { + case 'i': + case 'u': + __pyx_t_2 = (((sizeof(short)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L31_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L31_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_short_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L31_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_short, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; + } + __pyx_t_2 = (((sizeof(int)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L35_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L35_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_int_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L35_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; + } + __pyx_t_2 = (((sizeof(long)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L39_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L39_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_long_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L39_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; + } + __pyx_t_2 = (((sizeof(PY_LONG_LONG)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L43_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L43_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_long_long_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L43_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_long_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; + } + __pyx_t_2 = (((sizeof(unsigned char)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L47_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L47_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_unsigned_char_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L47_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; + } + __pyx_t_2 = (((sizeof(char)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L51_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L51_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_char_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L51_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; + } + __pyx_t_2 = (((sizeof(unsigned int)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L55_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L55_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_unsigned_int_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L55_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; + } + break; + case 'f': + break; + case 'c': + break; + case 'O': + break; + default: break; } - goto __pyx_L50; - } - __pyx_L50:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L55_bool_binop_done; } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(int))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L55_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_int(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - /*else*/ { - PyErr_Clear(); - } - goto __pyx_L54; + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L59_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(short))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L59_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_short(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_short, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_L54:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L59_bool_binop_done; + /*else*/ { + PyErr_Clear(); } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(long))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L59_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_long(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - /*else*/ { - PyErr_Clear(); - } - goto __pyx_L58; + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L63_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(int))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L63_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_int(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_L58:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L63_bool_binop_done; + /*else*/ { + PyErr_Clear(); } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(PY_LONG_LONG))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L63_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_PY_LONG_LONG(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_long_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - /*else*/ { - PyErr_Clear(); - } - goto __pyx_L62; + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L67_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(long))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L67_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_long(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_L62:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L67_bool_binop_done; + /*else*/ { + PyErr_Clear(); } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(unsigned char))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L67_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_char(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - /*else*/ { - PyErr_Clear(); - } - goto __pyx_L66; + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L71_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(PY_LONG_LONG))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L71_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_PY_LONG_LONG(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_long_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_L66:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L71_bool_binop_done; + /*else*/ { + PyErr_Clear(); } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(char))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L71_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_char(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - /*else*/ { - PyErr_Clear(); - } - goto __pyx_L70; + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L75_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(unsigned char))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L75_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_char(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_L70:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L75_bool_binop_done; + /*else*/ { + PyErr_Clear(); } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(unsigned int))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L75_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_int(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - /*else*/ { - PyErr_Clear(); - } - goto __pyx_L74; + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L79_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(char))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L79_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_char(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_L74:; - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, Py_None, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - __pyx_L17_break:; - } - __pyx_L15:; - __pyx_t_8 = PyList_New(0); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_v_candidates = ((PyObject*)__pyx_t_8); - __pyx_t_8 = 0; - __pyx_t_10 = 0; - if (unlikely(__pyx_v_signatures == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*else*/ { + PyErr_Clear(); + } + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L83_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(unsigned int))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L83_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_int(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; + } + /*else*/ { + PyErr_Clear(); + } + } + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, Py_None, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_t_9 = __Pyx_dict_iterator(((PyObject*)__pyx_v_signatures), 1, ((PyObject *)NULL), (&__pyx_t_12), (&__pyx_t_7)); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L10_break:; + __pyx_t_9 = PyList_New(0); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_8); - __pyx_t_8 = __pyx_t_9; + __pyx_v_candidates = ((PyObject*)__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_5 = 0; + if (unlikely(__pyx_v_signatures == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + __PYX_ERR(0, 14, __pyx_L1_error) + } + __pyx_t_6 = __Pyx_dict_iterator(((PyObject*)__pyx_v_signatures), 1, ((PyObject *)NULL), (&__pyx_t_15), (&__pyx_t_8)); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_9); + __pyx_t_9 = __pyx_t_6; + __pyx_t_6 = 0; while (1) { - __pyx_t_13 = __Pyx_dict_iter_next(__pyx_t_8, __pyx_t_12, &__pyx_t_10, &__pyx_t_9, NULL, NULL, __pyx_t_7); - if (unlikely(__pyx_t_13 == 0)) break; - if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_XDECREF_SET(__pyx_v_sig, __pyx_t_9); - __pyx_t_9 = 0; + __pyx_t_16 = __Pyx_dict_iter_next(__pyx_t_9, __pyx_t_15, &__pyx_t_5, &__pyx_t_6, NULL, NULL, __pyx_t_8); + if (unlikely(__pyx_t_16 == 0)) break; + if (unlikely(__pyx_t_16 == -1)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_XDECREF_SET(__pyx_v_sig, __pyx_t_6); + __pyx_t_6 = 0; __pyx_v_match_found = 0; - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_sig, __pyx_n_s_strip); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_9, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_split); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_9, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_dest_sig); - PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_v_dest_sig); - __Pyx_GIVEREF(__pyx_v_dest_sig); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { - __pyx_t_9 = __pyx_t_1; __Pyx_INCREF(__pyx_t_9); __pyx_t_14 = 0; - __pyx_t_15 = NULL; - } else { - __pyx_t_14 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_15 = Py_TYPE(__pyx_t_9)->tp_iternext; if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - for (;;) { - if (likely(!__pyx_t_15)) { - if (likely(PyList_CheckExact(__pyx_t_9))) { - if (__pyx_t_14 >= PyList_GET_SIZE(__pyx_t_9)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_1 = PyList_GET_ITEM(__pyx_t_9, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_1 = PySequence_ITEM(__pyx_t_9, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - } else { - if (__pyx_t_14 >= PyTuple_GET_SIZE(__pyx_t_9)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_1 = PySequence_ITEM(__pyx_t_9, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - } - } else { - __pyx_t_1 = __pyx_t_15(__pyx_t_9); - if (unlikely(!__pyx_t_1)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - break; - } - __Pyx_GOTREF(__pyx_t_1); - } - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - #if CYTHON_COMPILING_IN_CPYTHON - Py_ssize_t size = Py_SIZE(sequence); - #else - Py_ssize_t size = PySequence_Size(sequence); - #endif - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - #if CYTHON_COMPILING_IN_CPYTHON - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_16 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_17 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_16 = PyList_GET_ITEM(sequence, 0); - __pyx_t_17 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_16); - __Pyx_INCREF(__pyx_t_17); - #else - __pyx_t_16 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_16); - __pyx_t_17 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_17); - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_18 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_18); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_19 = Py_TYPE(__pyx_t_18)->tp_iternext; - index = 0; __pyx_t_16 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_16)) goto __pyx_L82_unpacking_failed; - __Pyx_GOTREF(__pyx_t_16); - index = 1; __pyx_t_17 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_17)) goto __pyx_L82_unpacking_failed; - __Pyx_GOTREF(__pyx_t_17); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_19(__pyx_t_18), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_19 = NULL; - __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; - goto __pyx_L83_unpacking_done; - __pyx_L82_unpacking_failed:; - __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; - __pyx_t_19 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_L83_unpacking_done:; - } - __Pyx_XDECREF_SET(__pyx_v_src_type, __pyx_t_16); - __pyx_t_16 = 0; - __Pyx_XDECREF_SET(__pyx_v_dst_type, __pyx_t_17); - __pyx_t_17 = 0; - __pyx_t_2 = (__pyx_v_dst_type != Py_None); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - __pyx_t_1 = PyObject_RichCompare(__pyx_v_src_type, __pyx_v_dst_type, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_3) { + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_sig, __pyx_n_s_strip); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_11 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_11, __pyx_n_s_split); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_11 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF_SET(__pyx_v_src_sig, __pyx_t_11); + __pyx_t_11 = 0; + __pyx_t_17 = PyList_GET_SIZE(__pyx_v_dest_sig); if (unlikely(__pyx_t_17 == ((Py_ssize_t)-1))) __PYX_ERR(0, 14, __pyx_L1_error) + for (__pyx_t_18 = 0; __pyx_t_18 < __pyx_t_17; __pyx_t_18+=1) { + __pyx_v_i = __pyx_t_18; + __pyx_t_11 = PyList_GET_ITEM(__pyx_v_dest_sig, __pyx_v_i); + __Pyx_INCREF(__pyx_t_11); + __Pyx_XDECREF_SET(__pyx_v_dst_type, __pyx_t_11); + __pyx_t_11 = 0; + __pyx_t_3 = (__pyx_v_dst_type != Py_None); + __pyx_t_2 = (__pyx_t_3 != 0); + if (__pyx_t_2) { + __pyx_t_11 = __Pyx_GetItemInt(__pyx_v_src_sig, __pyx_v_i, Py_ssize_t, 1, PyInt_FromSsize_t, 0, 0, 0); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_11, __pyx_v_dst_type, Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (__pyx_t_2) { __pyx_v_match_found = 1; - goto __pyx_L85; + goto __pyx_L91; } /*else*/ { __pyx_v_match_found = 0; - goto __pyx_L81_break; + goto __pyx_L89_break; } - __pyx_L85:; - goto __pyx_L84; + __pyx_L91:; } - __pyx_L84:; } - __pyx_L81_break:; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_3 = (__pyx_v_match_found != 0); - if (__pyx_t_3) { - __pyx_t_20 = __Pyx_PyList_Append(__pyx_v_candidates, __pyx_v_sig); if (unlikely(__pyx_t_20 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L86; + __pyx_L89_break:; + __pyx_t_2 = (__pyx_v_match_found != 0); + if (__pyx_t_2) { + __pyx_t_19 = __Pyx_PyList_Append(__pyx_v_candidates, __pyx_v_sig); if (unlikely(__pyx_t_19 == ((int)-1))) __PYX_ERR(0, 14, __pyx_L1_error) } - __pyx_L86:; } - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = (__pyx_v_candidates != Py_None) && (PyList_GET_SIZE(__pyx_v_candidates) != 0); - __pyx_t_2 = ((!__pyx_t_3) != 0); - if (__pyx_t_2) { - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_12 = PyList_GET_SIZE(__pyx_v_candidates); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = ((__pyx_t_12 > 1) != 0); - if (__pyx_t_2) { - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = (__pyx_v_candidates != Py_None) && (PyList_GET_SIZE(__pyx_v_candidates) != 0); + __pyx_t_3 = ((!__pyx_t_2) != 0); + if (__pyx_t_3) { + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __PYX_ERR(0, 14, __pyx_L1_error) + } + __pyx_t_15 = PyList_GET_SIZE(__pyx_v_candidates); if (unlikely(__pyx_t_15 == ((Py_ssize_t)-1))) __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_t_3 = ((__pyx_t_15 > 1) != 0); + if (__pyx_t_3) { + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __PYX_ERR(0, 14, __pyx_L1_error) } /*else*/ { __Pyx_XDECREF(__pyx_r); if (unlikely(__pyx_v_signatures == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 14, __pyx_L1_error) } - __pyx_t_8 = __Pyx_PyDict_GetItem(((PyObject*)__pyx_v_signatures), PyList_GET_ITEM(__pyx_v_candidates, 0)); if (unlikely(__pyx_t_8 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_8); - __pyx_r = __pyx_t_8; - __pyx_t_8 = 0; + __pyx_t_9 = __Pyx_PyDict_GetItem(((PyObject*)__pyx_v_signatures), PyList_GET_ITEM(__pyx_v_candidates, 0)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_r = __pyx_t_9; + __pyx_t_9 = 0; goto __pyx_L0; } /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_16); - __Pyx_XDECREF(__pyx_t_17); - __Pyx_XDECREF(__pyx_t_18); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_XDECREF(__pyx_t_12); __Pyx_AddTraceback("utils.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_dest_sig); __Pyx_XDECREF(__pyx_v_ndarray); - __Pyx_XDECREF(__pyx_v_numpy); __Pyx_XDECREF(__pyx_v_arg); __Pyx_XDECREF(__pyx_v_dtype); __Pyx_XDECREF(__pyx_v_arg_base); + __Pyx_XDECREF(__pyx_v_byteorder); + __Pyx_XDECREF(__pyx_v_cur_stride); + __Pyx_XDECREF(__pyx_v_dim); + __Pyx_XDECREF(__pyx_v_stride); __Pyx_XDECREF(__pyx_v_candidates); __Pyx_XDECREF(__pyx_v_sig); - __Pyx_XDECREF(__pyx_v_src_type); + __Pyx_XDECREF(__pyx_v_src_sig); __Pyx_XDECREF(__pyx_v_dst_type); __Pyx_XDECREF(__pyx_v_kwargs); __Pyx_XGIVEREF(__pyx_r); @@ -2417,9 +3114,6 @@ static PyObject *__pyx_fuse_0__pyx_pw_5utils_5crammer_singer_joint_feature(PyObj __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_Y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_out = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("crammer_singer_joint_feature (wrapper)", 0); @@ -2431,8 +3125,11 @@ static PyObject *__pyx_fuse_0__pyx_pw_5utils_5crammer_singer_joint_feature(PyObj const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -2441,19 +3138,21 @@ static PyObject *__pyx_fuse_0__pyx_pw_5utils_5crammer_singer_joint_feature(PyObj case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); __PYX_ERR(0, 14, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_out)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); __PYX_ERR(0, 14, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) __PYX_ERR(0, 14, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -2462,13 +3161,13 @@ static PyObject *__pyx_fuse_0__pyx_pw_5utils_5crammer_singer_joint_feature(PyObj values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_short(values[1]); if (unlikely(!__pyx_v_Y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_short(values[1]); if (unlikely(!__pyx_v_Y.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) __PYX_ERR(0, 14, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 14, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.crammer_singer_joint_feature", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -2489,21 +3188,21 @@ static PyObject *__pyx_pf_5utils_4crammer_singer_joint_feature(CYTHON_UNUSED PyO __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; int __pyx_t_2; - int __pyx_t_3; + Py_ssize_t __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; - int __pyx_t_6; + Py_ssize_t __pyx_t_6; Py_ssize_t __pyx_t_7; - int __pyx_t_8; + Py_ssize_t __pyx_t_8; Py_ssize_t __pyx_t_9; __Pyx_RefNannySetupContext("__pyx_fuse_0crammer_singer_joint_feature", 0); /* "utils.pyx":16 * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): * cdef int y, i - * for i in xrange(X.shape[0]): # <<<<<<<<<<<<<< + * for i in range(X.shape[0]): # <<<<<<<<<<<<<< * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): */ __pyx_t_1 = (__pyx_v_X.shape[0]); for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { @@ -2511,18 +3210,18 @@ static PyObject *__pyx_pf_5utils_4crammer_singer_joint_feature(CYTHON_UNUSED PyO /* "utils.pyx":17 * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] # <<<<<<<<<<<<<< - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] */ __pyx_t_3 = __pyx_v_i; __pyx_v_y = (*((short *) ( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_3 * __pyx_v_Y.strides[0]) ))); /* "utils.pyx":18 - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] - * for j in xrange(X.shape[1]): # <<<<<<<<<<<<<< + * for j in range(X.shape[1]): # <<<<<<<<<<<<<< * out[y, j] += X[i, j] * */ @@ -2532,7 +3231,7 @@ static PyObject *__pyx_pf_5utils_4crammer_singer_joint_feature(CYTHON_UNUSED PyO /* "utils.pyx":19 * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] # <<<<<<<<<<<<<< * * def loss_augment_unaries(double[:,:] unary_potentials, some_int[:] y, double[:] class_weight): @@ -2550,7 +3249,7 @@ static PyObject *__pyx_pf_5utils_4crammer_singer_joint_feature(CYTHON_UNUSED PyO * * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): # <<<<<<<<<<<<<< * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): */ /* function exit code */ @@ -2570,9 +3269,6 @@ static PyObject *__pyx_fuse_1__pyx_pw_5utils_7crammer_singer_joint_feature(PyObj __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_Y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_out = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("crammer_singer_joint_feature (wrapper)", 0); @@ -2584,8 +3280,11 @@ static PyObject *__pyx_fuse_1__pyx_pw_5utils_7crammer_singer_joint_feature(PyObj const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -2594,19 +3293,21 @@ static PyObject *__pyx_fuse_1__pyx_pw_5utils_7crammer_singer_joint_feature(PyObj case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); __PYX_ERR(0, 14, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_out)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); __PYX_ERR(0, 14, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) __PYX_ERR(0, 14, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -2615,13 +3316,13 @@ static PyObject *__pyx_fuse_1__pyx_pw_5utils_7crammer_singer_joint_feature(PyObj values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[1]); if (unlikely(!__pyx_v_Y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[1]); if (unlikely(!__pyx_v_Y.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) __PYX_ERR(0, 14, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 14, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.crammer_singer_joint_feature", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -2642,21 +3343,21 @@ static PyObject *__pyx_pf_5utils_6crammer_singer_joint_feature(CYTHON_UNUSED PyO __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; int __pyx_t_2; - int __pyx_t_3; + Py_ssize_t __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; - int __pyx_t_6; + Py_ssize_t __pyx_t_6; Py_ssize_t __pyx_t_7; - int __pyx_t_8; + Py_ssize_t __pyx_t_8; Py_ssize_t __pyx_t_9; __Pyx_RefNannySetupContext("__pyx_fuse_1crammer_singer_joint_feature", 0); /* "utils.pyx":16 * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): * cdef int y, i - * for i in xrange(X.shape[0]): # <<<<<<<<<<<<<< + * for i in range(X.shape[0]): # <<<<<<<<<<<<<< * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): */ __pyx_t_1 = (__pyx_v_X.shape[0]); for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { @@ -2664,18 +3365,18 @@ static PyObject *__pyx_pf_5utils_6crammer_singer_joint_feature(CYTHON_UNUSED PyO /* "utils.pyx":17 * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] # <<<<<<<<<<<<<< - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] */ __pyx_t_3 = __pyx_v_i; __pyx_v_y = (*((int *) ( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_3 * __pyx_v_Y.strides[0]) ))); /* "utils.pyx":18 - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] - * for j in xrange(X.shape[1]): # <<<<<<<<<<<<<< + * for j in range(X.shape[1]): # <<<<<<<<<<<<<< * out[y, j] += X[i, j] * */ @@ -2685,7 +3386,7 @@ static PyObject *__pyx_pf_5utils_6crammer_singer_joint_feature(CYTHON_UNUSED PyO /* "utils.pyx":19 * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] # <<<<<<<<<<<<<< * * def loss_augment_unaries(double[:,:] unary_potentials, some_int[:] y, double[:] class_weight): @@ -2703,7 +3404,7 @@ static PyObject *__pyx_pf_5utils_6crammer_singer_joint_feature(CYTHON_UNUSED PyO * * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): # <<<<<<<<<<<<<< * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): */ /* function exit code */ @@ -2723,9 +3424,6 @@ static PyObject *__pyx_fuse_2__pyx_pw_5utils_9crammer_singer_joint_feature(PyObj __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_Y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_out = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("crammer_singer_joint_feature (wrapper)", 0); @@ -2737,8 +3435,11 @@ static PyObject *__pyx_fuse_2__pyx_pw_5utils_9crammer_singer_joint_feature(PyObj const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -2747,19 +3448,21 @@ static PyObject *__pyx_fuse_2__pyx_pw_5utils_9crammer_singer_joint_feature(PyObj case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); __PYX_ERR(0, 14, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_out)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); __PYX_ERR(0, 14, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) __PYX_ERR(0, 14, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -2768,13 +3471,13 @@ static PyObject *__pyx_fuse_2__pyx_pw_5utils_9crammer_singer_joint_feature(PyObj values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[1]); if (unlikely(!__pyx_v_Y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[1]); if (unlikely(!__pyx_v_Y.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) __PYX_ERR(0, 14, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 14, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.crammer_singer_joint_feature", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -2795,21 +3498,21 @@ static PyObject *__pyx_pf_5utils_8crammer_singer_joint_feature(CYTHON_UNUSED PyO __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; int __pyx_t_2; - int __pyx_t_3; + Py_ssize_t __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; - int __pyx_t_6; + Py_ssize_t __pyx_t_6; Py_ssize_t __pyx_t_7; - int __pyx_t_8; + Py_ssize_t __pyx_t_8; Py_ssize_t __pyx_t_9; __Pyx_RefNannySetupContext("__pyx_fuse_2crammer_singer_joint_feature", 0); /* "utils.pyx":16 * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): * cdef int y, i - * for i in xrange(X.shape[0]): # <<<<<<<<<<<<<< + * for i in range(X.shape[0]): # <<<<<<<<<<<<<< * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): */ __pyx_t_1 = (__pyx_v_X.shape[0]); for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { @@ -2817,18 +3520,18 @@ static PyObject *__pyx_pf_5utils_8crammer_singer_joint_feature(CYTHON_UNUSED PyO /* "utils.pyx":17 * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] # <<<<<<<<<<<<<< - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] */ __pyx_t_3 = __pyx_v_i; __pyx_v_y = (*((long *) ( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_3 * __pyx_v_Y.strides[0]) ))); /* "utils.pyx":18 - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] - * for j in xrange(X.shape[1]): # <<<<<<<<<<<<<< + * for j in range(X.shape[1]): # <<<<<<<<<<<<<< * out[y, j] += X[i, j] * */ @@ -2838,7 +3541,7 @@ static PyObject *__pyx_pf_5utils_8crammer_singer_joint_feature(CYTHON_UNUSED PyO /* "utils.pyx":19 * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] # <<<<<<<<<<<<<< * * def loss_augment_unaries(double[:,:] unary_potentials, some_int[:] y, double[:] class_weight): @@ -2856,7 +3559,7 @@ static PyObject *__pyx_pf_5utils_8crammer_singer_joint_feature(CYTHON_UNUSED PyO * * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): # <<<<<<<<<<<<<< * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): */ /* function exit code */ @@ -2876,9 +3579,6 @@ static PyObject *__pyx_fuse_3__pyx_pw_5utils_11crammer_singer_joint_feature(PyOb __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_Y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_out = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("crammer_singer_joint_feature (wrapper)", 0); @@ -2890,8 +3590,11 @@ static PyObject *__pyx_fuse_3__pyx_pw_5utils_11crammer_singer_joint_feature(PyOb const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -2900,19 +3603,21 @@ static PyObject *__pyx_fuse_3__pyx_pw_5utils_11crammer_singer_joint_feature(PyOb case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); __PYX_ERR(0, 14, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_out)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); __PYX_ERR(0, 14, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) __PYX_ERR(0, 14, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -2921,13 +3626,13 @@ static PyObject *__pyx_fuse_3__pyx_pw_5utils_11crammer_singer_joint_feature(PyOb values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_PY_LONG_LONG(values[1]); if (unlikely(!__pyx_v_Y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_PY_LONG_LONG(values[1]); if (unlikely(!__pyx_v_Y.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) __PYX_ERR(0, 14, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 14, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.crammer_singer_joint_feature", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -2948,21 +3653,21 @@ static PyObject *__pyx_pf_5utils_10crammer_singer_joint_feature(CYTHON_UNUSED Py __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; int __pyx_t_2; - int __pyx_t_3; + Py_ssize_t __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; - int __pyx_t_6; + Py_ssize_t __pyx_t_6; Py_ssize_t __pyx_t_7; - int __pyx_t_8; + Py_ssize_t __pyx_t_8; Py_ssize_t __pyx_t_9; __Pyx_RefNannySetupContext("__pyx_fuse_3crammer_singer_joint_feature", 0); /* "utils.pyx":16 * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): * cdef int y, i - * for i in xrange(X.shape[0]): # <<<<<<<<<<<<<< + * for i in range(X.shape[0]): # <<<<<<<<<<<<<< * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): */ __pyx_t_1 = (__pyx_v_X.shape[0]); for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { @@ -2970,18 +3675,18 @@ static PyObject *__pyx_pf_5utils_10crammer_singer_joint_feature(CYTHON_UNUSED Py /* "utils.pyx":17 * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] # <<<<<<<<<<<<<< - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] */ __pyx_t_3 = __pyx_v_i; __pyx_v_y = (*((PY_LONG_LONG *) ( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_3 * __pyx_v_Y.strides[0]) ))); /* "utils.pyx":18 - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] - * for j in xrange(X.shape[1]): # <<<<<<<<<<<<<< + * for j in range(X.shape[1]): # <<<<<<<<<<<<<< * out[y, j] += X[i, j] * */ @@ -2991,7 +3696,7 @@ static PyObject *__pyx_pf_5utils_10crammer_singer_joint_feature(CYTHON_UNUSED Py /* "utils.pyx":19 * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] # <<<<<<<<<<<<<< * * def loss_augment_unaries(double[:,:] unary_potentials, some_int[:] y, double[:] class_weight): @@ -3009,7 +3714,7 @@ static PyObject *__pyx_pf_5utils_10crammer_singer_joint_feature(CYTHON_UNUSED Py * * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): # <<<<<<<<<<<<<< * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): */ /* function exit code */ @@ -3029,9 +3734,6 @@ static PyObject *__pyx_fuse_4__pyx_pw_5utils_13crammer_singer_joint_feature(PyOb __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_Y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_out = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("crammer_singer_joint_feature (wrapper)", 0); @@ -3043,8 +3745,11 @@ static PyObject *__pyx_fuse_4__pyx_pw_5utils_13crammer_singer_joint_feature(PyOb const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -3053,19 +3758,21 @@ static PyObject *__pyx_fuse_4__pyx_pw_5utils_13crammer_singer_joint_feature(PyOb case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); __PYX_ERR(0, 14, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_out)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); __PYX_ERR(0, 14, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) __PYX_ERR(0, 14, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -3074,13 +3781,13 @@ static PyObject *__pyx_fuse_4__pyx_pw_5utils_13crammer_singer_joint_feature(PyOb values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_char(values[1]); if (unlikely(!__pyx_v_Y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_char(values[1]); if (unlikely(!__pyx_v_Y.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) __PYX_ERR(0, 14, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 14, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.crammer_singer_joint_feature", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -3101,21 +3808,21 @@ static PyObject *__pyx_pf_5utils_12crammer_singer_joint_feature(CYTHON_UNUSED Py __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; int __pyx_t_2; - int __pyx_t_3; + Py_ssize_t __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; - int __pyx_t_6; + Py_ssize_t __pyx_t_6; Py_ssize_t __pyx_t_7; - int __pyx_t_8; + Py_ssize_t __pyx_t_8; Py_ssize_t __pyx_t_9; __Pyx_RefNannySetupContext("__pyx_fuse_4crammer_singer_joint_feature", 0); /* "utils.pyx":16 * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): * cdef int y, i - * for i in xrange(X.shape[0]): # <<<<<<<<<<<<<< + * for i in range(X.shape[0]): # <<<<<<<<<<<<<< * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): */ __pyx_t_1 = (__pyx_v_X.shape[0]); for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { @@ -3123,18 +3830,18 @@ static PyObject *__pyx_pf_5utils_12crammer_singer_joint_feature(CYTHON_UNUSED Py /* "utils.pyx":17 * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] # <<<<<<<<<<<<<< - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] */ __pyx_t_3 = __pyx_v_i; __pyx_v_y = (*((unsigned char *) ( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_3 * __pyx_v_Y.strides[0]) ))); /* "utils.pyx":18 - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] - * for j in xrange(X.shape[1]): # <<<<<<<<<<<<<< + * for j in range(X.shape[1]): # <<<<<<<<<<<<<< * out[y, j] += X[i, j] * */ @@ -3144,7 +3851,7 @@ static PyObject *__pyx_pf_5utils_12crammer_singer_joint_feature(CYTHON_UNUSED Py /* "utils.pyx":19 * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] # <<<<<<<<<<<<<< * * def loss_augment_unaries(double[:,:] unary_potentials, some_int[:] y, double[:] class_weight): @@ -3162,7 +3869,7 @@ static PyObject *__pyx_pf_5utils_12crammer_singer_joint_feature(CYTHON_UNUSED Py * * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): # <<<<<<<<<<<<<< * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): */ /* function exit code */ @@ -3182,9 +3889,6 @@ static PyObject *__pyx_fuse_5__pyx_pw_5utils_15crammer_singer_joint_feature(PyOb __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_Y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_out = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("crammer_singer_joint_feature (wrapper)", 0); @@ -3196,8 +3900,11 @@ static PyObject *__pyx_fuse_5__pyx_pw_5utils_15crammer_singer_joint_feature(PyOb const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -3206,19 +3913,21 @@ static PyObject *__pyx_fuse_5__pyx_pw_5utils_15crammer_singer_joint_feature(PyOb case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); __PYX_ERR(0, 14, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_out)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); __PYX_ERR(0, 14, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) __PYX_ERR(0, 14, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -3227,13 +3936,13 @@ static PyObject *__pyx_fuse_5__pyx_pw_5utils_15crammer_singer_joint_feature(PyOb values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_char(values[1]); if (unlikely(!__pyx_v_Y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_char(values[1]); if (unlikely(!__pyx_v_Y.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) __PYX_ERR(0, 14, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 14, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.crammer_singer_joint_feature", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -3254,21 +3963,21 @@ static PyObject *__pyx_pf_5utils_14crammer_singer_joint_feature(CYTHON_UNUSED Py __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; int __pyx_t_2; - int __pyx_t_3; + Py_ssize_t __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; - int __pyx_t_6; + Py_ssize_t __pyx_t_6; Py_ssize_t __pyx_t_7; - int __pyx_t_8; + Py_ssize_t __pyx_t_8; Py_ssize_t __pyx_t_9; __Pyx_RefNannySetupContext("__pyx_fuse_5crammer_singer_joint_feature", 0); /* "utils.pyx":16 * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): * cdef int y, i - * for i in xrange(X.shape[0]): # <<<<<<<<<<<<<< + * for i in range(X.shape[0]): # <<<<<<<<<<<<<< * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): */ __pyx_t_1 = (__pyx_v_X.shape[0]); for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { @@ -3276,18 +3985,18 @@ static PyObject *__pyx_pf_5utils_14crammer_singer_joint_feature(CYTHON_UNUSED Py /* "utils.pyx":17 * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] # <<<<<<<<<<<<<< - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] */ __pyx_t_3 = __pyx_v_i; __pyx_v_y = (*((char *) ( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_3 * __pyx_v_Y.strides[0]) ))); /* "utils.pyx":18 - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] - * for j in xrange(X.shape[1]): # <<<<<<<<<<<<<< + * for j in range(X.shape[1]): # <<<<<<<<<<<<<< * out[y, j] += X[i, j] * */ @@ -3297,7 +4006,7 @@ static PyObject *__pyx_pf_5utils_14crammer_singer_joint_feature(CYTHON_UNUSED Py /* "utils.pyx":19 * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] # <<<<<<<<<<<<<< * * def loss_augment_unaries(double[:,:] unary_potentials, some_int[:] y, double[:] class_weight): @@ -3315,7 +4024,7 @@ static PyObject *__pyx_pf_5utils_14crammer_singer_joint_feature(CYTHON_UNUSED Py * * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): # <<<<<<<<<<<<<< * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): */ /* function exit code */ @@ -3335,9 +4044,6 @@ static PyObject *__pyx_fuse_6__pyx_pw_5utils_17crammer_singer_joint_feature(PyOb __Pyx_memviewslice __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_Y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_out = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("crammer_singer_joint_feature (wrapper)", 0); @@ -3349,8 +4055,11 @@ static PyObject *__pyx_fuse_6__pyx_pw_5utils_17crammer_singer_joint_feature(PyOb const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -3359,19 +4068,21 @@ static PyObject *__pyx_fuse_6__pyx_pw_5utils_17crammer_singer_joint_feature(PyOb case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 1); __PYX_ERR(0, 14, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_out)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, 2); __PYX_ERR(0, 14, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "crammer_singer_joint_feature") < 0)) __PYX_ERR(0, 14, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -3380,13 +4091,13 @@ static PyObject *__pyx_fuse_6__pyx_pw_5utils_17crammer_singer_joint_feature(PyOb values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_int(values[1]); if (unlikely(!__pyx_v_Y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_int(values[1]); if (unlikely(!__pyx_v_Y.memview)) __PYX_ERR(0, 14, __pyx_L3_error) + __pyx_v_out = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_out.memview)) __PYX_ERR(0, 14, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("crammer_singer_joint_feature", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 14, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.crammer_singer_joint_feature", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -3407,21 +4118,21 @@ static PyObject *__pyx_pf_5utils_16crammer_singer_joint_feature(CYTHON_UNUSED Py __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; int __pyx_t_2; - int __pyx_t_3; + Py_ssize_t __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; - int __pyx_t_6; + Py_ssize_t __pyx_t_6; Py_ssize_t __pyx_t_7; - int __pyx_t_8; + Py_ssize_t __pyx_t_8; Py_ssize_t __pyx_t_9; __Pyx_RefNannySetupContext("__pyx_fuse_6crammer_singer_joint_feature", 0); /* "utils.pyx":16 * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): * cdef int y, i - * for i in xrange(X.shape[0]): # <<<<<<<<<<<<<< + * for i in range(X.shape[0]): # <<<<<<<<<<<<<< * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): */ __pyx_t_1 = (__pyx_v_X.shape[0]); for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { @@ -3429,18 +4140,18 @@ static PyObject *__pyx_pf_5utils_16crammer_singer_joint_feature(CYTHON_UNUSED Py /* "utils.pyx":17 * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] # <<<<<<<<<<<<<< - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] */ __pyx_t_3 = __pyx_v_i; __pyx_v_y = (*((unsigned int *) ( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_3 * __pyx_v_Y.strides[0]) ))); /* "utils.pyx":18 - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): * y = Y[i] - * for j in xrange(X.shape[1]): # <<<<<<<<<<<<<< + * for j in range(X.shape[1]): # <<<<<<<<<<<<<< * out[y, j] += X[i, j] * */ @@ -3450,7 +4161,7 @@ static PyObject *__pyx_pf_5utils_16crammer_singer_joint_feature(CYTHON_UNUSED Py /* "utils.pyx":19 * y = Y[i] - * for j in xrange(X.shape[1]): + * for j in range(X.shape[1]): * out[y, j] += X[i, j] # <<<<<<<<<<<<<< * * def loss_augment_unaries(double[:,:] unary_potentials, some_int[:] y, double[:] class_weight): @@ -3468,7 +4179,7 @@ static PyObject *__pyx_pf_5utils_16crammer_singer_joint_feature(CYTHON_UNUSED Py * * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): # <<<<<<<<<<<<<< * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): */ /* function exit code */ @@ -3497,9 +4208,6 @@ static PyObject *__pyx_pw_5utils_3loss_augment_unaries(PyObject *__pyx_self, PyO PyObject *__pyx_v_args = 0; PyObject *__pyx_v_kwargs = 0; CYTHON_UNUSED PyObject *__pyx_v_defaults = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__pyx_fused_cpdef (wrapper)", 0); @@ -3511,9 +4219,13 @@ static PyObject *__pyx_pw_5utils_3loss_augment_unaries(PyObject *__pyx_self, PyO const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -3522,24 +4234,27 @@ static PyObject *__pyx_pw_5utils_3loss_augment_unaries(PyObject *__pyx_self, PyO case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_signatures)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_args)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 1); __PYX_ERR(0, 21, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kwargs)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 2); __PYX_ERR(0, 21, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_defaults)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 3); __PYX_ERR(0, 21, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_fused_cpdef") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_fused_cpdef") < 0)) __PYX_ERR(0, 21, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { goto __pyx_L5_argtuple_error; @@ -3556,7 +4271,7 @@ static PyObject *__pyx_pw_5utils_3loss_augment_unaries(PyObject *__pyx_self, PyO } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 21, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -3571,817 +4286,879 @@ static PyObject *__pyx_pw_5utils_3loss_augment_unaries(PyObject *__pyx_self, PyO static PyObject *__pyx_pf_5utils_2loss_augment_unaries(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults) { PyObject *__pyx_v_dest_sig = NULL; - PyObject *__pyx_v_ndarray = 0; - PyObject *__pyx_v_numpy = NULL; + Py_ssize_t __pyx_v_i; + PyTypeObject *__pyx_v_ndarray = 0; __Pyx_memviewslice __pyx_v_memslice; Py_ssize_t __pyx_v_itemsize; int __pyx_v_dtype_signed; char __pyx_v_kind; + int __pyx_v_arg_is_pythran_compatible; + int __pyx_v_short_is_signed; + int __pyx_v_int_is_signed; + int __pyx_v_long_is_signed; int __pyx_v_long_long_is_signed; int __pyx_v_unsigned_char_is_signed; int __pyx_v_char_is_signed; int __pyx_v_unsigned_int_is_signed; - int __pyx_v_int_is_signed; - int __pyx_v_short_is_signed; - int __pyx_v_long_is_signed; PyObject *__pyx_v_arg = NULL; PyObject *__pyx_v_dtype = NULL; PyObject *__pyx_v_arg_base = NULL; + PyObject *__pyx_v_byteorder = NULL; + PyObject *__pyx_v_cur_stride = NULL; + PyObject *__pyx_v_dim = NULL; + PyObject *__pyx_v_stride = NULL; PyObject *__pyx_v_candidates = NULL; PyObject *__pyx_v_sig = NULL; int __pyx_v_match_found; - PyObject *__pyx_v_src_type = NULL; + PyObject *__pyx_v_src_sig = NULL; PyObject *__pyx_v_dst_type = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - PyObject *__pyx_t_5 = NULL; + int __pyx_t_4; + Py_ssize_t __pyx_t_5; PyObject *__pyx_t_6 = NULL; - int __pyx_t_7; - PyObject *__pyx_t_8 = NULL; + long __pyx_t_7; + int __pyx_t_8; PyObject *__pyx_t_9 = NULL; - Py_ssize_t __pyx_t_10; - char __pyx_t_11; - Py_ssize_t __pyx_t_12; - int __pyx_t_13; - Py_ssize_t __pyx_t_14; - PyObject *(*__pyx_t_15)(PyObject *); - PyObject *__pyx_t_16 = NULL; - PyObject *__pyx_t_17 = NULL; - PyObject *__pyx_t_18 = NULL; - PyObject *(*__pyx_t_19)(PyObject *); - int __pyx_t_20; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; + PyObject *(*__pyx_t_10)(PyObject *); + PyObject *__pyx_t_11 = NULL; + PyObject *__pyx_t_12 = NULL; + PyObject *(*__pyx_t_13)(PyObject *); + __Pyx_memviewslice __pyx_t_14; + Py_ssize_t __pyx_t_15; + int __pyx_t_16; + Py_ssize_t __pyx_t_17; + Py_ssize_t __pyx_t_18; + int __pyx_t_19; __Pyx_RefNannySetupContext("loss_augment_unaries", 0); __Pyx_INCREF(__pyx_v_kwargs); - __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(Py_None); - PyList_SET_ITEM(__pyx_t_1, 0, Py_None); __Pyx_GIVEREF(Py_None); + PyList_SET_ITEM(__pyx_t_1, 0, Py_None); __pyx_v_dest_sig = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_2 = (__pyx_v_kwargs == Py_None); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF_SET(__pyx_v_kwargs, __pyx_t_1); - __pyx_t_1 = 0; - goto __pyx_L3; + __pyx_t_3 = (__pyx_v_kwargs != Py_None); + __pyx_t_4 = (__pyx_t_3 != 0); + if (__pyx_t_4) { + } else { + __pyx_t_2 = __pyx_t_4; + goto __pyx_L4_bool_binop_done; } - __pyx_L3:; - { - __Pyx_ExceptionSave(&__pyx_t_4, &__pyx_t_5, &__pyx_t_6); - __Pyx_XGOTREF(__pyx_t_4); - __Pyx_XGOTREF(__pyx_t_5); - __Pyx_XGOTREF(__pyx_t_6); - /*try:*/ { - __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L4_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_v_numpy = __pyx_t_1; - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_numpy, __pyx_n_s_ndarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L4_error;} - __Pyx_GOTREF(__pyx_t_1); - if (!(likely(PyType_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "type", Py_TYPE(__pyx_t_1)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L4_error;} - __pyx_v_ndarray = ((PyObject*)__pyx_t_1); - __pyx_t_1 = 0; - } - __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; - __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; - goto __pyx_L11_try_end; - __pyx_L4_error:; - __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_7 = PyErr_ExceptionMatches(__pyx_builtin_ImportError) || PyErr_ExceptionMatches(__pyx_builtin_AttributeError) || PyErr_ExceptionMatches(__pyx_builtin_TypeError); - if (__pyx_t_7) { - __Pyx_AddTraceback("utils.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_8, &__pyx_t_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_GOTREF(__pyx_t_8); - __Pyx_GOTREF(__pyx_t_9); - __Pyx_INCREF(Py_None); - __Pyx_XDECREF_SET(__pyx_v_ndarray, ((PyObject*)Py_None)); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - goto __pyx_L5_exception_handled; - } - goto __pyx_L6_except_error; - __pyx_L6_except_error:; - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_XGIVEREF(__pyx_t_6); - __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); - goto __pyx_L1_error; - __pyx_L5_exception_handled:; - __Pyx_XGIVEREF(__pyx_t_4); - __Pyx_XGIVEREF(__pyx_t_5); - __Pyx_XGIVEREF(__pyx_t_6); - __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); - __pyx_L11_try_end:; - } - __pyx_v_itemsize = -1; - __pyx_v_long_long_is_signed = (((PY_LONG_LONG)-1) < 0); - __pyx_v_unsigned_char_is_signed = (((unsigned char)-1) < 0); - __pyx_v_char_is_signed = (((char)-1) < 0); - __pyx_v_unsigned_int_is_signed = (((unsigned int)-1) < 0); - __pyx_v_int_is_signed = (((int)-1) < 0); - __pyx_v_short_is_signed = (((short)-1) < 0); - __pyx_v_long_is_signed = (((long)-1) < 0); + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_kwargs); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + __pyx_t_3 = ((!__pyx_t_4) != 0); + __pyx_t_2 = __pyx_t_3; + __pyx_L4_bool_binop_done:; + if (__pyx_t_2) { + __Pyx_INCREF(Py_None); + __Pyx_DECREF_SET(__pyx_v_kwargs, Py_None); + } + __pyx_t_1 = ((PyObject *)__Pyx_ImportNumPyArrayTypeIfAvailable()); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_ndarray = ((PyTypeObject*)__pyx_t_1); + __pyx_t_1 = 0; + __pyx_v_itemsize = -1L; + __pyx_v_arg_is_pythran_compatible = 0; + __pyx_v_short_is_signed = (((short)-1L) < 0); + __pyx_v_int_is_signed = (((int)-1L) < 0); + __pyx_v_long_is_signed = (((long)-1L) < 0); + __pyx_v_long_long_is_signed = (((PY_LONG_LONG)-1L) < 0); + __pyx_v_unsigned_char_is_signed = (((unsigned char)-1L) < 0); + __pyx_v_char_is_signed = (((char)-1L) < 0); + __pyx_v_unsigned_int_is_signed = (((unsigned int)-1L) < 0); if (unlikely(__pyx_v_args == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 21, __pyx_L1_error) } - __pyx_t_10 = PyTuple_GET_SIZE(((PyObject*)__pyx_v_args)); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = ((1 < __pyx_t_10) != 0); - if (__pyx_t_3) { + __pyx_t_5 = PyTuple_GET_SIZE(((PyObject*)__pyx_v_args)); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 21, __pyx_L1_error) + __pyx_t_2 = ((1 < __pyx_t_5) != 0); + if (__pyx_t_2) { if (unlikely(__pyx_v_args == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 21, __pyx_L1_error) } - __pyx_t_9 = PyTuple_GET_ITEM(((PyObject*)__pyx_v_args), 1); - __Pyx_INCREF(__pyx_t_9); - __pyx_v_arg = __pyx_t_9; - __pyx_t_9 = 0; - goto __pyx_L14; + __pyx_t_1 = PyTuple_GET_ITEM(((PyObject*)__pyx_v_args), 1); + __Pyx_INCREF(__pyx_t_1); + __pyx_v_arg = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L6; + } + __pyx_t_3 = (__pyx_v_kwargs != Py_None); + __pyx_t_4 = (__pyx_t_3 != 0); + if (__pyx_t_4) { + } else { + __pyx_t_2 = __pyx_t_4; + goto __pyx_L7_bool_binop_done; } if (unlikely(__pyx_v_kwargs == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 21, __pyx_L1_error) } - __pyx_t_3 = (__Pyx_PyDict_Contains(__pyx_n_s_y, ((PyObject*)__pyx_v_kwargs), Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = (__pyx_t_3 != 0); + __pyx_t_4 = (__Pyx_PyDict_ContainsTF(__pyx_n_s_y, ((PyObject*)__pyx_v_kwargs), Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + __pyx_t_3 = (__pyx_t_4 != 0); + __pyx_t_2 = __pyx_t_3; + __pyx_L7_bool_binop_done:; if (__pyx_t_2) { if (unlikely(__pyx_v_kwargs == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 21, __pyx_L1_error) } - __pyx_t_9 = __Pyx_PyDict_GetItem(((PyObject*)__pyx_v_kwargs), __pyx_n_s_y); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_9); - __pyx_v_arg = __pyx_t_9; - __pyx_t_9 = 0; - goto __pyx_L14; + __pyx_t_1 = __Pyx_PyDict_GetItem(((PyObject*)__pyx_v_kwargs), __pyx_n_s_y); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_arg = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L6; } /*else*/ { if (unlikely(__pyx_v_args == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 21, __pyx_L1_error) } - __pyx_t_10 = PyTuple_GET_SIZE(((PyObject*)__pyx_v_args)); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_9 = PyInt_FromSsize_t(__pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_8 = __Pyx_PyString_Format(__pyx_kp_s_Expected_at_least_d_arguments, __pyx_t_9); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_8); - __pyx_t_8 = 0; - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_L14:; - if (0) { - goto __pyx_L15; - } - /*else*/ { - while (1) { - if (!1) break; - __pyx_t_2 = (__pyx_v_ndarray != ((PyObject*)Py_None)); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - __pyx_t_3 = __Pyx_TypeCheck(__pyx_v_arg, __pyx_v_ndarray); - __pyx_t_2 = (__pyx_t_3 != 0); - if (__pyx_t_2) { - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_v_dtype = __pyx_t_8; - __pyx_t_8 = 0; - goto __pyx_L19; - } - __pyx_t_2 = (__pyx_memoryview_check(__pyx_v_arg) != 0); + __pyx_t_5 = PyTuple_GET_SIZE(((PyObject*)__pyx_v_args)); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(0, 21, __pyx_L1_error) + __pyx_t_1 = PyInt_FromSsize_t(__pyx_t_5); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = PyTuple_New(3); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_INCREF(__pyx_int_3); + __Pyx_GIVEREF(__pyx_int_3); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_int_3); + __Pyx_INCREF(__pyx_n_s_s); + __Pyx_GIVEREF(__pyx_n_s_s); + PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_n_s_s); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_6, 2, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_Expected_at_least_d_argument_s_g, __pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_6, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(0, 21, __pyx_L1_error) + } + __pyx_L6:; + while (1) { + __pyx_t_2 = (__pyx_v_ndarray != ((PyTypeObject*)Py_None)); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + __pyx_t_3 = __Pyx_TypeCheck(__pyx_v_arg, __pyx_v_ndarray); + __pyx_t_2 = (__pyx_t_3 != 0); + if (__pyx_t_2) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_dtype); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_dtype = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_v_arg_is_pythran_compatible = 1; + goto __pyx_L12; + } + __pyx_t_2 = __pyx_memoryview_check(__pyx_v_arg); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_arg_base = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_t_3 = __Pyx_TypeCheck(__pyx_v_arg_base, __pyx_v_ndarray); + __pyx_t_2 = (__pyx_t_3 != 0); if (__pyx_t_2) { - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_base); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_v_arg_base = __pyx_t_8; - __pyx_t_8 = 0; - __pyx_t_2 = __Pyx_TypeCheck(__pyx_v_arg_base, __pyx_v_ndarray); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg_base, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_v_dtype = __pyx_t_8; - __pyx_t_8 = 0; - goto __pyx_L20; - } - /*else*/ { - __Pyx_INCREF(Py_None); - __pyx_v_dtype = Py_None; - } - __pyx_L20:; - goto __pyx_L19; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg_base, __pyx_n_s_dtype); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_dtype = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L13; } /*else*/ { __Pyx_INCREF(Py_None); __pyx_v_dtype = Py_None; } - __pyx_L19:; - __pyx_v_itemsize = -1; - __pyx_t_3 = (__pyx_v_dtype != Py_None); - __pyx_t_2 = (__pyx_t_3 != 0); + __pyx_L13:; + goto __pyx_L12; + } + /*else*/ { + __Pyx_INCREF(Py_None); + __pyx_v_dtype = Py_None; + } + __pyx_L12:; + __pyx_v_itemsize = -1L; + __pyx_t_2 = (__pyx_v_dtype != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_1); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_itemsize = __pyx_t_5; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_7 = __Pyx_PyObject_Ord(__pyx_t_1); if (unlikely(__pyx_t_7 == ((long)(long)(Py_UCS4)-1))) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __pyx_v_kind = __pyx_t_7; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_byteorder); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_byteorder = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_t_2 = (__Pyx_PyString_Equals(__pyx_v_byteorder, __pyx_kp_s_, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 21, __pyx_L1_error) if (__pyx_t_2) { - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_itemsize); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_v_itemsize = __pyx_t_10; - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L16_bool_binop_done; + } + __pyx_t_8 = __Pyx_Is_Little_Endian(); + __pyx_t_2 = ((!(__pyx_t_8 != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L16_bool_binop_done:; + if (__pyx_t_3) { + __pyx_v_arg_is_pythran_compatible = 0; + } + __pyx_t_2 = (__Pyx_PyString_Equals(__pyx_v_byteorder, __pyx_kp_s__2, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L19_bool_binop_done; + } + __pyx_t_8 = __Pyx_Is_Little_Endian(); + __pyx_t_2 = (__pyx_t_8 != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L19_bool_binop_done:; + if (__pyx_t_3) { + __pyx_v_arg_is_pythran_compatible = 0; + } + __pyx_v_dtype_signed = (__pyx_v_kind == 'i'); + __pyx_t_3 = (__pyx_v_arg_is_pythran_compatible != 0); + if (__pyx_t_3) { + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v_cur_stride = __pyx_t_1; + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_shape); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_6 = PyTuple_New(1); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_1); + __pyx_t_1 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_reversed, __pyx_t_6, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_strides); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); - __Pyx_GIVEREF(__pyx_t_8); - __pyx_t_8 = 0; - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ord, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_reversed, __pyx_t_9, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_11 = __Pyx_PyInt_As_char(__pyx_t_8); if (unlikely((__pyx_t_11 == (char)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_v_kind = __pyx_t_11; - __pyx_v_dtype_signed = (__pyx_v_kind == 'i'); - switch (__pyx_v_kind) { - case 'i': - case 'u': - __pyx_t_3 = (((sizeof(short)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L23_bool_binop_done; - } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L23_bool_binop_done; - } - __pyx_t_3 = ((!((__pyx_v_short_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L23_bool_binop_done:; - if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_short, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - __pyx_t_3 = (((sizeof(int)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L27_bool_binop_done; - } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L27_bool_binop_done; - } - __pyx_t_3 = ((!((__pyx_v_int_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L27_bool_binop_done:; - if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - __pyx_t_3 = (((sizeof(long)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L31_bool_binop_done; - } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L31_bool_binop_done; - } - __pyx_t_3 = ((!((__pyx_v_long_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L31_bool_binop_done:; - if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - __pyx_t_3 = (((sizeof(PY_LONG_LONG)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L35_bool_binop_done; - } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L35_bool_binop_done; - } - __pyx_t_3 = ((!((__pyx_v_long_long_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L35_bool_binop_done:; - if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_long_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - __pyx_t_3 = (((sizeof(unsigned char)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L39_bool_binop_done; - } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); - if (__pyx_t_3) { + __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_1); + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_t_6); + __pyx_t_1 = 0; + __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_9, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + if (likely(PyList_CheckExact(__pyx_t_6)) || PyTuple_CheckExact(__pyx_t_6)) { + __pyx_t_9 = __pyx_t_6; __Pyx_INCREF(__pyx_t_9); __pyx_t_5 = 0; + __pyx_t_10 = NULL; + } else { + __pyx_t_5 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_t_6); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_10 = Py_TYPE(__pyx_t_9)->tp_iternext; if (unlikely(!__pyx_t_10)) __PYX_ERR(0, 21, __pyx_L1_error) + } + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + for (;;) { + if (likely(!__pyx_t_10)) { + if (likely(PyList_CheckExact(__pyx_t_9))) { + if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_9)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_6 = PyList_GET_ITEM(__pyx_t_9, __pyx_t_5); __Pyx_INCREF(__pyx_t_6); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + #else + __pyx_t_6 = PySequence_ITEM(__pyx_t_9, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #endif + } else { + if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_9)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_6 = PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_5); __Pyx_INCREF(__pyx_t_6); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + #else + __pyx_t_6 = PySequence_ITEM(__pyx_t_9, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + #endif + } } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L39_bool_binop_done; - } - __pyx_t_3 = ((!((__pyx_v_unsigned_char_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L39_bool_binop_done:; - if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; + __pyx_t_6 = __pyx_t_10(__pyx_t_9); + if (unlikely(!__pyx_t_6)) { + PyObject* exc_type = PyErr_Occurred(); + if (exc_type) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(0, 21, __pyx_L1_error) + } + break; + } + __Pyx_GOTREF(__pyx_t_6); } - __pyx_t_3 = (((sizeof(char)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { + if ((likely(PyTuple_CheckExact(__pyx_t_6))) || (PyList_CheckExact(__pyx_t_6))) { + PyObject* sequence = __pyx_t_6; + #if !CYTHON_COMPILING_IN_PYPY + Py_ssize_t size = Py_SIZE(sequence); + #else + Py_ssize_t size = PySequence_Size(sequence); + #endif + if (unlikely(size != 2)) { + if (size > 2) __Pyx_RaiseTooManyValuesError(2); + else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); + __PYX_ERR(0, 21, __pyx_L1_error) + } + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + if (likely(PyTuple_CheckExact(sequence))) { + __pyx_t_1 = PyTuple_GET_ITEM(sequence, 0); + __pyx_t_11 = PyTuple_GET_ITEM(sequence, 1); + } else { + __pyx_t_1 = PyList_GET_ITEM(sequence, 0); + __pyx_t_11 = PyList_GET_ITEM(sequence, 1); + } + __Pyx_INCREF(__pyx_t_1); + __Pyx_INCREF(__pyx_t_11); + #else + __pyx_t_1 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_11 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + #endif + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L43_bool_binop_done; + Py_ssize_t index = -1; + __pyx_t_12 = PyObject_GetIter(__pyx_t_6); if (unlikely(!__pyx_t_12)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_12); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_13 = Py_TYPE(__pyx_t_12)->tp_iternext; + index = 0; __pyx_t_1 = __pyx_t_13(__pyx_t_12); if (unlikely(!__pyx_t_1)) goto __pyx_L24_unpacking_failed; + __Pyx_GOTREF(__pyx_t_1); + index = 1; __pyx_t_11 = __pyx_t_13(__pyx_t_12); if (unlikely(!__pyx_t_11)) goto __pyx_L24_unpacking_failed; + __Pyx_GOTREF(__pyx_t_11); + if (__Pyx_IternextUnpackEndCheck(__pyx_t_13(__pyx_t_12), 2) < 0) __PYX_ERR(0, 21, __pyx_L1_error) + __pyx_t_13 = NULL; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + goto __pyx_L25_unpacking_done; + __pyx_L24_unpacking_failed:; + __Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0; + __pyx_t_13 = NULL; + if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); + __PYX_ERR(0, 21, __pyx_L1_error) + __pyx_L25_unpacking_done:; } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); + __Pyx_XDECREF_SET(__pyx_v_dim, __pyx_t_1); + __pyx_t_1 = 0; + __Pyx_XDECREF_SET(__pyx_v_stride, __pyx_t_11); + __pyx_t_11 = 0; + __pyx_t_6 = PyObject_RichCompare(__pyx_v_stride, __pyx_v_cur_stride, Py_NE); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_3 < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L43_bool_binop_done; + __pyx_v_arg_is_pythran_compatible = 0; + goto __pyx_L23_break; } - __pyx_t_3 = ((!((__pyx_v_char_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L43_bool_binop_done:; + __pyx_t_6 = PyNumber_InPlaceMultiply(__pyx_v_cur_stride, __pyx_v_dim); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF_SET(__pyx_v_cur_stride, __pyx_t_6); + __pyx_t_6 = 0; + } + /*else*/ { + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_flags); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_11 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_f_contiguous); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_11); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - __pyx_t_3 = (((sizeof(unsigned int)) == __pyx_v_itemsize) != 0); - if (__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L47_bool_binop_done; - } - __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); - if (__pyx_t_3) { } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L47_bool_binop_done; - } - __pyx_t_3 = ((!((__pyx_v_unsigned_int_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L47_bool_binop_done:; - if (__pyx_t_2) { - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; + __pyx_t_3 = __pyx_t_2; + goto __pyx_L28_bool_binop_done; } - break; - case 'f': - break; - case 'c': - break; - case 'O': - break; - default: break; + __pyx_t_11 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_11, __pyx_int_1, Py_GT); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_3 = __pyx_t_2; + __pyx_L28_bool_binop_done:; + __pyx_v_arg_is_pythran_compatible = (!__pyx_t_3); + } + __pyx_L23_break:; + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } + switch (__pyx_v_kind) { + case 'i': + case 'u': + __pyx_t_2 = (((sizeof(short)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L31_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L31_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_short_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L31_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_short, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; + } + __pyx_t_2 = (((sizeof(int)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L35_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L35_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_int_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L35_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; + } + __pyx_t_2 = (((sizeof(long)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L39_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L39_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_long_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L39_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; + } + __pyx_t_2 = (((sizeof(PY_LONG_LONG)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L43_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L43_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_long_long_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L43_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_long_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; + } + __pyx_t_2 = (((sizeof(unsigned char)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L47_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L47_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_unsigned_char_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L47_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; + } + __pyx_t_2 = (((sizeof(char)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L51_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L51_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_char_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L51_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; + } + __pyx_t_2 = (((sizeof(unsigned int)) == __pyx_v_itemsize) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L55_bool_binop_done; + } + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_t_5 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_5 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = ((((Py_ssize_t)__pyx_t_5) == 1) != 0); + if (__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L55_bool_binop_done; + } + __pyx_t_2 = ((!((__pyx_v_unsigned_int_is_signed ^ __pyx_v_dtype_signed) != 0)) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L55_bool_binop_done:; + if (__pyx_t_3) { + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; } - goto __pyx_L21; + break; + case 'f': + break; + case 'c': + break; + case 'O': + break; + default: break; } - __pyx_L21:; - goto __pyx_L18; } - __pyx_L18:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L51_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L59_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(short))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L59_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_short(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_short, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(short))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L51_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_short(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_short, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - /*else*/ { - PyErr_Clear(); - } - goto __pyx_L50; + /*else*/ { + PyErr_Clear(); } - __pyx_L50:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L55_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L63_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(int))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L63_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_int(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(int))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L55_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_int(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - /*else*/ { - PyErr_Clear(); - } - goto __pyx_L54; + /*else*/ { + PyErr_Clear(); } - __pyx_L54:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L59_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L67_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(long))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L67_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_long(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(long))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L59_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_long(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - /*else*/ { - PyErr_Clear(); - } - goto __pyx_L58; + /*else*/ { + PyErr_Clear(); } - __pyx_L58:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L63_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L71_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(PY_LONG_LONG))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L71_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_PY_LONG_LONG(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_long_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(PY_LONG_LONG))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L63_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_PY_LONG_LONG(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_long_long, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - /*else*/ { - PyErr_Clear(); - } - goto __pyx_L62; + /*else*/ { + PyErr_Clear(); } - __pyx_L62:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L67_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L75_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(unsigned char))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L75_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_char(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(unsigned char))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L67_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_char(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - /*else*/ { - PyErr_Clear(); - } - goto __pyx_L66; + /*else*/ { + PyErr_Clear(); } - __pyx_L66:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L71_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L79_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(char))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L79_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_char(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(char))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L71_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_char(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_char, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - /*else*/ { - PyErr_Clear(); - } - goto __pyx_L70; + /*else*/ { + PyErr_Clear(); } - __pyx_L70:; - __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); - if (!__pyx_t_3) { - } else { - __pyx_t_2 = __pyx_t_3; - goto __pyx_L75_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == -1L) != 0); + if (!__pyx_t_2) { + } else { + __pyx_t_3 = __pyx_t_2; + goto __pyx_L83_bool_binop_done; + } + __pyx_t_2 = ((__pyx_v_itemsize == (sizeof(unsigned int))) != 0); + __pyx_t_3 = __pyx_t_2; + __pyx_L83_bool_binop_done:; + if (__pyx_t_3) { + __pyx_t_14 = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_int(__pyx_v_arg); + __pyx_v_memslice = __pyx_t_14; + __pyx_t_3 = (__pyx_v_memslice.memview != 0); + if (__pyx_t_3) { + __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(unsigned int))) != 0); - __pyx_t_2 = __pyx_t_3; - __pyx_L75_bool_binop_done:; - if (__pyx_t_2) { - __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_int(__pyx_v_arg); - __pyx_t_2 = (__pyx_v_memslice.memview != 0); - if (__pyx_t_2) { - __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_unsigned_int, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - /*else*/ { - PyErr_Clear(); - } - goto __pyx_L74; + /*else*/ { + PyErr_Clear(); } - __pyx_L74:; - if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, Py_None, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L17_break; - } - __pyx_L17_break:; - } - __pyx_L15:; - __pyx_t_8 = PyList_New(0); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __pyx_v_candidates = ((PyObject*)__pyx_t_8); - __pyx_t_8 = 0; - __pyx_t_10 = 0; - if (unlikely(__pyx_v_signatures == Py_None)) { - PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + } + if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, Py_None, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + goto __pyx_L10_break; } - __pyx_t_9 = __Pyx_dict_iterator(((PyObject*)__pyx_v_signatures), 1, ((PyObject *)NULL), (&__pyx_t_12), (&__pyx_t_7)); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_L10_break:; + __pyx_t_9 = PyList_New(0); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_8); - __pyx_t_8 = __pyx_t_9; + __pyx_v_candidates = ((PyObject*)__pyx_t_9); __pyx_t_9 = 0; - while (1) { - __pyx_t_13 = __Pyx_dict_iter_next(__pyx_t_8, __pyx_t_12, &__pyx_t_10, &__pyx_t_9, NULL, NULL, __pyx_t_7); - if (unlikely(__pyx_t_13 == 0)) break; - if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_XDECREF_SET(__pyx_v_sig, __pyx_t_9); - __pyx_t_9 = 0; - __pyx_v_match_found = 0; - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_sig, __pyx_n_s_strip); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_9, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_split); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_9, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_dest_sig); - PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_v_dest_sig); - __Pyx_GIVEREF(__pyx_v_dest_sig); - __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { - __pyx_t_9 = __pyx_t_1; __Pyx_INCREF(__pyx_t_9); __pyx_t_14 = 0; - __pyx_t_15 = NULL; - } else { - __pyx_t_14 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_9); - __pyx_t_15 = Py_TYPE(__pyx_t_9)->tp_iternext; if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - for (;;) { - if (likely(!__pyx_t_15)) { - if (likely(PyList_CheckExact(__pyx_t_9))) { - if (__pyx_t_14 >= PyList_GET_SIZE(__pyx_t_9)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_1 = PyList_GET_ITEM(__pyx_t_9, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_1 = PySequence_ITEM(__pyx_t_9, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - } else { - if (__pyx_t_14 >= PyTuple_GET_SIZE(__pyx_t_9)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_1 = PySequence_ITEM(__pyx_t_9, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - } - } else { - __pyx_t_1 = __pyx_t_15(__pyx_t_9); - if (unlikely(!__pyx_t_1)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - break; - } - __Pyx_GOTREF(__pyx_t_1); - } - if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { - PyObject* sequence = __pyx_t_1; - #if CYTHON_COMPILING_IN_CPYTHON - Py_ssize_t size = Py_SIZE(sequence); - #else - Py_ssize_t size = PySequence_Size(sequence); - #endif - if (unlikely(size != 2)) { - if (size > 2) __Pyx_RaiseTooManyValuesError(2); - else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - #if CYTHON_COMPILING_IN_CPYTHON - if (likely(PyTuple_CheckExact(sequence))) { - __pyx_t_16 = PyTuple_GET_ITEM(sequence, 0); - __pyx_t_17 = PyTuple_GET_ITEM(sequence, 1); - } else { - __pyx_t_16 = PyList_GET_ITEM(sequence, 0); - __pyx_t_17 = PyList_GET_ITEM(sequence, 1); - } - __Pyx_INCREF(__pyx_t_16); - __Pyx_INCREF(__pyx_t_17); - #else - __pyx_t_16 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_16); - __pyx_t_17 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_17); - #endif - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - } else { - Py_ssize_t index = -1; - __pyx_t_18 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_18); - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_19 = Py_TYPE(__pyx_t_18)->tp_iternext; - index = 0; __pyx_t_16 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_16)) goto __pyx_L82_unpacking_failed; - __Pyx_GOTREF(__pyx_t_16); - index = 1; __pyx_t_17 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_17)) goto __pyx_L82_unpacking_failed; - __Pyx_GOTREF(__pyx_t_17); - if (__Pyx_IternextUnpackEndCheck(__pyx_t_19(__pyx_t_18), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_19 = NULL; - __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; - goto __pyx_L83_unpacking_done; - __pyx_L82_unpacking_failed:; - __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; - __pyx_t_19 = NULL; - if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_L83_unpacking_done:; - } - __Pyx_XDECREF_SET(__pyx_v_src_type, __pyx_t_16); - __pyx_t_16 = 0; - __Pyx_XDECREF_SET(__pyx_v_dst_type, __pyx_t_17); - __pyx_t_17 = 0; - __pyx_t_2 = (__pyx_v_dst_type != Py_None); - __pyx_t_3 = (__pyx_t_2 != 0); - if (__pyx_t_3) { - __pyx_t_1 = PyObject_RichCompare(__pyx_v_src_type, __pyx_v_dst_type, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_3) { + __pyx_t_5 = 0; + if (unlikely(__pyx_v_signatures == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); + __PYX_ERR(0, 21, __pyx_L1_error) + } + __pyx_t_6 = __Pyx_dict_iterator(((PyObject*)__pyx_v_signatures), 1, ((PyObject *)NULL), (&__pyx_t_15), (&__pyx_t_8)); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_9); + __pyx_t_9 = __pyx_t_6; + __pyx_t_6 = 0; + while (1) { + __pyx_t_16 = __Pyx_dict_iter_next(__pyx_t_9, __pyx_t_15, &__pyx_t_5, &__pyx_t_6, NULL, NULL, __pyx_t_8); + if (unlikely(__pyx_t_16 == 0)) break; + if (unlikely(__pyx_t_16 == -1)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_XDECREF_SET(__pyx_v_sig, __pyx_t_6); + __pyx_t_6 = 0; + __pyx_v_match_found = 0; + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_sig, __pyx_n_s_strip); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_11 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_t_11, __pyx_n_s_split); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_11 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_XDECREF_SET(__pyx_v_src_sig, __pyx_t_11); + __pyx_t_11 = 0; + __pyx_t_17 = PyList_GET_SIZE(__pyx_v_dest_sig); if (unlikely(__pyx_t_17 == ((Py_ssize_t)-1))) __PYX_ERR(0, 21, __pyx_L1_error) + for (__pyx_t_18 = 0; __pyx_t_18 < __pyx_t_17; __pyx_t_18+=1) { + __pyx_v_i = __pyx_t_18; + __pyx_t_11 = PyList_GET_ITEM(__pyx_v_dest_sig, __pyx_v_i); + __Pyx_INCREF(__pyx_t_11); + __Pyx_XDECREF_SET(__pyx_v_dst_type, __pyx_t_11); + __pyx_t_11 = 0; + __pyx_t_3 = (__pyx_v_dst_type != Py_None); + __pyx_t_2 = (__pyx_t_3 != 0); + if (__pyx_t_2) { + __pyx_t_11 = __Pyx_GetItemInt(__pyx_v_src_sig, __pyx_v_i, Py_ssize_t, 1, PyInt_FromSsize_t, 0, 0, 0); if (unlikely(!__pyx_t_11)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_11); + __pyx_t_6 = PyObject_RichCompare(__pyx_t_11, __pyx_v_dst_type, Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (__pyx_t_2) { __pyx_v_match_found = 1; - goto __pyx_L85; + goto __pyx_L91; } /*else*/ { __pyx_v_match_found = 0; - goto __pyx_L81_break; + goto __pyx_L89_break; } - __pyx_L85:; - goto __pyx_L84; + __pyx_L91:; } - __pyx_L84:; } - __pyx_L81_break:; - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __pyx_t_3 = (__pyx_v_match_found != 0); - if (__pyx_t_3) { - __pyx_t_20 = __Pyx_PyList_Append(__pyx_v_candidates, __pyx_v_sig); if (unlikely(__pyx_t_20 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L86; + __pyx_L89_break:; + __pyx_t_2 = (__pyx_v_match_found != 0); + if (__pyx_t_2) { + __pyx_t_19 = __Pyx_PyList_Append(__pyx_v_candidates, __pyx_v_sig); if (unlikely(__pyx_t_19 == ((int)-1))) __PYX_ERR(0, 21, __pyx_L1_error) } - __pyx_L86:; } - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - __pyx_t_3 = (__pyx_v_candidates != Py_None) && (PyList_GET_SIZE(__pyx_v_candidates) != 0); - __pyx_t_2 = ((!__pyx_t_3) != 0); - if (__pyx_t_2) { - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_12 = PyList_GET_SIZE(__pyx_v_candidates); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_2 = ((__pyx_t_12 > 1) != 0); - if (__pyx_t_2) { - __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - __Pyx_Raise(__pyx_t_8, 0, 0, 0); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __pyx_t_2 = (__pyx_v_candidates != Py_None) && (PyList_GET_SIZE(__pyx_v_candidates) != 0); + __pyx_t_3 = ((!__pyx_t_2) != 0); + if (__pyx_t_3) { + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __PYX_ERR(0, 21, __pyx_L1_error) + } + __pyx_t_15 = PyList_GET_SIZE(__pyx_v_candidates); if (unlikely(__pyx_t_15 == ((Py_ssize_t)-1))) __PYX_ERR(0, 21, __pyx_L1_error) + __pyx_t_3 = ((__pyx_t_15 > 1) != 0); + if (__pyx_t_3) { + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_Raise(__pyx_t_9, 0, 0, 0); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __PYX_ERR(0, 21, __pyx_L1_error) } /*else*/ { __Pyx_XDECREF(__pyx_r); if (unlikely(__pyx_v_signatures == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); - {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(0, 21, __pyx_L1_error) } - __pyx_t_8 = __Pyx_PyDict_GetItem(((PyObject*)__pyx_v_signatures), PyList_GET_ITEM(__pyx_v_candidates, 0)); if (unlikely(__pyx_t_8 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __Pyx_GOTREF(__pyx_t_8); - __pyx_r = __pyx_t_8; - __pyx_t_8 = 0; + __pyx_t_9 = __Pyx_PyDict_GetItem(((PyObject*)__pyx_v_signatures), PyList_GET_ITEM(__pyx_v_candidates, 0)); if (unlikely(!__pyx_t_9)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __pyx_r = __pyx_t_9; + __pyx_t_9 = 0; goto __pyx_L0; } /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_9); - __Pyx_XDECREF(__pyx_t_16); - __Pyx_XDECREF(__pyx_t_17); - __Pyx_XDECREF(__pyx_t_18); + __Pyx_XDECREF(__pyx_t_11); + __Pyx_XDECREF(__pyx_t_12); __Pyx_AddTraceback("utils.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_dest_sig); __Pyx_XDECREF(__pyx_v_ndarray); - __Pyx_XDECREF(__pyx_v_numpy); __Pyx_XDECREF(__pyx_v_arg); __Pyx_XDECREF(__pyx_v_dtype); __Pyx_XDECREF(__pyx_v_arg_base); + __Pyx_XDECREF(__pyx_v_byteorder); + __Pyx_XDECREF(__pyx_v_cur_stride); + __Pyx_XDECREF(__pyx_v_dim); + __Pyx_XDECREF(__pyx_v_stride); __Pyx_XDECREF(__pyx_v_candidates); __Pyx_XDECREF(__pyx_v_sig); - __Pyx_XDECREF(__pyx_v_src_type); + __Pyx_XDECREF(__pyx_v_src_sig); __Pyx_XDECREF(__pyx_v_dst_type); __Pyx_XDECREF(__pyx_v_kwargs); __Pyx_XGIVEREF(__pyx_r); @@ -4396,9 +5173,6 @@ static PyObject *__pyx_fuse_0__pyx_pw_5utils_21loss_augment_unaries(PyObject *__ __Pyx_memviewslice __pyx_v_unary_potentials = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_class_weight = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("loss_augment_unaries (wrapper)", 0); @@ -4410,8 +5184,11 @@ static PyObject *__pyx_fuse_0__pyx_pw_5utils_21loss_augment_unaries(PyObject *__ const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -4420,19 +5197,21 @@ static PyObject *__pyx_fuse_0__pyx_pw_5utils_21loss_augment_unaries(PyObject *__ case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_unary_potentials)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); __PYX_ERR(0, 21, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_class_weight)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); __PYX_ERR(0, 21, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) __PYX_ERR(0, 21, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -4441,13 +5220,13 @@ static PyObject *__pyx_fuse_0__pyx_pw_5utils_21loss_augment_unaries(PyObject *__ values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_short(values[1]); if (unlikely(!__pyx_v_y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_short(values[1]); if (unlikely(!__pyx_v_y.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) __PYX_ERR(0, 21, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 21, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.loss_augment_unaries", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -4470,12 +5249,12 @@ static PyObject *__pyx_pf_5utils_20loss_augment_unaries(CYTHON_UNUSED PyObject * int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; - int __pyx_t_5; + Py_ssize_t __pyx_t_5; int __pyx_t_6; - int __pyx_t_7; - short __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; + Py_ssize_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; __Pyx_RefNannySetupContext("__pyx_fuse_0loss_augment_unaries", 0); /* "utils.pyx":23 @@ -4527,6 +5306,14 @@ static PyObject *__pyx_pf_5utils_20loss_augment_unaries(CYTHON_UNUSED PyObject * * unary_potentials[i, s] += class_weight[y[i]] */ goto __pyx_L5_continue; + + /* "utils.pyx":26 + * for i in range(unary_potentials.shape[0]): + * for s in range(n_states): + * if s == y[i]: # <<<<<<<<<<<<<< + * continue + * unary_potentials[i, s] += class_weight[y[i]] + */ } /* "utils.pyx":28 @@ -4568,9 +5355,6 @@ static PyObject *__pyx_fuse_1__pyx_pw_5utils_23loss_augment_unaries(PyObject *__ __Pyx_memviewslice __pyx_v_unary_potentials = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_class_weight = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("loss_augment_unaries (wrapper)", 0); @@ -4582,8 +5366,11 @@ static PyObject *__pyx_fuse_1__pyx_pw_5utils_23loss_augment_unaries(PyObject *__ const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -4592,19 +5379,21 @@ static PyObject *__pyx_fuse_1__pyx_pw_5utils_23loss_augment_unaries(PyObject *__ case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_unary_potentials)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); __PYX_ERR(0, 21, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_class_weight)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); __PYX_ERR(0, 21, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) __PYX_ERR(0, 21, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -4613,13 +5402,13 @@ static PyObject *__pyx_fuse_1__pyx_pw_5utils_23loss_augment_unaries(PyObject *__ values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[1]); if (unlikely(!__pyx_v_y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[1]); if (unlikely(!__pyx_v_y.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) __PYX_ERR(0, 21, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 21, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.loss_augment_unaries", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -4642,12 +5431,12 @@ static PyObject *__pyx_pf_5utils_22loss_augment_unaries(CYTHON_UNUSED PyObject * int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; - int __pyx_t_5; + Py_ssize_t __pyx_t_5; int __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; + Py_ssize_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; __Pyx_RefNannySetupContext("__pyx_fuse_1loss_augment_unaries", 0); /* "utils.pyx":23 @@ -4699,6 +5488,14 @@ static PyObject *__pyx_pf_5utils_22loss_augment_unaries(CYTHON_UNUSED PyObject * * unary_potentials[i, s] += class_weight[y[i]] */ goto __pyx_L5_continue; + + /* "utils.pyx":26 + * for i in range(unary_potentials.shape[0]): + * for s in range(n_states): + * if s == y[i]: # <<<<<<<<<<<<<< + * continue + * unary_potentials[i, s] += class_weight[y[i]] + */ } /* "utils.pyx":28 @@ -4740,9 +5537,6 @@ static PyObject *__pyx_fuse_2__pyx_pw_5utils_25loss_augment_unaries(PyObject *__ __Pyx_memviewslice __pyx_v_unary_potentials = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_class_weight = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("loss_augment_unaries (wrapper)", 0); @@ -4754,8 +5548,11 @@ static PyObject *__pyx_fuse_2__pyx_pw_5utils_25loss_augment_unaries(PyObject *__ const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -4764,19 +5561,21 @@ static PyObject *__pyx_fuse_2__pyx_pw_5utils_25loss_augment_unaries(PyObject *__ case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_unary_potentials)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); __PYX_ERR(0, 21, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_class_weight)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); __PYX_ERR(0, 21, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) __PYX_ERR(0, 21, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -4785,13 +5584,13 @@ static PyObject *__pyx_fuse_2__pyx_pw_5utils_25loss_augment_unaries(PyObject *__ values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[1]); if (unlikely(!__pyx_v_y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_long(values[1]); if (unlikely(!__pyx_v_y.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) __PYX_ERR(0, 21, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 21, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.loss_augment_unaries", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -4814,12 +5613,12 @@ static PyObject *__pyx_pf_5utils_24loss_augment_unaries(CYTHON_UNUSED PyObject * int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; - int __pyx_t_5; + Py_ssize_t __pyx_t_5; int __pyx_t_6; - int __pyx_t_7; - long __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; + Py_ssize_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; __Pyx_RefNannySetupContext("__pyx_fuse_2loss_augment_unaries", 0); /* "utils.pyx":23 @@ -4871,6 +5670,14 @@ static PyObject *__pyx_pf_5utils_24loss_augment_unaries(CYTHON_UNUSED PyObject * * unary_potentials[i, s] += class_weight[y[i]] */ goto __pyx_L5_continue; + + /* "utils.pyx":26 + * for i in range(unary_potentials.shape[0]): + * for s in range(n_states): + * if s == y[i]: # <<<<<<<<<<<<<< + * continue + * unary_potentials[i, s] += class_weight[y[i]] + */ } /* "utils.pyx":28 @@ -4912,9 +5719,6 @@ static PyObject *__pyx_fuse_3__pyx_pw_5utils_27loss_augment_unaries(PyObject *__ __Pyx_memviewslice __pyx_v_unary_potentials = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_class_weight = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("loss_augment_unaries (wrapper)", 0); @@ -4926,8 +5730,11 @@ static PyObject *__pyx_fuse_3__pyx_pw_5utils_27loss_augment_unaries(PyObject *__ const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -4936,19 +5743,21 @@ static PyObject *__pyx_fuse_3__pyx_pw_5utils_27loss_augment_unaries(PyObject *__ case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_unary_potentials)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); __PYX_ERR(0, 21, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_class_weight)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); __PYX_ERR(0, 21, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) __PYX_ERR(0, 21, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -4957,13 +5766,13 @@ static PyObject *__pyx_fuse_3__pyx_pw_5utils_27loss_augment_unaries(PyObject *__ values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_PY_LONG_LONG(values[1]); if (unlikely(!__pyx_v_y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_PY_LONG_LONG(values[1]); if (unlikely(!__pyx_v_y.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) __PYX_ERR(0, 21, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 21, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.loss_augment_unaries", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -4986,12 +5795,12 @@ static PyObject *__pyx_pf_5utils_26loss_augment_unaries(CYTHON_UNUSED PyObject * int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; - int __pyx_t_5; + Py_ssize_t __pyx_t_5; int __pyx_t_6; - int __pyx_t_7; + Py_ssize_t __pyx_t_7; PY_LONG_LONG __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; __Pyx_RefNannySetupContext("__pyx_fuse_3loss_augment_unaries", 0); /* "utils.pyx":23 @@ -5043,6 +5852,14 @@ static PyObject *__pyx_pf_5utils_26loss_augment_unaries(CYTHON_UNUSED PyObject * * unary_potentials[i, s] += class_weight[y[i]] */ goto __pyx_L5_continue; + + /* "utils.pyx":26 + * for i in range(unary_potentials.shape[0]): + * for s in range(n_states): + * if s == y[i]: # <<<<<<<<<<<<<< + * continue + * unary_potentials[i, s] += class_weight[y[i]] + */ } /* "utils.pyx":28 @@ -5084,9 +5901,6 @@ static PyObject *__pyx_fuse_4__pyx_pw_5utils_29loss_augment_unaries(PyObject *__ __Pyx_memviewslice __pyx_v_unary_potentials = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_class_weight = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("loss_augment_unaries (wrapper)", 0); @@ -5098,8 +5912,11 @@ static PyObject *__pyx_fuse_4__pyx_pw_5utils_29loss_augment_unaries(PyObject *__ const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -5108,19 +5925,21 @@ static PyObject *__pyx_fuse_4__pyx_pw_5utils_29loss_augment_unaries(PyObject *__ case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_unary_potentials)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); __PYX_ERR(0, 21, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_class_weight)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); __PYX_ERR(0, 21, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) __PYX_ERR(0, 21, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -5129,13 +5948,13 @@ static PyObject *__pyx_fuse_4__pyx_pw_5utils_29loss_augment_unaries(PyObject *__ values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_char(values[1]); if (unlikely(!__pyx_v_y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_char(values[1]); if (unlikely(!__pyx_v_y.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) __PYX_ERR(0, 21, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 21, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.loss_augment_unaries", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -5158,12 +5977,12 @@ static PyObject *__pyx_pf_5utils_28loss_augment_unaries(CYTHON_UNUSED PyObject * int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; - int __pyx_t_5; + Py_ssize_t __pyx_t_5; int __pyx_t_6; - int __pyx_t_7; - unsigned char __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; + Py_ssize_t __pyx_t_7; + size_t __pyx_t_8; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; __Pyx_RefNannySetupContext("__pyx_fuse_4loss_augment_unaries", 0); /* "utils.pyx":23 @@ -5215,6 +6034,14 @@ static PyObject *__pyx_pf_5utils_28loss_augment_unaries(CYTHON_UNUSED PyObject * * unary_potentials[i, s] += class_weight[y[i]] */ goto __pyx_L5_continue; + + /* "utils.pyx":26 + * for i in range(unary_potentials.shape[0]): + * for s in range(n_states): + * if s == y[i]: # <<<<<<<<<<<<<< + * continue + * unary_potentials[i, s] += class_weight[y[i]] + */ } /* "utils.pyx":28 @@ -5256,9 +6083,6 @@ static PyObject *__pyx_fuse_5__pyx_pw_5utils_31loss_augment_unaries(PyObject *__ __Pyx_memviewslice __pyx_v_unary_potentials = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_class_weight = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("loss_augment_unaries (wrapper)", 0); @@ -5270,8 +6094,11 @@ static PyObject *__pyx_fuse_5__pyx_pw_5utils_31loss_augment_unaries(PyObject *__ const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -5280,19 +6107,21 @@ static PyObject *__pyx_fuse_5__pyx_pw_5utils_31loss_augment_unaries(PyObject *__ case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_unary_potentials)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); __PYX_ERR(0, 21, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_class_weight)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); __PYX_ERR(0, 21, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) __PYX_ERR(0, 21, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -5301,13 +6130,13 @@ static PyObject *__pyx_fuse_5__pyx_pw_5utils_31loss_augment_unaries(PyObject *__ values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_char(values[1]); if (unlikely(!__pyx_v_y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_char(values[1]); if (unlikely(!__pyx_v_y.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) __PYX_ERR(0, 21, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 21, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.loss_augment_unaries", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -5330,12 +6159,12 @@ static PyObject *__pyx_pf_5utils_30loss_augment_unaries(CYTHON_UNUSED PyObject * int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; - int __pyx_t_5; + Py_ssize_t __pyx_t_5; int __pyx_t_6; - int __pyx_t_7; - char __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; + Py_ssize_t __pyx_t_7; + Py_ssize_t __pyx_t_8; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; __Pyx_RefNannySetupContext("__pyx_fuse_5loss_augment_unaries", 0); /* "utils.pyx":23 @@ -5387,6 +6216,14 @@ static PyObject *__pyx_pf_5utils_30loss_augment_unaries(CYTHON_UNUSED PyObject * * unary_potentials[i, s] += class_weight[y[i]] */ goto __pyx_L5_continue; + + /* "utils.pyx":26 + * for i in range(unary_potentials.shape[0]): + * for s in range(n_states): + * if s == y[i]: # <<<<<<<<<<<<<< + * continue + * unary_potentials[i, s] += class_weight[y[i]] + */ } /* "utils.pyx":28 @@ -5428,9 +6265,6 @@ static PyObject *__pyx_fuse_6__pyx_pw_5utils_33loss_augment_unaries(PyObject *__ __Pyx_memviewslice __pyx_v_unary_potentials = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_y = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_memviewslice __pyx_v_class_weight = { 0, 0, { 0 }, { 0 }, { 0 } }; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("loss_augment_unaries (wrapper)", 0); @@ -5442,8 +6276,11 @@ static PyObject *__pyx_fuse_6__pyx_pw_5utils_33loss_augment_unaries(PyObject *__ const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -5452,19 +6289,21 @@ static PyObject *__pyx_fuse_6__pyx_pw_5utils_33loss_augment_unaries(PyObject *__ case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_unary_potentials)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 1); __PYX_ERR(0, 21, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_class_weight)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, 2); __PYX_ERR(0, 21, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "loss_augment_unaries") < 0)) __PYX_ERR(0, 21, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; @@ -5473,13 +6312,13 @@ static PyObject *__pyx_fuse_6__pyx_pw_5utils_33loss_augment_unaries(PyObject *__ values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } - __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_int(values[1]); if (unlikely(!__pyx_v_y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_unary_potentials = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_unary_potentials.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_y = __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_int(values[1]); if (unlikely(!__pyx_v_y.memview)) __PYX_ERR(0, 21, __pyx_L3_error) + __pyx_v_class_weight = __Pyx_PyObject_to_MemoryviewSlice_ds_double(values[2]); if (unlikely(!__pyx_v_class_weight.memview)) __PYX_ERR(0, 21, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("loss_augment_unaries", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 21, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("utils.loss_augment_unaries", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); @@ -5502,12 +6341,12 @@ static PyObject *__pyx_pf_5utils_32loss_augment_unaries(CYTHON_UNUSED PyObject * int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; - int __pyx_t_5; + Py_ssize_t __pyx_t_5; int __pyx_t_6; - int __pyx_t_7; - unsigned int __pyx_t_8; - int __pyx_t_9; - int __pyx_t_10; + Py_ssize_t __pyx_t_7; + size_t __pyx_t_8; + Py_ssize_t __pyx_t_9; + Py_ssize_t __pyx_t_10; __Pyx_RefNannySetupContext("__pyx_fuse_6loss_augment_unaries", 0); /* "utils.pyx":23 @@ -5559,6 +6398,14 @@ static PyObject *__pyx_pf_5utils_32loss_augment_unaries(CYTHON_UNUSED PyObject * * unary_potentials[i, s] += class_weight[y[i]] */ goto __pyx_L5_continue; + + /* "utils.pyx":26 + * for i in range(unary_potentials.shape[0]): + * for s in range(n_states): + * if s == y[i]: # <<<<<<<<<<<<<< + * continue + * unary_potentials[i, s] += class_weight[y[i]] + */ } /* "utils.pyx":28 @@ -5593,7 +6440,7 @@ static PyObject *__pyx_pf_5utils_32loss_augment_unaries(CYTHON_UNUSED PyObject * return __pyx_r; } -/* "View.MemoryView":116 +/* "View.MemoryView":120 * cdef bint dtype_is_object * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< @@ -5609,9 +6456,6 @@ static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, P PyObject *__pyx_v_format = 0; PyObject *__pyx_v_mode = 0; int __pyx_v_allocate_buffer; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); @@ -5624,10 +6468,15 @@ static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, P const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -5636,21 +6485,25 @@ static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, P case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); __PYX_ERR(1, 120, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); __PYX_ERR(1, 120, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 3: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mode); if (value) { values[3] = value; kw_args--; } } + CYTHON_FALLTHROUGH; case 4: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_allocate_buffer); @@ -5658,12 +6511,14 @@ static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, P } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(1, 120, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); + CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); + CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); @@ -5672,14 +6527,14 @@ static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, P } } __pyx_v_shape = ((PyObject*)values[0]); - __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 120, __pyx_L3_error) __pyx_v_format = values[2]; __pyx_v_mode = values[3]; if (values[4]) { - __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 121, __pyx_L3_error) } else { - /* "View.MemoryView":117 + /* "View.MemoryView":121 * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, * mode="c", bint allocate_buffer=True): # <<<<<<<<<<<<<< @@ -5691,19 +6546,19 @@ static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, P } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 120, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; - if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) __PYX_ERR(1, 120, __pyx_L1_error) if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { - PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); __PYX_ERR(1, 120, __pyx_L1_error) } - __pyx_r = __pyx_array_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); - /* "View.MemoryView":116 + /* "View.MemoryView":120 * cdef bint dtype_is_object * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< @@ -5720,7 +6575,7 @@ static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, P return __pyx_r; } -static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { int __pyx_v_idx; Py_ssize_t __pyx_v_i; Py_ssize_t __pyx_v_dim; @@ -5732,19 +6587,16 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; - char *__pyx_t_5; - int __pyx_t_6; - PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_5 = NULL; + char *__pyx_t_6; + int __pyx_t_7; Py_ssize_t __pyx_t_8; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__cinit__", 0); __Pyx_INCREF(__pyx_v_format); - /* "View.MemoryView":123 + /* "View.MemoryView":127 * cdef PyObject **p * * self.ndim = len(shape) # <<<<<<<<<<<<<< @@ -5753,12 +6605,12 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx */ if (unlikely(__pyx_v_shape == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 127, __pyx_L1_error) } - __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == ((Py_ssize_t)-1))) __PYX_ERR(1, 127, __pyx_L1_error) __pyx_v_self->ndim = ((int)__pyx_t_1); - /* "View.MemoryView":124 + /* "View.MemoryView":128 * * self.ndim = len(shape) * self.itemsize = itemsize # <<<<<<<<<<<<<< @@ -5767,7 +6619,7 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx */ __pyx_v_self->itemsize = __pyx_v_itemsize; - /* "View.MemoryView":126 + /* "View.MemoryView":130 * self.itemsize = itemsize * * if not self.ndim: # <<<<<<<<<<<<<< @@ -5777,21 +6629,29 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":127 + /* "View.MemoryView":131 * * if not self.ndim: * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< * * if itemsize <= 0: */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__13, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 131, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 131, __pyx_L1_error) + + /* "View.MemoryView":130 + * self.itemsize = itemsize + * + * if not self.ndim: # <<<<<<<<<<<<<< + * raise ValueError("Empty shape tuple for cython.array") + * + */ } - /* "View.MemoryView":129 + /* "View.MemoryView":133 * raise ValueError("Empty shape tuple for cython.array") * * if itemsize <= 0: # <<<<<<<<<<<<<< @@ -5801,95 +6661,112 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx __pyx_t_2 = ((__pyx_v_itemsize <= 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":130 + /* "View.MemoryView":134 * * if itemsize <= 0: * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< * - * if isinstance(format, unicode): + * if not isinstance(format, bytes): */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__14, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 134, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 134, __pyx_L1_error) + + /* "View.MemoryView":133 + * raise ValueError("Empty shape tuple for cython.array") + * + * if itemsize <= 0: # <<<<<<<<<<<<<< + * raise ValueError("itemsize <= 0 for cython.array") + * + */ } - /* "View.MemoryView":132 + /* "View.MemoryView":136 * raise ValueError("itemsize <= 0 for cython.array") * - * if isinstance(format, unicode): # <<<<<<<<<<<<<< - * format = (format).encode('ASCII') + * if not isinstance(format, bytes): # <<<<<<<<<<<<<< + * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string */ - __pyx_t_2 = PyUnicode_Check(__pyx_v_format); - __pyx_t_4 = (__pyx_t_2 != 0); + __pyx_t_2 = PyBytes_Check(__pyx_v_format); + __pyx_t_4 = ((!(__pyx_t_2 != 0)) != 0); if (__pyx_t_4) { - /* "View.MemoryView":133 + /* "View.MemoryView":137 * - * if isinstance(format, unicode): - * format = (format).encode('ASCII') # <<<<<<<<<<<<<< + * if not isinstance(format, bytes): + * format = format.encode('ASCII') # <<<<<<<<<<<<<< * self._format = format # keep a reference to the byte string * self.format = self._format */ - if (unlikely(__pyx_v_format == Py_None)) { - PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", "encode"); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __pyx_t_3 = PyUnicode_AsASCIIString(((PyObject*)__pyx_v_format)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_v_format, __pyx_n_s_encode); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 137, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); - __pyx_t_3 = 0; - goto __pyx_L5; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 137, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_5); + __pyx_t_5 = 0; + + /* "View.MemoryView":136 + * raise ValueError("itemsize <= 0 for cython.array") + * + * if not isinstance(format, bytes): # <<<<<<<<<<<<<< + * format = format.encode('ASCII') + * self._format = format # keep a reference to the byte string + */ } - __pyx_L5:; - /* "View.MemoryView":134 - * if isinstance(format, unicode): - * format = (format).encode('ASCII') + /* "View.MemoryView":138 + * if not isinstance(format, bytes): + * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string # <<<<<<<<<<<<<< * self.format = self._format * */ - if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 134; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_3 = __pyx_v_format; - __Pyx_INCREF(__pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); + if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) __PYX_ERR(1, 138, __pyx_L1_error) + __pyx_t_5 = __pyx_v_format; + __Pyx_INCREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_5); __Pyx_GOTREF(__pyx_v_self->_format); __Pyx_DECREF(__pyx_v_self->_format); - __pyx_v_self->_format = ((PyObject*)__pyx_t_3); - __pyx_t_3 = 0; + __pyx_v_self->_format = ((PyObject*)__pyx_t_5); + __pyx_t_5 = 0; - /* "View.MemoryView":135 - * format = (format).encode('ASCII') + /* "View.MemoryView":139 + * format = format.encode('ASCII') * self._format = format # keep a reference to the byte string * self.format = self._format # <<<<<<<<<<<<<< * * */ - __pyx_t_5 = __Pyx_PyObject_AsString(__pyx_v_self->_format); if (unlikely((!__pyx_t_5) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_v_self->format = __pyx_t_5; + if (unlikely(__pyx_v_self->_format == Py_None)) { + PyErr_SetString(PyExc_TypeError, "expected bytes, NoneType found"); + __PYX_ERR(1, 139, __pyx_L1_error) + } + __pyx_t_6 = __Pyx_PyBytes_AsWritableString(__pyx_v_self->_format); if (unlikely((!__pyx_t_6) && PyErr_Occurred())) __PYX_ERR(1, 139, __pyx_L1_error) + __pyx_v_self->format = __pyx_t_6; - /* "View.MemoryView":138 + /* "View.MemoryView":142 * * - * self._shape = PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< + * self._shape = PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< * self._strides = self._shape + self.ndim * */ - __pyx_v_self->_shape = ((Py_ssize_t *)PyMem_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); + __pyx_v_self->_shape = ((Py_ssize_t *)PyObject_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); - /* "View.MemoryView":139 + /* "View.MemoryView":143 * - * self._shape = PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) + * self._shape = PyObject_Malloc(sizeof(Py_ssize_t)*self.ndim*2) * self._strides = self._shape + self.ndim # <<<<<<<<<<<<<< * * if not self._shape: */ __pyx_v_self->_strides = (__pyx_v_self->_shape + __pyx_v_self->ndim); - /* "View.MemoryView":141 + /* "View.MemoryView":145 * self._strides = self._shape + self.ndim * * if not self._shape: # <<<<<<<<<<<<<< @@ -5899,43 +6776,52 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx __pyx_t_4 = ((!(__pyx_v_self->_shape != 0)) != 0); if (__pyx_t_4) { - /* "View.MemoryView":142 + /* "View.MemoryView":146 * * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__13, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __PYX_ERR(1, 146, __pyx_L1_error) + + /* "View.MemoryView":145 + * self._strides = self._shape + self.ndim + * + * if not self._shape: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate shape and strides.") + * + */ } - /* "View.MemoryView":145 + /* "View.MemoryView":149 * * * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) */ - __pyx_t_6 = 0; - __pyx_t_3 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; + __pyx_t_7 = 0; + __pyx_t_5 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_5); __pyx_t_1 = 0; for (;;) { - if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_7); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_5)) break; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_5, __pyx_t_1); __Pyx_INCREF(__pyx_t_3); __pyx_t_1++; if (unlikely(0 < 0)) __PYX_ERR(1, 149, __pyx_L1_error) #else - __pyx_t_7 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PySequence_ITEM(__pyx_t_5, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 149, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); #endif - __pyx_t_8 = __Pyx_PyIndex_AsSsize_t(__pyx_t_7); if (unlikely((__pyx_t_8 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __pyx_t_8 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_8 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 149, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_dim = __pyx_t_8; - __pyx_v_idx = __pyx_t_6; - __pyx_t_6 = (__pyx_t_6 + 1); + __pyx_v_idx = __pyx_t_7; + __pyx_t_7 = (__pyx_t_7 + 1); - /* "View.MemoryView":146 + /* "View.MemoryView":150 * * for idx, dim in enumerate(shape): * if dim <= 0: # <<<<<<<<<<<<<< @@ -5945,42 +6831,50 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx __pyx_t_4 = ((__pyx_v_dim <= 0) != 0); if (__pyx_t_4) { - /* "View.MemoryView":147 + /* "View.MemoryView":151 * for idx, dim in enumerate(shape): * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< * self._shape[idx] = dim * */ - __pyx_t_7 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_7); - __pyx_t_9 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 151, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_9 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); - __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); - PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_7); - __Pyx_GIVEREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_9); + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_9); - __pyx_t_7 = 0; + PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_9); + __pyx_t_3 = 0; __pyx_t_9 = 0; - __pyx_t_9 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - __pyx_t_10 = PyTuple_New(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = PyTuple_New(1); if (unlikely(!__pyx_t_10)) __PYX_ERR(1, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_10); - PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_9); __Pyx_GIVEREF(__pyx_t_9); + PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_9); __pyx_t_9 = 0; - __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_10, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_10, NULL); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 151, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __Pyx_Raise(__pyx_t_9, 0, 0, 0); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 151, __pyx_L1_error) + + /* "View.MemoryView":150 + * + * for idx, dim in enumerate(shape): + * if dim <= 0: # <<<<<<<<<<<<<< + * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) + * self._shape[idx] = dim + */ } - /* "View.MemoryView":148 + /* "View.MemoryView":152 * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) * self._shape[idx] = dim # <<<<<<<<<<<<<< @@ -5989,7 +6883,7 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx */ (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_v_dim; - /* "View.MemoryView":145 + /* "View.MemoryView":149 * * * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< @@ -5997,19 +6891,19 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) */ } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - /* "View.MemoryView":151 + /* "View.MemoryView":155 * * cdef char order * if mode == 'fortran': # <<<<<<<<<<<<<< * order = b'F' * self.mode = u'fortran' */ - __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(1, 155, __pyx_L1_error) if (__pyx_t_4) { - /* "View.MemoryView":152 + /* "View.MemoryView":156 * cdef char order * if mode == 'fortran': * order = b'F' # <<<<<<<<<<<<<< @@ -6018,7 +6912,7 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx */ __pyx_v_order = 'F'; - /* "View.MemoryView":153 + /* "View.MemoryView":157 * if mode == 'fortran': * order = b'F' * self.mode = u'fortran' # <<<<<<<<<<<<<< @@ -6030,20 +6924,28 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx __Pyx_GOTREF(__pyx_v_self->mode); __Pyx_DECREF(__pyx_v_self->mode); __pyx_v_self->mode = __pyx_n_u_fortran; + + /* "View.MemoryView":155 + * + * cdef char order + * if mode == 'fortran': # <<<<<<<<<<<<<< + * order = b'F' + * self.mode = u'fortran' + */ goto __pyx_L10; } - /* "View.MemoryView":154 + /* "View.MemoryView":158 * order = b'F' * self.mode = u'fortran' * elif mode == 'c': # <<<<<<<<<<<<<< * order = b'C' * self.mode = u'c' */ - __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(1, 158, __pyx_L1_error) if (__pyx_t_4) { - /* "View.MemoryView":155 + /* "View.MemoryView":159 * self.mode = u'fortran' * elif mode == 'c': * order = b'C' # <<<<<<<<<<<<<< @@ -6052,7 +6954,7 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx */ __pyx_v_order = 'C'; - /* "View.MemoryView":156 + /* "View.MemoryView":160 * elif mode == 'c': * order = b'C' * self.mode = u'c' # <<<<<<<<<<<<<< @@ -6064,34 +6966,42 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx __Pyx_GOTREF(__pyx_v_self->mode); __Pyx_DECREF(__pyx_v_self->mode); __pyx_v_self->mode = __pyx_n_u_c; + + /* "View.MemoryView":158 + * order = b'F' + * self.mode = u'fortran' + * elif mode == 'c': # <<<<<<<<<<<<<< + * order = b'C' + * self.mode = u'c' + */ goto __pyx_L10; } - /*else*/ { - /* "View.MemoryView":158 + /* "View.MemoryView":162 * self.mode = u'c' * else: * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< * * self.len = fill_contig_strides_array(self._shape, self._strides, */ - __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*else*/ { + __pyx_t_5 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 162, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 162, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_5); + __pyx_t_5 = 0; + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 162, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __PYX_ERR(1, 162, __pyx_L1_error) } __pyx_L10:; - /* "View.MemoryView":160 + /* "View.MemoryView":164 * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) * * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< @@ -6100,7 +7010,7 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx */ __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); - /* "View.MemoryView":163 + /* "View.MemoryView":167 * itemsize, self.ndim, order) * * self.free_data = allocate_buffer # <<<<<<<<<<<<<< @@ -6109,19 +7019,19 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx */ __pyx_v_self->free_data = __pyx_v_allocate_buffer; - /* "View.MemoryView":164 + /* "View.MemoryView":168 * * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< * if allocate_buffer: * */ - __pyx_t_3 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_t_5 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_5); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 168, __pyx_L1_error) + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_5); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 168, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_self->dtype_is_object = __pyx_t_4; - /* "View.MemoryView":165 + /* "View.MemoryView":169 * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' * if allocate_buffer: # <<<<<<<<<<<<<< @@ -6131,7 +7041,7 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx __pyx_t_4 = (__pyx_v_allocate_buffer != 0); if (__pyx_t_4) { - /* "View.MemoryView":168 + /* "View.MemoryView":172 * * * self.data = malloc(self.len) # <<<<<<<<<<<<<< @@ -6140,7 +7050,7 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx */ __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); - /* "View.MemoryView":169 + /* "View.MemoryView":173 * * self.data = malloc(self.len) * if not self.data: # <<<<<<<<<<<<<< @@ -6150,21 +7060,29 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx __pyx_t_4 = ((!(__pyx_v_self->data != 0)) != 0); if (__pyx_t_4) { - /* "View.MemoryView":170 + /* "View.MemoryView":174 * self.data = malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__14, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_Raise(__pyx_t_3, 0, 0, 0); - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__17, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 174, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __PYX_ERR(1, 174, __pyx_L1_error) + + /* "View.MemoryView":173 + * + * self.data = malloc(self.len) + * if not self.data: # <<<<<<<<<<<<<< + * raise MemoryError("unable to allocate array data.") + * + */ } - /* "View.MemoryView":172 + /* "View.MemoryView":176 * raise MemoryError("unable to allocate array data.") * * if self.dtype_is_object: # <<<<<<<<<<<<<< @@ -6174,7 +7092,7 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx __pyx_t_4 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_4) { - /* "View.MemoryView":173 + /* "View.MemoryView":177 * * if self.dtype_is_object: * p = self.data # <<<<<<<<<<<<<< @@ -6183,7 +7101,7 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx */ __pyx_v_p = ((PyObject **)__pyx_v_self->data); - /* "View.MemoryView":174 + /* "View.MemoryView":178 * if self.dtype_is_object: * p = self.data * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< @@ -6191,30 +7109,18 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx * Py_INCREF(Py_None) */ if (unlikely(__pyx_v_itemsize == 0)) { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); - #endif PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); - #endif - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 178, __pyx_L1_error) } - else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); - #endif + else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); - #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); - #endif - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 178, __pyx_L1_error) } __pyx_t_1 = __Pyx_div_Py_ssize_t(__pyx_v_self->len, __pyx_v_itemsize); for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_1; __pyx_t_8+=1) { __pyx_v_i = __pyx_t_8; - /* "View.MemoryView":175 + /* "View.MemoryView":179 * p = self.data * for i in range(self.len / itemsize): * p[i] = Py_None # <<<<<<<<<<<<<< @@ -6223,7 +7129,7 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx */ (__pyx_v_p[__pyx_v_i]) = Py_None; - /* "View.MemoryView":176 + /* "View.MemoryView":180 * for i in range(self.len / itemsize): * p[i] = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< @@ -6232,14 +7138,26 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx */ Py_INCREF(Py_None); } - goto __pyx_L13; + + /* "View.MemoryView":176 + * raise MemoryError("unable to allocate array data.") + * + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * p = self.data + * for i in range(self.len / itemsize): + */ } - __pyx_L13:; - goto __pyx_L11; + + /* "View.MemoryView":169 + * self.free_data = allocate_buffer + * self.dtype_is_object = format == b'O' + * if allocate_buffer: # <<<<<<<<<<<<<< + * + * + */ } - __pyx_L11:; - /* "View.MemoryView":116 + /* "View.MemoryView":120 * cdef bint dtype_is_object * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< @@ -6252,7 +7170,7 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_9); __Pyx_XDECREF(__pyx_t_10); __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); @@ -6263,7 +7181,7 @@ static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx return __pyx_r; } -/* "View.MemoryView":179 +/* "View.MemoryView":183 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< @@ -6277,14 +7195,14 @@ static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); - __pyx_r = __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_bufmode; int __pyx_r; __Pyx_RefNannyDeclarations @@ -6295,16 +7213,13 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a Py_ssize_t __pyx_t_5; int __pyx_t_6; Py_ssize_t *__pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "View.MemoryView":180 + /* "View.MemoryView":184 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * cdef int bufmode = -1 # <<<<<<<<<<<<<< @@ -6313,18 +7228,18 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a */ __pyx_v_bufmode = -1; - /* "View.MemoryView":181 + /* "View.MemoryView":185 * def __getbuffer__(self, Py_buffer *info, int flags): * cdef int bufmode = -1 * if self.mode == u"c": # <<<<<<<<<<<<<< * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": */ - __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 185, __pyx_L1_error) __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":182 + /* "View.MemoryView":186 * cdef int bufmode = -1 * if self.mode == u"c": * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< @@ -6332,21 +7247,29 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS */ __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); + + /* "View.MemoryView":185 + * def __getbuffer__(self, Py_buffer *info, int flags): + * cdef int bufmode = -1 + * if self.mode == u"c": # <<<<<<<<<<<<<< + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": + */ goto __pyx_L3; } - /* "View.MemoryView":183 + /* "View.MemoryView":187 * if self.mode == u"c": * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": # <<<<<<<<<<<<<< * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): */ - __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(1, 187, __pyx_L1_error) __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { - /* "View.MemoryView":184 + /* "View.MemoryView":188 * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< @@ -6354,11 +7277,18 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a * raise ValueError("Can only create a buffer that is contiguous in memory.") */ __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); - goto __pyx_L3; + + /* "View.MemoryView":187 + * if self.mode == u"c": + * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * elif self.mode == u"fortran": # <<<<<<<<<<<<<< + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): + */ } __pyx_L3:; - /* "View.MemoryView":185 + /* "View.MemoryView":189 * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): # <<<<<<<<<<<<<< @@ -6368,21 +7298,29 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); if (__pyx_t_1) { - /* "View.MemoryView":186 + /* "View.MemoryView":190 * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< * info.buf = self.data * info.len = self.len */ - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__18, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 190, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 190, __pyx_L1_error) + + /* "View.MemoryView":189 + * elif self.mode == u"fortran": + * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS + * if not (flags & bufmode): # <<<<<<<<<<<<<< + * raise ValueError("Can only create a buffer that is contiguous in memory.") + * info.buf = self.data + */ } - /* "View.MemoryView":187 + /* "View.MemoryView":191 * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data # <<<<<<<<<<<<<< @@ -6392,7 +7330,7 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a __pyx_t_4 = __pyx_v_self->data; __pyx_v_info->buf = __pyx_t_4; - /* "View.MemoryView":188 + /* "View.MemoryView":192 * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data * info.len = self.len # <<<<<<<<<<<<<< @@ -6402,7 +7340,7 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a __pyx_t_5 = __pyx_v_self->len; __pyx_v_info->len = __pyx_t_5; - /* "View.MemoryView":189 + /* "View.MemoryView":193 * info.buf = self.data * info.len = self.len * info.ndim = self.ndim # <<<<<<<<<<<<<< @@ -6412,7 +7350,7 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a __pyx_t_6 = __pyx_v_self->ndim; __pyx_v_info->ndim = __pyx_t_6; - /* "View.MemoryView":190 + /* "View.MemoryView":194 * info.len = self.len * info.ndim = self.ndim * info.shape = self._shape # <<<<<<<<<<<<<< @@ -6422,7 +7360,7 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a __pyx_t_7 = __pyx_v_self->_shape; __pyx_v_info->shape = __pyx_t_7; - /* "View.MemoryView":191 + /* "View.MemoryView":195 * info.ndim = self.ndim * info.shape = self._shape * info.strides = self._strides # <<<<<<<<<<<<<< @@ -6432,7 +7370,7 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a __pyx_t_7 = __pyx_v_self->_strides; __pyx_v_info->strides = __pyx_t_7; - /* "View.MemoryView":192 + /* "View.MemoryView":196 * info.shape = self._shape * info.strides = self._strides * info.suboffsets = NULL # <<<<<<<<<<<<<< @@ -6441,7 +7379,7 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a */ __pyx_v_info->suboffsets = NULL; - /* "View.MemoryView":193 + /* "View.MemoryView":197 * info.strides = self._strides * info.suboffsets = NULL * info.itemsize = self.itemsize # <<<<<<<<<<<<<< @@ -6451,7 +7389,7 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a __pyx_t_5 = __pyx_v_self->itemsize; __pyx_v_info->itemsize = __pyx_t_5; - /* "View.MemoryView":194 + /* "View.MemoryView":198 * info.suboffsets = NULL * info.itemsize = self.itemsize * info.readonly = 0 # <<<<<<<<<<<<<< @@ -6460,7 +7398,7 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a */ __pyx_v_info->readonly = 0; - /* "View.MemoryView":196 + /* "View.MemoryView":200 * info.readonly = 0 * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< @@ -6470,7 +7408,7 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { - /* "View.MemoryView":197 + /* "View.MemoryView":201 * * if flags & PyBUF_FORMAT: * info.format = self.format # <<<<<<<<<<<<<< @@ -6479,22 +7417,30 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a */ __pyx_t_4 = __pyx_v_self->format; __pyx_v_info->format = __pyx_t_4; + + /* "View.MemoryView":200 + * info.readonly = 0 + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.format + * else: + */ goto __pyx_L5; } - /*else*/ { - /* "View.MemoryView":199 + /* "View.MemoryView":203 * info.format = self.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.obj = self */ + /*else*/ { __pyx_v_info->format = NULL; } __pyx_L5:; - /* "View.MemoryView":201 + /* "View.MemoryView":205 * info.format = NULL * * info.obj = self # <<<<<<<<<<<<<< @@ -6507,7 +7453,7 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); - /* "View.MemoryView":179 + /* "View.MemoryView":183 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< @@ -6537,7 +7483,7 @@ static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_a return __pyx_r; } -/* "View.MemoryView":205 +/* "View.MemoryView":209 * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") * * def __dealloc__(array self): # <<<<<<<<<<<<<< @@ -6550,18 +7496,18 @@ static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_array_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); + __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } -static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { +static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__dealloc__", 0); - /* "View.MemoryView":206 + /* "View.MemoryView":210 * * def __dealloc__(array self): * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< @@ -6571,7 +7517,7 @@ static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *_ __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":207 + /* "View.MemoryView":211 * def __dealloc__(array self): * if self.callback_free_data != NULL: * self.callback_free_data(self.data) # <<<<<<<<<<<<<< @@ -6579,10 +7525,18 @@ static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *_ * if self.dtype_is_object: */ __pyx_v_self->callback_free_data(__pyx_v_self->data); + + /* "View.MemoryView":210 + * + * def __dealloc__(array self): + * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< + * self.callback_free_data(self.data) + * elif self.free_data: + */ goto __pyx_L3; } - /* "View.MemoryView":208 + /* "View.MemoryView":212 * if self.callback_free_data != NULL: * self.callback_free_data(self.data) * elif self.free_data: # <<<<<<<<<<<<<< @@ -6592,7 +7546,7 @@ static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *_ __pyx_t_1 = (__pyx_v_self->free_data != 0); if (__pyx_t_1) { - /* "View.MemoryView":209 + /* "View.MemoryView":213 * self.callback_free_data(self.data) * elif self.free_data: * if self.dtype_is_object: # <<<<<<<<<<<<<< @@ -6602,7 +7556,7 @@ static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *_ __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_1) { - /* "View.MemoryView":210 + /* "View.MemoryView":214 * elif self.free_data: * if self.dtype_is_object: * refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<< @@ -6610,32 +7564,45 @@ static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *_ * free(self.data) */ __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); - goto __pyx_L4; + + /* "View.MemoryView":213 + * self.callback_free_data(self.data) + * elif self.free_data: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice(self.data, self._shape, + * self._strides, self.ndim, False) + */ } - __pyx_L4:; - /* "View.MemoryView":212 + /* "View.MemoryView":216 * refcount_objects_in_slice(self.data, self._shape, * self._strides, self.ndim, False) * free(self.data) # <<<<<<<<<<<<<< - * PyMem_Free(self._shape) + * PyObject_Free(self._shape) * */ free(__pyx_v_self->data); - goto __pyx_L3; + + /* "View.MemoryView":212 + * if self.callback_free_data != NULL: + * self.callback_free_data(self.data) + * elif self.free_data: # <<<<<<<<<<<<<< + * if self.dtype_is_object: + * refcount_objects_in_slice(self.data, self._shape, + */ } __pyx_L3:; - /* "View.MemoryView":213 + /* "View.MemoryView":217 * self._strides, self.ndim, False) * free(self.data) - * PyMem_Free(self._shape) # <<<<<<<<<<<<<< + * PyObject_Free(self._shape) # <<<<<<<<<<<<<< * - * property memview: + * @property */ - PyMem_Free(__pyx_v_self->_shape); + PyObject_Free(__pyx_v_self->_shape); - /* "View.MemoryView":205 + /* "View.MemoryView":209 * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") * * def __dealloc__(array self): # <<<<<<<<<<<<<< @@ -6647,84 +7614,128 @@ static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *_ __Pyx_RefNannyFinishContext(); } -/* "View.MemoryView":217 - * property memview: - * @cname('get_memview') - * def __get__(self): # <<<<<<<<<<<<<< +/* "View.MemoryView":220 + * + * @property + * def memview(self): # <<<<<<<<<<<<<< + * return self.get_memview() * - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE */ /* Python wrapper */ -static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ -static PyObject *get_memview(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = get_memview_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); + __pyx_r = __pyx_pf_15View_dot_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { - int __pyx_v_flags; +static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":219 - * def __get__(self): - * - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< - * return memoryview(self, flags, self.dtype_is_object) + /* "View.MemoryView":221 + * @property + * def memview(self): + * return self.get_memview() # <<<<<<<<<<<<<< * + * @cname('get_memview') */ - __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = ((struct __pyx_vtabstruct_array *)__pyx_v_self->__pyx_vtab)->get_memview(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 221, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_r = __pyx_t_1; + __pyx_t_1 = 0; + goto __pyx_L0; /* "View.MemoryView":220 * - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE - * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< + * @property + * def memview(self): # <<<<<<<<<<<<<< + * return self.get_memview() + * + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":224 + * + * @cname('get_memview') + * cdef get_memview(self): # <<<<<<<<<<<<<< + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) + */ + +static PyObject *__pyx_array_get_memview(struct __pyx_array_obj *__pyx_v_self) { + int __pyx_v_flags; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + __Pyx_RefNannySetupContext("get_memview", 0); + + /* "View.MemoryView":225 + * @cname('get_memview') + * cdef get_memview(self): + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< + * return memoryview(self, flags, self.dtype_is_object) * + */ + __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); + + /* "View.MemoryView":226 + * cdef get_memview(self): + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< * + * def __len__(self): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 226, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 226, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 226, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(((PyObject *)__pyx_v_self)); - PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 226, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; - /* "View.MemoryView":217 - * property memview: - * @cname('get_memview') - * def __get__(self): # <<<<<<<<<<<<<< + /* "View.MemoryView":224 * - * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * @cname('get_memview') + * cdef get_memview(self): # <<<<<<<<<<<<<< + * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE + * return memoryview(self, flags, self.dtype_is_object) */ /* function exit code */ @@ -6732,64 +7743,111 @@ static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_arr __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); - __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); - __pyx_r = NULL; + __Pyx_AddTraceback("View.MemoryView.array.get_memview", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "View.MemoryView":223 - * +/* "View.MemoryView":228 + * return memoryview(self, flags, self.dtype_is_object) * - * def __getattr__(self, attr): # <<<<<<<<<<<<<< - * return getattr(self.memview, attr) + * def __len__(self): # <<<<<<<<<<<<<< + * return self._shape[0] * */ /* Python wrapper */ -static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ -static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { - PyObject *__pyx_r = 0; +static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self); /*proto*/ +static Py_ssize_t __pyx_array___len__(PyObject *__pyx_v_self) { + Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations - __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); - __pyx_r = __pyx_array_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); + __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { - PyObject *__pyx_r = NULL; +static Py_ssize_t __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__len__(struct __pyx_array_obj *__pyx_v_self) { + Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations - PyObject *__pyx_t_1 = NULL; - PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - __Pyx_RefNannySetupContext("__getattr__", 0); + __Pyx_RefNannySetupContext("__len__", 0); - /* "View.MemoryView":224 + /* "View.MemoryView":229 * - * def __getattr__(self, attr): - * return getattr(self.memview, attr) # <<<<<<<<<<<<<< + * def __len__(self): + * return self._shape[0] # <<<<<<<<<<<<<< * - * def __getitem__(self, item): + * def __getattr__(self, attr): */ - __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_r = (__pyx_v_self->_shape[0]); + goto __pyx_L0; + + /* "View.MemoryView":228 + * return memoryview(self, flags, self.dtype_is_object) + * + * def __len__(self): # <<<<<<<<<<<<<< + * return self._shape[0] + * + */ + + /* function exit code */ + __pyx_L0:; + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":231 + * return self._shape[0] + * + * def __getattr__(self, attr): # <<<<<<<<<<<<<< + * return getattr(self.memview, attr) + * + */ + +/* Python wrapper */ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ +static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + PyObject *__pyx_t_2 = NULL; + __Pyx_RefNannySetupContext("__getattr__", 0); + + /* "View.MemoryView":232 + * + * def __getattr__(self, attr): + * return getattr(self.memview, attr) # <<<<<<<<<<<<<< + * + * def __getitem__(self, item): + */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 232, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 232, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; - /* "View.MemoryView":223 - * + /* "View.MemoryView":231 + * return self._shape[0] * * def __getattr__(self, attr): # <<<<<<<<<<<<<< * return getattr(self.memview, attr) @@ -6808,7 +7866,7 @@ static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_o return __pyx_r; } -/* "View.MemoryView":226 +/* "View.MemoryView":234 * return getattr(self.memview, attr) * * def __getitem__(self, item): # <<<<<<<<<<<<<< @@ -6822,24 +7880,21 @@ static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); - __pyx_r = __pyx_array_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { +static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getitem__", 0); - /* "View.MemoryView":227 + /* "View.MemoryView":235 * * def __getitem__(self, item): * return self.memview[item] # <<<<<<<<<<<<<< @@ -6847,16 +7902,16 @@ static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_o * def __setitem__(self, item, value): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 235, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 235, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; - /* "View.MemoryView":226 + /* "View.MemoryView":234 * return getattr(self.memview, attr) * * def __getitem__(self, item): # <<<<<<<<<<<<<< @@ -6876,7 +7931,7 @@ static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_o return __pyx_r; } -/* "View.MemoryView":229 +/* "View.MemoryView":237 * return self.memview[item] * * def __setitem__(self, item, value): # <<<<<<<<<<<<<< @@ -6890,35 +7945,32 @@ static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_ite int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); - __pyx_r = __pyx_array_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); + __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { +static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_12__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setitem__", 0); - /* "View.MemoryView":230 + /* "View.MemoryView":238 * * def __setitem__(self, item, value): * self.memview[item] = value # <<<<<<<<<<<<<< * * */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 238, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) __PYX_ERR(1, 238, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "View.MemoryView":229 + /* "View.MemoryView":237 * return self.memview[item] * * def __setitem__(self, item, value): # <<<<<<<<<<<<<< @@ -6938,7 +7990,114 @@ static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *_ return __pyx_r; } -/* "View.MemoryView":234 +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw___pyx_array_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_array___reduce_cython__(((struct __pyx_array_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_array___reduce_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(1, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ +static PyObject *__pyx_pw___pyx_array_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_array_2__setstate_cython__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_array_2__setstate_cython__(CYTHON_UNUSED struct __pyx_array_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":4 + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(1, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.array.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":242 * * @cname("__pyx_array_new") * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< @@ -6955,12 +8114,9 @@ static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("array_cwrapper", 0); - /* "View.MemoryView":238 + /* "View.MemoryView":246 * cdef array result * * if buf == NULL: # <<<<<<<<<<<<<< @@ -6970,96 +8126,104 @@ static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":239 + /* "View.MemoryView":247 * * if buf == NULL: * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), */ - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 247, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 247, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 247, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 247, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); __pyx_t_2 = 0; __pyx_t_3 = 0; __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 247, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); __pyx_t_4 = 0; + + /* "View.MemoryView":246 + * cdef array result + * + * if buf == NULL: # <<<<<<<<<<<<<< + * result = array(shape, itemsize, format, mode.decode('ASCII')) + * else: + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":241 + /* "View.MemoryView":249 * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< * allocate_buffer=False) * result.data = buf */ - __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*else*/ { + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); - __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_v_shape); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); __pyx_t_4 = 0; __pyx_t_5 = 0; __pyx_t_3 = 0; - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - /* "View.MemoryView":242 + /* "View.MemoryView":250 * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), * allocate_buffer=False) # <<<<<<<<<<<<<< * result.data = buf * */ - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyDict_NewPresized(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 250, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) __PYX_ERR(1, 250, __pyx_L1_error) - /* "View.MemoryView":241 + /* "View.MemoryView":249 * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< * allocate_buffer=False) * result.data = buf */ - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)__pyx_array_type), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); __pyx_t_5 = 0; - /* "View.MemoryView":243 + /* "View.MemoryView":251 * result = array(shape, itemsize, format, mode.decode('ASCII'), * allocate_buffer=False) * result.data = buf # <<<<<<<<<<<<<< @@ -7070,7 +8234,7 @@ static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize } __pyx_L3:; - /* "View.MemoryView":245 + /* "View.MemoryView":253 * result.data = buf * * return result # <<<<<<<<<<<<<< @@ -7082,7 +8246,7 @@ static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize __pyx_r = __pyx_v_result; goto __pyx_L0; - /* "View.MemoryView":234 + /* "View.MemoryView":242 * * @cname("__pyx_array_new") * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< @@ -7105,7 +8269,7 @@ static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize return __pyx_r; } -/* "View.MemoryView":271 +/* "View.MemoryView":279 * cdef class Enum(object): * cdef object name * def __init__(self, name): # <<<<<<<<<<<<<< @@ -7117,9 +8281,6 @@ static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_name = 0; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); @@ -7131,6 +8292,7 @@ static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_ar const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -7141,7 +8303,7 @@ static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_ar else goto __pyx_L5_argtuple_error; } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) __PYX_ERR(1, 279, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { goto __pyx_L5_argtuple_error; @@ -7152,25 +8314,25 @@ static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_ar } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 279, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); + __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { +static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__init__", 0); - /* "View.MemoryView":272 + /* "View.MemoryView":280 * cdef object name * def __init__(self, name): * self.name = name # <<<<<<<<<<<<<< @@ -7183,7 +8345,7 @@ static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_ __Pyx_DECREF(__pyx_v_self->name); __pyx_v_self->name = __pyx_v_name; - /* "View.MemoryView":271 + /* "View.MemoryView":279 * cdef class Enum(object): * cdef object name * def __init__(self, name): # <<<<<<<<<<<<<< @@ -7197,7 +8359,7 @@ static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_ return __pyx_r; } -/* "View.MemoryView":273 +/* "View.MemoryView":281 * def __init__(self, name): * self.name = name * def __repr__(self): # <<<<<<<<<<<<<< @@ -7211,19 +8373,19 @@ static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_MemviewEnum_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); + __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { +static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__repr__", 0); - /* "View.MemoryView":274 + /* "View.MemoryView":282 * self.name = name * def __repr__(self): * return self.name # <<<<<<<<<<<<<< @@ -7235,7 +8397,7 @@ static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_Memvi __pyx_r = __pyx_v_self->name; goto __pyx_L0; - /* "View.MemoryView":273 + /* "View.MemoryView":281 * def __init__(self, name): * self.name = name * def __repr__(self): # <<<<<<<<<<<<<< @@ -7250,84 +8412,377 @@ static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_Memvi return __pyx_r; } -/* "View.MemoryView":288 - * - * @cname('__pyx_align_pointer') - * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< - * "Align pointer memory on a given boundary" - * cdef Py_intptr_t aligned_p = memory +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef bint use_setstate + * state = (self.name,) */ -static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { - Py_intptr_t __pyx_v_aligned_p; - size_t __pyx_v_offset; - void *__pyx_r; - int __pyx_t_1; +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw___pyx_MemviewEnum_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_MemviewEnum___reduce_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); - /* "View.MemoryView":290 - * cdef void *align_pointer(void *memory, size_t alignment) nogil: - * "Align pointer memory on a given boundary" - * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< - * cdef size_t offset - * + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_MemviewEnum___reduce_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { + int __pyx_v_use_setstate; + PyObject *__pyx_v_state = NULL; + PyObject *__pyx_v__dict = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + int __pyx_t_3; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * cdef bint use_setstate + * state = (self.name,) # <<<<<<<<<<<<<< + * _dict = getattr(self, '__dict__', None) + * if _dict is not None: */ - __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v_self->name); + __Pyx_GIVEREF(__pyx_v_self->name); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v_self->name); + __pyx_v_state = ((PyObject*)__pyx_t_1); + __pyx_t_1 = 0; - /* "View.MemoryView":294 - * - * with cython.cdivision(True): - * offset = aligned_p % alignment # <<<<<<<<<<<<<< - * - * if offset > 0: + /* "(tree fragment)":4 + * cdef bint use_setstate + * state = (self.name,) + * _dict = getattr(self, '__dict__', None) # <<<<<<<<<<<<<< + * if _dict is not None: + * state += (_dict,) */ - __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); + __pyx_t_1 = __Pyx_GetAttr3(((PyObject *)__pyx_v_self), __pyx_n_s_dict, Py_None); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __pyx_v__dict = __pyx_t_1; + __pyx_t_1 = 0; - /* "View.MemoryView":296 - * offset = aligned_p % alignment - * - * if offset > 0: # <<<<<<<<<<<<<< - * aligned_p += alignment - offset - * + /* "(tree fragment)":5 + * state = (self.name,) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True */ - __pyx_t_1 = ((__pyx_v_offset > 0) != 0); - if (__pyx_t_1) { + __pyx_t_2 = (__pyx_v__dict != Py_None); + __pyx_t_3 = (__pyx_t_2 != 0); + if (__pyx_t_3) { - /* "View.MemoryView":297 - * - * if offset > 0: - * aligned_p += alignment - offset # <<<<<<<<<<<<<< - * - * return aligned_p + /* "(tree fragment)":6 + * _dict = getattr(self, '__dict__', None) + * if _dict is not None: + * state += (_dict,) # <<<<<<<<<<<<<< + * use_setstate = True + * else: + */ + __pyx_t_1 = PyTuple_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(__pyx_v__dict); + __Pyx_GIVEREF(__pyx_v__dict); + PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_v__dict); + __pyx_t_4 = PyNumber_InPlaceAdd(__pyx_v_state, __pyx_t_1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 6, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __Pyx_DECREF_SET(__pyx_v_state, ((PyObject*)__pyx_t_4)); + __pyx_t_4 = 0; + + /* "(tree fragment)":7 + * if _dict is not None: + * state += (_dict,) + * use_setstate = True # <<<<<<<<<<<<<< + * else: + * use_setstate = self.name is not None + */ + __pyx_v_use_setstate = 1; + + /* "(tree fragment)":5 + * state = (self.name,) + * _dict = getattr(self, '__dict__', None) + * if _dict is not None: # <<<<<<<<<<<<<< + * state += (_dict,) + * use_setstate = True */ - __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); goto __pyx_L3; } + + /* "(tree fragment)":9 + * use_setstate = True + * else: + * use_setstate = self.name is not None # <<<<<<<<<<<<<< + * if use_setstate: + * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state + */ + /*else*/ { + __pyx_t_3 = (__pyx_v_self->name != Py_None); + __pyx_v_use_setstate = __pyx_t_3; + } __pyx_L3:; - /* "View.MemoryView":299 - * aligned_p += alignment - offset - * - * return aligned_p # <<<<<<<<<<<<<< - * - * @cname('__pyx_memoryview') + /* "(tree fragment)":10 + * else: + * use_setstate = self.name is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state + * else: */ - __pyx_r = ((void *)__pyx_v_aligned_p); - goto __pyx_L0; + __pyx_t_3 = (__pyx_v_use_setstate != 0); + if (__pyx_t_3) { - /* "View.MemoryView":288 - * - * @cname('__pyx_align_pointer') - * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< - * "Align pointer memory on a given boundary" - * cdef Py_intptr_t aligned_p = memory + /* "(tree fragment)":11 + * use_setstate = self.name is not None + * if use_setstate: + * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state # <<<<<<<<<<<<<< + * else: + * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) */ + __Pyx_XDECREF(__pyx_r); + __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 11, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 11, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_INCREF(__pyx_int_184977713); + __Pyx_GIVEREF(__pyx_int_184977713); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); + __Pyx_INCREF(Py_None); + __Pyx_GIVEREF(Py_None); + PyTuple_SET_ITEM(__pyx_t_1, 2, Py_None); + __pyx_t_5 = PyTuple_New(3); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 11, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_1); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_v_state); + __pyx_t_4 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; + goto __pyx_L0; - /* function exit code */ - __pyx_L0:; - return __pyx_r; -} + /* "(tree fragment)":10 + * else: + * use_setstate = self.name is not None + * if use_setstate: # <<<<<<<<<<<<<< + * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state + * else: + */ + } -/* "View.MemoryView":317 + /* "(tree fragment)":13 + * return __pyx_unpickle_Enum, (type(self), 0xb068931, None), state + * else: + * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_Enum__set_state(self, __pyx_state) + */ + /*else*/ { + __Pyx_XDECREF(__pyx_r); + __pyx_t_5 = __Pyx_GetModuleGlobalName(__pyx_n_s_pyx_unpickle_Enum); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __pyx_t_1 = PyTuple_New(3); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_INCREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_GIVEREF(((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + PyTuple_SET_ITEM(__pyx_t_1, 0, ((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self)))); + __Pyx_INCREF(__pyx_int_184977713); + __Pyx_GIVEREF(__pyx_int_184977713); + PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_int_184977713); + __Pyx_INCREF(__pyx_v_state); + __Pyx_GIVEREF(__pyx_v_state); + PyTuple_SET_ITEM(__pyx_t_1, 2, __pyx_v_state); + __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 13, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_5); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_1); + __pyx_t_5 = 0; + __pyx_t_1 = 0; + __pyx_r = __pyx_t_4; + __pyx_t_4 = 0; + goto __pyx_L0; + } + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * cdef bint use_setstate + * state = (self.name,) + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_AddTraceback("View.MemoryView.Enum.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v_state); + __Pyx_XDECREF(__pyx_v__dict); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":14 + * else: + * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_Enum__set_state(self, __pyx_state) + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ +static PyObject *__pyx_pw___pyx_MemviewEnum_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_MemviewEnum_2__setstate_cython__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_MemviewEnum_2__setstate_cython__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":15 + * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) + * def __setstate_cython__(self, __pyx_state): + * __pyx_unpickle_Enum__set_state(self, __pyx_state) # <<<<<<<<<<<<<< + */ + if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 15, __pyx_L1_error) + __pyx_t_1 = __pyx_unpickle_Enum__set_state(__pyx_v_self, ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 15, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "(tree fragment)":14 + * else: + * return __pyx_unpickle_Enum, (type(self), 0xb068931, state) + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * __pyx_unpickle_Enum__set_state(self, __pyx_state) + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.Enum.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":296 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + +static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { + Py_intptr_t __pyx_v_aligned_p; + size_t __pyx_v_offset; + void *__pyx_r; + int __pyx_t_1; + + /* "View.MemoryView":298 + * cdef void *align_pointer(void *memory, size_t alignment) nogil: + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory # <<<<<<<<<<<<<< + * cdef size_t offset + * + */ + __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); + + /* "View.MemoryView":302 + * + * with cython.cdivision(True): + * offset = aligned_p % alignment # <<<<<<<<<<<<<< + * + * if offset > 0: + */ + __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); + + /* "View.MemoryView":304 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + __pyx_t_1 = ((__pyx_v_offset > 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":305 + * + * if offset > 0: + * aligned_p += alignment - offset # <<<<<<<<<<<<<< + * + * return aligned_p + */ + __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); + + /* "View.MemoryView":304 + * offset = aligned_p % alignment + * + * if offset > 0: # <<<<<<<<<<<<<< + * aligned_p += alignment - offset + * + */ + } + + /* "View.MemoryView":307 + * aligned_p += alignment - offset + * + * return aligned_p # <<<<<<<<<<<<<< + * + * + */ + __pyx_r = ((void *)__pyx_v_aligned_p); + goto __pyx_L0; + + /* "View.MemoryView":296 + * + * @cname('__pyx_align_pointer') + * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< + * "Align pointer memory on a given boundary" + * cdef Py_intptr_t aligned_p = memory + */ + + /* function exit code */ + __pyx_L0:; + return __pyx_r; +} + +/* "View.MemoryView":343 * cdef __Pyx_TypeInfo *typeinfo * * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< @@ -7341,9 +8796,6 @@ static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_ar PyObject *__pyx_v_obj = 0; int __pyx_v_flags; int __pyx_v_dtype_is_object; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); @@ -7355,8 +8807,11 @@ static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_ar const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } @@ -7365,11 +8820,13 @@ static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_ar case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; else { - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); __PYX_ERR(1, 343, __pyx_L3_error) } + CYTHON_FALLTHROUGH; case 2: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dtype_is_object); @@ -7377,11 +8834,12 @@ static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_ar } } if (unlikely(kw_args > 0)) { - if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) __PYX_ERR(1, 343, __pyx_L3_error) } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; @@ -7389,43 +8847,38 @@ static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_ar } } __pyx_v_obj = values[0]; - __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 343, __pyx_L3_error) if (values[2]) { - __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 343, __pyx_L3_error) } else { __pyx_v_dtype_is_object = ((int)0); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; - __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 343, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; - __pyx_r = __pyx_memoryview_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__cinit__", 0); - /* "View.MemoryView":318 + /* "View.MemoryView":344 * * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): * self.obj = obj # <<<<<<<<<<<<<< @@ -7438,7 +8891,7 @@ static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memor __Pyx_DECREF(__pyx_v_self->obj); __pyx_v_self->obj = __pyx_v_obj; - /* "View.MemoryView":319 + /* "View.MemoryView":345 * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): * self.obj = obj * self.flags = flags # <<<<<<<<<<<<<< @@ -7447,14 +8900,14 @@ static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memor */ __pyx_v_self->flags = __pyx_v_flags; - /* "View.MemoryView":320 + /* "View.MemoryView":346 * self.obj = obj * self.flags = flags * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< * __Pyx_GetBuffer(obj, &self.view, flags) * if self.view.obj == NULL: */ - __pyx_t_2 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)((PyObject *)__pyx_memoryview_type))); + __pyx_t_2 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)__pyx_memoryview_type)); __pyx_t_3 = (__pyx_t_2 != 0); if (!__pyx_t_3) { } else { @@ -7467,16 +8920,16 @@ static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memor __pyx_L4_bool_binop_done:; if (__pyx_t_1) { - /* "View.MemoryView":321 + /* "View.MemoryView":347 * self.flags = flags * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< * if self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None */ - __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 321; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 347, __pyx_L1_error) - /* "View.MemoryView":322 + /* "View.MemoryView":348 * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) * if self.view.obj == NULL: # <<<<<<<<<<<<<< @@ -7486,7 +8939,7 @@ static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memor __pyx_t_1 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":323 + /* "View.MemoryView":349 * __Pyx_GetBuffer(obj, &self.view, flags) * if self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< @@ -7495,90 +8948,177 @@ static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memor */ ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; - /* "View.MemoryView":324 + /* "View.MemoryView":350 * if self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * - * self.lock = PyThread_allocate_lock() + * global __pyx_memoryview_thread_locks_used */ Py_INCREF(Py_None); - goto __pyx_L6; + + /* "View.MemoryView":348 + * if type(self) is memoryview or obj is not None: + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: # <<<<<<<<<<<<<< + * (<__pyx_buffer *> &self.view).obj = Py_None + * Py_INCREF(Py_None) + */ } - __pyx_L6:; - goto __pyx_L3; + + /* "View.MemoryView":346 + * self.obj = obj + * self.flags = flags + * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< + * __Pyx_GetBuffer(obj, &self.view, flags) + * if self.view.obj == NULL: + */ } - __pyx_L3:; - /* "View.MemoryView":326 - * Py_INCREF(Py_None) + /* "View.MemoryView":353 * - * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< - * if self.lock == NULL: - * raise MemoryError + * global __pyx_memoryview_thread_locks_used + * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< + * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] + * __pyx_memoryview_thread_locks_used += 1 + */ + __pyx_t_1 = ((__pyx_memoryview_thread_locks_used < 8) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":354 + * global __pyx_memoryview_thread_locks_used + * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: + * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] # <<<<<<<<<<<<<< + * __pyx_memoryview_thread_locks_used += 1 + * if self.lock is NULL: */ - __pyx_v_self->lock = PyThread_allocate_lock(); + __pyx_v_self->lock = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); - /* "View.MemoryView":327 - * - * self.lock = PyThread_allocate_lock() - * if self.lock == NULL: # <<<<<<<<<<<<<< - * raise MemoryError + /* "View.MemoryView":355 + * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: + * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] + * __pyx_memoryview_thread_locks_used += 1 # <<<<<<<<<<<<<< + * if self.lock is NULL: + * self.lock = PyThread_allocate_lock() + */ + __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used + 1); + + /* "View.MemoryView":353 * + * global __pyx_memoryview_thread_locks_used + * if __pyx_memoryview_thread_locks_used < THREAD_LOCKS_PREALLOCATED: # <<<<<<<<<<<<<< + * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] + * __pyx_memoryview_thread_locks_used += 1 + */ + } + + /* "View.MemoryView":356 + * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] + * __pyx_memoryview_thread_locks_used += 1 + * if self.lock is NULL: # <<<<<<<<<<<<<< + * self.lock = PyThread_allocate_lock() + * if self.lock is NULL: */ __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":328 - * self.lock = PyThread_allocate_lock() - * if self.lock == NULL: - * raise MemoryError # <<<<<<<<<<<<<< + /* "View.MemoryView":357 + * __pyx_memoryview_thread_locks_used += 1 + * if self.lock is NULL: + * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< + * if self.lock is NULL: + * raise MemoryError + */ + __pyx_v_self->lock = PyThread_allocate_lock(); + + /* "View.MemoryView":358 + * if self.lock is NULL: + * self.lock = PyThread_allocate_lock() + * if self.lock is NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":359 + * self.lock = PyThread_allocate_lock() + * if self.lock is NULL: + * raise MemoryError # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ - PyErr_NoMemory(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyErr_NoMemory(); __PYX_ERR(1, 359, __pyx_L1_error) + + /* "View.MemoryView":358 + * if self.lock is NULL: + * self.lock = PyThread_allocate_lock() + * if self.lock is NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * + */ + } + + /* "View.MemoryView":356 + * self.lock = __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] + * __pyx_memoryview_thread_locks_used += 1 + * if self.lock is NULL: # <<<<<<<<<<<<<< + * self.lock = PyThread_allocate_lock() + * if self.lock is NULL: + */ } - /* "View.MemoryView":330 - * raise MemoryError + /* "View.MemoryView":361 + * raise MemoryError * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< - * self.dtype_is_object = self.view.format == b'O' + * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { - /* "View.MemoryView":331 + /* "View.MemoryView":362 * * if flags & PyBUF_FORMAT: - * self.dtype_is_object = self.view.format == b'O' # <<<<<<<<<<<<<< + * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') # <<<<<<<<<<<<<< * else: * self.dtype_is_object = dtype_is_object */ - __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = PyObject_RichCompare(__pyx_t_5, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __pyx_t_2 = (((__pyx_v_self->view.format[0]) == 'O') != 0); + if (__pyx_t_2) { + } else { + __pyx_t_1 = __pyx_t_2; + goto __pyx_L11_bool_binop_done; + } + __pyx_t_2 = (((__pyx_v_self->view.format[1]) == '\x00') != 0); + __pyx_t_1 = __pyx_t_2; + __pyx_L11_bool_binop_done:; __pyx_v_self->dtype_is_object = __pyx_t_1; - goto __pyx_L8; + + /* "View.MemoryView":361 + * raise MemoryError + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') + * else: + */ + goto __pyx_L10; } - /*else*/ { - /* "View.MemoryView":333 - * self.dtype_is_object = self.view.format == b'O' + /* "View.MemoryView":364 + * self.dtype_is_object = (self.view.format[0] == b'O' and self.view.format[1] == b'\0') * else: * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< * * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( */ + /*else*/ { __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; } - __pyx_L8:; + __pyx_L10:; - /* "View.MemoryView":335 + /* "View.MemoryView":366 * self.dtype_is_object = dtype_is_object * * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< @@ -7587,7 +9127,7 @@ static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memor */ __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); - /* "View.MemoryView":337 + /* "View.MemoryView":368 * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( * &self.acquisition_count[0], sizeof(__pyx_atomic_int)) * self.typeinfo = NULL # <<<<<<<<<<<<<< @@ -7596,7 +9136,7 @@ static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memor */ __pyx_v_self->typeinfo = NULL; - /* "View.MemoryView":317 + /* "View.MemoryView":343 * cdef __Pyx_TypeInfo *typeinfo * * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< @@ -7608,8 +9148,6 @@ static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memor __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_5); - __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; @@ -7617,7 +9155,7 @@ static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memor return __pyx_r; } -/* "View.MemoryView":339 +/* "View.MemoryView":370 * self.typeinfo = NULL * * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< @@ -7630,19 +9168,24 @@ static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } -static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { +static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { + int __pyx_v_i; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; + int __pyx_t_3; + int __pyx_t_4; + PyThread_type_lock __pyx_t_5; + PyThread_type_lock __pyx_t_6; __Pyx_RefNannySetupContext("__dealloc__", 0); - /* "View.MemoryView":340 + /* "View.MemoryView":371 * * def __dealloc__(memoryview self): * if self.obj is not None: # <<<<<<<<<<<<<< @@ -7653,79 +9196,179 @@ static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_m __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":341 + /* "View.MemoryView":372 * def __dealloc__(memoryview self): * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< * - * if self.lock != NULL: + * cdef int i */ __Pyx_ReleaseBuffer((&__pyx_v_self->view)); - goto __pyx_L3; - } - __pyx_L3:; - /* "View.MemoryView":343 + /* "View.MemoryView":371 + * + * def __dealloc__(memoryview self): + * if self.obj is not None: # <<<<<<<<<<<<<< * __Pyx_ReleaseBuffer(&self.view) * + */ + } + + /* "View.MemoryView":376 + * cdef int i + * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: # <<<<<<<<<<<<<< - * PyThread_free_lock(self.lock) - * + * for i in range(__pyx_memoryview_thread_locks_used): + * if __pyx_memoryview_thread_locks[i] is self.lock: */ __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); if (__pyx_t_2) { - /* "View.MemoryView":344 - * + /* "View.MemoryView":377 + * global __pyx_memoryview_thread_locks_used * if self.lock != NULL: - * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< - * - * cdef char *get_item_pointer(memoryview self, object index) except NULL: + * for i in range(__pyx_memoryview_thread_locks_used): # <<<<<<<<<<<<<< + * if __pyx_memoryview_thread_locks[i] is self.lock: + * __pyx_memoryview_thread_locks_used -= 1 */ - PyThread_free_lock(__pyx_v_self->lock); - goto __pyx_L4; - } - __pyx_L4:; + __pyx_t_3 = __pyx_memoryview_thread_locks_used; + for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { + __pyx_v_i = __pyx_t_4; - /* "View.MemoryView":339 - * self.typeinfo = NULL - * - * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< - * if self.obj is not None: - * __Pyx_ReleaseBuffer(&self.view) + /* "View.MemoryView":378 + * if self.lock != NULL: + * for i in range(__pyx_memoryview_thread_locks_used): + * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< + * __pyx_memoryview_thread_locks_used -= 1 + * if i != __pyx_memoryview_thread_locks_used: */ + __pyx_t_2 = (((__pyx_memoryview_thread_locks[__pyx_v_i]) == __pyx_v_self->lock) != 0); + if (__pyx_t_2) { - /* function exit code */ - __Pyx_RefNannyFinishContext(); -} + /* "View.MemoryView":379 + * for i in range(__pyx_memoryview_thread_locks_used): + * if __pyx_memoryview_thread_locks[i] is self.lock: + * __pyx_memoryview_thread_locks_used -= 1 # <<<<<<<<<<<<<< + * if i != __pyx_memoryview_thread_locks_used: + * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( + */ + __pyx_memoryview_thread_locks_used = (__pyx_memoryview_thread_locks_used - 1); -/* "View.MemoryView":346 - * PyThread_free_lock(self.lock) - * - * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< - * cdef Py_ssize_t dim - * cdef char *itemp = self.view.buf + /* "View.MemoryView":380 + * if __pyx_memoryview_thread_locks[i] is self.lock: + * __pyx_memoryview_thread_locks_used -= 1 + * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< + * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( + * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) */ + __pyx_t_2 = ((__pyx_v_i != __pyx_memoryview_thread_locks_used) != 0); + if (__pyx_t_2) { -static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { - Py_ssize_t __pyx_v_dim; - char *__pyx_v_itemp; - PyObject *__pyx_v_idx = NULL; - char *__pyx_r; - __Pyx_RefNannyDeclarations - Py_ssize_t __pyx_t_1; + /* "View.MemoryView":382 + * if i != __pyx_memoryview_thread_locks_used: + * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( + * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) # <<<<<<<<<<<<<< + * break + * else: + */ + __pyx_t_5 = (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]); + __pyx_t_6 = (__pyx_memoryview_thread_locks[__pyx_v_i]); + + /* "View.MemoryView":381 + * __pyx_memoryview_thread_locks_used -= 1 + * if i != __pyx_memoryview_thread_locks_used: + * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( # <<<<<<<<<<<<<< + * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) + * break + */ + (__pyx_memoryview_thread_locks[__pyx_v_i]) = __pyx_t_5; + (__pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used]) = __pyx_t_6; + + /* "View.MemoryView":380 + * if __pyx_memoryview_thread_locks[i] is self.lock: + * __pyx_memoryview_thread_locks_used -= 1 + * if i != __pyx_memoryview_thread_locks_used: # <<<<<<<<<<<<<< + * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( + * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) + */ + } + + /* "View.MemoryView":383 + * __pyx_memoryview_thread_locks[i], __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used] = ( + * __pyx_memoryview_thread_locks[__pyx_memoryview_thread_locks_used], __pyx_memoryview_thread_locks[i]) + * break # <<<<<<<<<<<<<< + * else: + * PyThread_free_lock(self.lock) + */ + goto __pyx_L6_break; + + /* "View.MemoryView":378 + * if self.lock != NULL: + * for i in range(__pyx_memoryview_thread_locks_used): + * if __pyx_memoryview_thread_locks[i] is self.lock: # <<<<<<<<<<<<<< + * __pyx_memoryview_thread_locks_used -= 1 + * if i != __pyx_memoryview_thread_locks_used: + */ + } + } + /*else*/ { + + /* "View.MemoryView":385 + * break + * else: + * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: + */ + PyThread_free_lock(__pyx_v_self->lock); + } + __pyx_L6_break:; + + /* "View.MemoryView":376 + * cdef int i + * global __pyx_memoryview_thread_locks_used + * if self.lock != NULL: # <<<<<<<<<<<<<< + * for i in range(__pyx_memoryview_thread_locks_used): + * if __pyx_memoryview_thread_locks[i] is self.lock: + */ + } + + /* "View.MemoryView":370 + * self.typeinfo = NULL + * + * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< + * if self.obj is not None: + * __Pyx_ReleaseBuffer(&self.view) + */ + + /* function exit code */ + __Pyx_RefNannyFinishContext(); +} + +/* "View.MemoryView":387 + * PyThread_free_lock(self.lock) + * + * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< + * cdef Py_ssize_t dim + * cdef char *itemp = self.view.buf + */ + +static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { + Py_ssize_t __pyx_v_dim; + char *__pyx_v_itemp; + PyObject *__pyx_v_idx = NULL; + char *__pyx_r; + __Pyx_RefNannyDeclarations + Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; Py_ssize_t __pyx_t_3; PyObject *(*__pyx_t_4)(PyObject *); PyObject *__pyx_t_5 = NULL; Py_ssize_t __pyx_t_6; char *__pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_item_pointer", 0); - /* "View.MemoryView":348 + /* "View.MemoryView":389 * cdef char *get_item_pointer(memoryview self, object index) except NULL: * cdef Py_ssize_t dim * cdef char *itemp = self.view.buf # <<<<<<<<<<<<<< @@ -7734,7 +9377,7 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py */ __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); - /* "View.MemoryView":350 + /* "View.MemoryView":391 * cdef char *itemp = self.view.buf * * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< @@ -7746,25 +9389,27 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; __pyx_t_4 = NULL; } else { - __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 391, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 391, __pyx_L1_error) } for (;;) { if (likely(!__pyx_t_4)) { if (likely(PyList_CheckExact(__pyx_t_2))) { if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(1, 391, __pyx_L1_error) #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 391, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); #endif } else { if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) __PYX_ERR(1, 391, __pyx_L1_error) #else - __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 391, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); #endif } } else { @@ -7772,8 +9417,8 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py if (unlikely(!__pyx_t_5)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { - if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[1]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(1, 391, __pyx_L1_error) } break; } @@ -7784,18 +9429,18 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py __pyx_v_dim = __pyx_t_1; __pyx_t_1 = (__pyx_t_1 + 1); - /* "View.MemoryView":351 + /* "View.MemoryView":392 * * for dim, idx in enumerate(index): * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< * * return itemp */ - __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 392, __pyx_L1_error) + __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == ((char *)NULL))) __PYX_ERR(1, 392, __pyx_L1_error) __pyx_v_itemp = __pyx_t_7; - /* "View.MemoryView":350 + /* "View.MemoryView":391 * cdef char *itemp = self.view.buf * * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< @@ -7805,7 +9450,7 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "View.MemoryView":353 + /* "View.MemoryView":394 * itemp = pybuffer_index(&self.view, itemp, idx, dim) * * return itemp # <<<<<<<<<<<<<< @@ -7815,8 +9460,8 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py __pyx_r = __pyx_v_itemp; goto __pyx_L0; - /* "View.MemoryView":346 - * PyThread_free_lock(self.lock) + /* "View.MemoryView":387 + * PyThread_free_lock(self.lock) * * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< * cdef Py_ssize_t dim @@ -7835,7 +9480,7 @@ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__py return __pyx_r; } -/* "View.MemoryView":356 +/* "View.MemoryView":397 * * * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< @@ -7849,14 +9494,14 @@ static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject * PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { PyObject *__pyx_v_have_slices = NULL; PyObject *__pyx_v_indices = NULL; char *__pyx_v_itemp; @@ -7868,12 +9513,9 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __ PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; char *__pyx_t_6; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getitem__", 0); - /* "View.MemoryView":357 + /* "View.MemoryView":398 * * def __getitem__(memoryview self, object index): * if index is Ellipsis: # <<<<<<<<<<<<<< @@ -7884,7 +9526,7 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __ __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":358 + /* "View.MemoryView":399 * def __getitem__(memoryview self, object index): * if index is Ellipsis: * return self # <<<<<<<<<<<<<< @@ -7895,20 +9537,28 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __ __Pyx_INCREF(((PyObject *)__pyx_v_self)); __pyx_r = ((PyObject *)__pyx_v_self); goto __pyx_L0; + + /* "View.MemoryView":398 + * + * def __getitem__(memoryview self, object index): + * if index is Ellipsis: # <<<<<<<<<<<<<< + * return self + * + */ } - /* "View.MemoryView":360 + /* "View.MemoryView":401 * return self * * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< * * cdef char *itemp */ - __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 401, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (likely(__pyx_t_3 != Py_None)) { PyObject* sequence = __pyx_t_3; - #if CYTHON_COMPILING_IN_CPYTHON + #if !CYTHON_COMPILING_IN_PYPY Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); @@ -7916,39 +9566,39 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __ if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 401, __pyx_L1_error) } - #if CYTHON_COMPILING_IN_CPYTHON + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(__pyx_t_5); #else - __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 401, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 401, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); #endif __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else { - __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 401, __pyx_L1_error) } __pyx_v_have_slices = __pyx_t_4; __pyx_t_4 = 0; __pyx_v_indices = __pyx_t_5; __pyx_t_5 = 0; - /* "View.MemoryView":363 + /* "View.MemoryView":404 * * cdef char *itemp * if have_slices: # <<<<<<<<<<<<<< * return memview_slice(self, indices) * else: */ - __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) __PYX_ERR(1, 404, __pyx_L1_error) if (__pyx_t_2) { - /* "View.MemoryView":364 + /* "View.MemoryView":405 * cdef char *itemp * if have_slices: * return memview_slice(self, indices) # <<<<<<<<<<<<<< @@ -7956,25 +9606,33 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __ * itemp = self.get_item_pointer(indices) */ __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 364; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 405, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; + + /* "View.MemoryView":404 + * + * cdef char *itemp + * if have_slices: # <<<<<<<<<<<<<< + * return memview_slice(self, indices) + * else: + */ } - /*else*/ { - /* "View.MemoryView":366 + /* "View.MemoryView":407 * return memview_slice(self, indices) * else: * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< * return self.convert_item_to_object(itemp) * */ - __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*else*/ { + __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == ((char *)NULL))) __PYX_ERR(1, 407, __pyx_L1_error) __pyx_v_itemp = __pyx_t_6; - /* "View.MemoryView":367 + /* "View.MemoryView":408 * else: * itemp = self.get_item_pointer(indices) * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< @@ -7982,14 +9640,14 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __ * def __setitem__(memoryview self, object index, object value): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 367; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 408, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; } - /* "View.MemoryView":356 + /* "View.MemoryView":397 * * * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< @@ -8012,7 +9670,7 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __ return __pyx_r; } -/* "View.MemoryView":369 +/* "View.MemoryView":410 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< @@ -8026,14 +9684,14 @@ static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_ int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { PyObject *__pyx_v_have_slices = NULL; PyObject *__pyx_v_obj = NULL; int __pyx_r; @@ -8042,24 +9700,21 @@ static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_me PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setitem__", 0); __Pyx_INCREF(__pyx_v_index); - /* "View.MemoryView":370 + /* "View.MemoryView":411 * * def __setitem__(memoryview self, object index, object value): * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< * * if have_slices: */ - __pyx_t_1 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 411, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (likely(__pyx_t_1 != Py_None)) { PyObject* sequence = __pyx_t_1; - #if CYTHON_COMPILING_IN_CPYTHON + #if !CYTHON_COMPILING_IN_PYPY Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); @@ -8067,111 +9722,127 @@ static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_me if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 411, __pyx_L1_error) } - #if CYTHON_COMPILING_IN_CPYTHON + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_2); __Pyx_INCREF(__pyx_t_3); #else - __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 411, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 411, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); #endif __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else { - __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 411, __pyx_L1_error) } __pyx_v_have_slices = __pyx_t_2; __pyx_t_2 = 0; __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_3); __pyx_t_3 = 0; - /* "View.MemoryView":372 + /* "View.MemoryView":413 * have_slices, index = _unellipsify(index, self.view.ndim) * * if have_slices: # <<<<<<<<<<<<<< * obj = self.is_slice(value) * if obj: */ - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(1, 413, __pyx_L1_error) if (__pyx_t_4) { - /* "View.MemoryView":373 + /* "View.MemoryView":414 * * if have_slices: * obj = self.is_slice(value) # <<<<<<<<<<<<<< * if obj: * self.setitem_slice_assignment(self[index], obj) */ - __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 414, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_obj = __pyx_t_1; __pyx_t_1 = 0; - /* "View.MemoryView":374 + /* "View.MemoryView":415 * if have_slices: * obj = self.is_slice(value) * if obj: # <<<<<<<<<<<<<< * self.setitem_slice_assignment(self[index], obj) * else: */ - __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_4 < 0)) __PYX_ERR(1, 415, __pyx_L1_error) if (__pyx_t_4) { - /* "View.MemoryView":375 + /* "View.MemoryView":416 * obj = self.is_slice(value) * if obj: * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< * else: * self.setitem_slice_assign_scalar(self[index], value) */ - __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 416, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 416, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "View.MemoryView":415 + * if have_slices: + * obj = self.is_slice(value) + * if obj: # <<<<<<<<<<<<<< + * self.setitem_slice_assignment(self[index], obj) + * else: + */ goto __pyx_L4; } - /*else*/ { - /* "View.MemoryView":377 + /* "View.MemoryView":418 * self.setitem_slice_assignment(self[index], obj) * else: * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< * else: * self.setitem_indexed(index, value) */ - __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + /*else*/ { + __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 418, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(1, 418, __pyx_L1_error) + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 418, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } __pyx_L4:; + + /* "View.MemoryView":413 + * have_slices, index = _unellipsify(index, self.view.ndim) + * + * if have_slices: # <<<<<<<<<<<<<< + * obj = self.is_slice(value) + * if obj: + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":379 + /* "View.MemoryView":420 * self.setitem_slice_assign_scalar(self[index], value) * else: * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< * * cdef is_slice(self, obj): */ - __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*else*/ { + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 420, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } __pyx_L3:; - /* "View.MemoryView":369 + /* "View.MemoryView":410 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< @@ -8196,7 +9867,7 @@ static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_me return __pyx_r; } -/* "View.MemoryView":381 +/* "View.MemoryView":422 * self.setitem_indexed(index, value) * * cdef is_slice(self, obj): # <<<<<<<<<<<<<< @@ -8216,24 +9887,21 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_t_9; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("is_slice", 0); __Pyx_INCREF(__pyx_v_obj); - /* "View.MemoryView":382 + /* "View.MemoryView":423 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, */ - __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, ((PyObject *)__pyx_memoryview_type)); + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, __pyx_memoryview_type); __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":383 + /* "View.MemoryView":424 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< @@ -8241,81 +9909,91 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ * self.dtype_is_object) */ { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); __Pyx_XGOTREF(__pyx_t_3); __Pyx_XGOTREF(__pyx_t_4); __Pyx_XGOTREF(__pyx_t_5); /*try:*/ { - /* "View.MemoryView":384 + /* "View.MemoryView":425 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ - __pyx_t_6 = __Pyx_PyInt_From_int((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __pyx_t_6 = __Pyx_PyInt_From_int((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 425, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_6); - /* "View.MemoryView":385 + /* "View.MemoryView":426 * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) # <<<<<<<<<<<<<< * except TypeError: * return None */ - __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 426, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_7); - /* "View.MemoryView":384 + /* "View.MemoryView":425 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ - __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 425, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_INCREF(__pyx_v_obj); - PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); __Pyx_GIVEREF(__pyx_v_obj); - PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); __Pyx_GIVEREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); __pyx_t_6 = 0; __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} + __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 425, __pyx_L4_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7); __pyx_t_7 = 0; + + /* "View.MemoryView":424 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ } __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; - goto __pyx_L11_try_end; + goto __pyx_L9_try_end; __pyx_L4_error:; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; - /* "View.MemoryView":386 + /* "View.MemoryView":427 * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) * except TypeError: # <<<<<<<<<<<<<< * return None * */ - __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); + __pyx_t_9 = __Pyx_PyErr_ExceptionMatches(__pyx_builtin_TypeError); if (__pyx_t_9) { __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} + if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) __PYX_ERR(1, 427, __pyx_L6_except_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GOTREF(__pyx_t_8); __Pyx_GOTREF(__pyx_t_6); - /* "View.MemoryView":387 + /* "View.MemoryView":428 * self.dtype_is_object) * except TypeError: * return None # <<<<<<<<<<<<<< @@ -8332,6 +10010,14 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ } goto __pyx_L6_except_error; __pyx_L6_except_error:; + + /* "View.MemoryView":424 + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): + * try: # <<<<<<<<<<<<<< + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + * self.dtype_is_object) + */ __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_XGIVEREF(__pyx_t_5); @@ -8343,13 +10029,19 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ __Pyx_XGIVEREF(__pyx_t_5); __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); goto __pyx_L0; - __pyx_L11_try_end:; + __pyx_L9_try_end:; } - goto __pyx_L3; + + /* "View.MemoryView":423 + * + * cdef is_slice(self, obj): + * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< + * try: + * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, + */ } - __pyx_L3:; - /* "View.MemoryView":389 + /* "View.MemoryView":430 * return None * * return obj # <<<<<<<<<<<<<< @@ -8361,7 +10053,7 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ __pyx_r = __pyx_v_obj; goto __pyx_L0; - /* "View.MemoryView":381 + /* "View.MemoryView":422 * self.setitem_indexed(index, value) * * cdef is_slice(self, obj): # <<<<<<<<<<<<<< @@ -8383,7 +10075,7 @@ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_ return __pyx_r; } -/* "View.MemoryView":391 +/* "View.MemoryView":432 * return obj * * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< @@ -8400,55 +10092,52 @@ static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryvi int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); - /* "View.MemoryView":395 + /* "View.MemoryView":436 * cdef __Pyx_memviewslice src_slice * * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< * get_slice_from_memview(dst, &dst_slice)[0], * src.ndim, dst.ndim, self.dtype_is_object) */ - if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) __PYX_ERR(1, 436, __pyx_L1_error) - /* "View.MemoryView":396 + /* "View.MemoryView":437 * * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< * src.ndim, dst.ndim, self.dtype_is_object) * */ - if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) __PYX_ERR(1, 437, __pyx_L1_error) - /* "View.MemoryView":397 + /* "View.MemoryView":438 * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], * get_slice_from_memview(dst, &dst_slice)[0], * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 438, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 438, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 438, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 438, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "View.MemoryView":395 + /* "View.MemoryView":436 * cdef __Pyx_memviewslice src_slice * * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< * get_slice_from_memview(dst, &dst_slice)[0], * src.ndim, dst.ndim, self.dtype_is_object) */ - __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 436, __pyx_L1_error) - /* "View.MemoryView":391 + /* "View.MemoryView":432 * return obj * * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< @@ -8469,7 +10158,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryvi return __pyx_r; } -/* "View.MemoryView":399 +/* "View.MemoryView":440 * src.ndim, dst.ndim, self.dtype_is_object) * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< @@ -8478,7 +10167,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryvi */ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { - int __pyx_v_array[128]; + int __pyx_v_array[0x80]; void *__pyx_v_tmp; void *__pyx_v_item; __Pyx_memviewslice *__pyx_v_dst_slice; @@ -8496,12 +10185,9 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); - /* "View.MemoryView":401 + /* "View.MemoryView":442 * cdef setitem_slice_assign_scalar(self, memoryview dst, value): * cdef int array[128] * cdef void *tmp = NULL # <<<<<<<<<<<<<< @@ -8510,7 +10196,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor */ __pyx_v_tmp = NULL; - /* "View.MemoryView":406 + /* "View.MemoryView":447 * cdef __Pyx_memviewslice *dst_slice * cdef __Pyx_memviewslice tmp_slice * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< @@ -8519,7 +10205,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor */ __pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); - /* "View.MemoryView":408 + /* "View.MemoryView":449 * dst_slice = get_slice_from_memview(dst, &tmp_slice) * * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< @@ -8529,7 +10215,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor __pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); if (__pyx_t_1) { - /* "View.MemoryView":409 + /* "View.MemoryView":450 * * if self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) # <<<<<<<<<<<<<< @@ -8538,7 +10224,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor */ __pyx_v_tmp = PyMem_Malloc(__pyx_v_self->view.itemsize); - /* "View.MemoryView":410 + /* "View.MemoryView":451 * if self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: # <<<<<<<<<<<<<< @@ -8548,17 +10234,25 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":411 + /* "View.MemoryView":452 * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: * raise MemoryError # <<<<<<<<<<<<<< * item = tmp * else: */ - PyErr_NoMemory(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyErr_NoMemory(); __PYX_ERR(1, 452, __pyx_L1_error) + + /* "View.MemoryView":451 + * if self.view.itemsize > sizeof(array): + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: # <<<<<<<<<<<<<< + * raise MemoryError + * item = tmp + */ } - /* "View.MemoryView":412 + /* "View.MemoryView":453 * if tmp == NULL: * raise MemoryError * item = tmp # <<<<<<<<<<<<<< @@ -8566,22 +10260,30 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor * item = array */ __pyx_v_item = __pyx_v_tmp; + + /* "View.MemoryView":449 + * dst_slice = get_slice_from_memview(dst, &tmp_slice) + * + * if self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< + * tmp = PyMem_Malloc(self.view.itemsize) + * if tmp == NULL: + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":414 + /* "View.MemoryView":455 * item = tmp * else: * item = array # <<<<<<<<<<<<<< * * try: */ + /*else*/ { __pyx_v_item = ((void *)__pyx_v_array); } __pyx_L3:; - /* "View.MemoryView":416 + /* "View.MemoryView":457 * item = array * * try: # <<<<<<<<<<<<<< @@ -8590,7 +10292,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor */ /*try:*/ { - /* "View.MemoryView":417 + /* "View.MemoryView":458 * * try: * if self.dtype_is_object: # <<<<<<<<<<<<<< @@ -8600,7 +10302,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_1) { - /* "View.MemoryView":418 + /* "View.MemoryView":459 * try: * if self.dtype_is_object: * ( item)[0] = value # <<<<<<<<<<<<<< @@ -8608,24 +10310,32 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor * self.assign_item_from_object( item, value) */ (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); + + /* "View.MemoryView":458 + * + * try: + * if self.dtype_is_object: # <<<<<<<<<<<<<< + * ( item)[0] = value + * else: + */ goto __pyx_L8; } - /*else*/ { - /* "View.MemoryView":420 + /* "View.MemoryView":461 * ( item)[0] = value * else: * self.assign_item_from_object( item, value) # <<<<<<<<<<<<<< * * */ - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + /*else*/ { + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 461, __pyx_L6_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_L8:; - /* "View.MemoryView":424 + /* "View.MemoryView":465 * * * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< @@ -8635,21 +10345,27 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor __pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":425 + /* "View.MemoryView":466 * * if self.view.suboffsets != NULL: * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, * item, self.dtype_is_object) */ - __pyx_t_2 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L6_error;} + __pyx_t_2 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 466, __pyx_L6_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - goto __pyx_L9; + + /* "View.MemoryView":465 + * + * + * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< + * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) + * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, + */ } - __pyx_L9:; - /* "View.MemoryView":426 + /* "View.MemoryView":467 * if self.view.suboffsets != NULL: * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<< @@ -8659,7 +10375,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); } - /* "View.MemoryView":429 + /* "View.MemoryView":470 * item, self.dtype_is_object) * finally: * PyMem_Free(tmp) # <<<<<<<<<<<<<< @@ -8671,8 +10387,10 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor PyMem_Free(__pyx_v_tmp); goto __pyx_L7; } + __pyx_L6_error:; /*exception exit:*/{ - __pyx_L6_error:; + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); @@ -8704,7 +10422,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor __pyx_L7:; } - /* "View.MemoryView":399 + /* "View.MemoryView":440 * src.ndim, dst.ndim, self.dtype_is_object) * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< @@ -8725,7 +10443,7 @@ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memor return __pyx_r; } -/* "View.MemoryView":431 +/* "View.MemoryView":472 * PyMem_Free(tmp) * * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< @@ -8739,33 +10457,30 @@ static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *_ __Pyx_RefNannyDeclarations char *__pyx_t_1; PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_indexed", 0); - /* "View.MemoryView":432 + /* "View.MemoryView":473 * * cdef setitem_indexed(self, index, value): * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< * self.assign_item_from_object(itemp, value) * */ - __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == ((char *)NULL))) __PYX_ERR(1, 473, __pyx_L1_error) __pyx_v_itemp = __pyx_t_1; - /* "View.MemoryView":433 + /* "View.MemoryView":474 * cdef setitem_indexed(self, index, value): * cdef char *itemp = self.get_item_pointer(index) * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< * * cdef convert_item_to_object(self, char *itemp): */ - __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 474, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "View.MemoryView":431 + /* "View.MemoryView":472 * PyMem_Free(tmp) * * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< @@ -8786,7 +10501,7 @@ static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *_ return __pyx_r; } -/* "View.MemoryView":435 +/* "View.MemoryView":476 * self.assign_item_from_object(itemp, value) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< @@ -8807,41 +10522,37 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; - Py_ssize_t __pyx_t_8; + int __pyx_t_8; PyObject *__pyx_t_9 = NULL; size_t __pyx_t_10; int __pyx_t_11; - int __pyx_t_12; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("convert_item_to_object", 0); - /* "View.MemoryView":438 + /* "View.MemoryView":479 * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" * import struct # <<<<<<<<<<<<<< * cdef bytes bytesitem * */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 479, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; - /* "View.MemoryView":441 + /* "View.MemoryView":482 * cdef bytes bytesitem * * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< * try: * result = struct.unpack(self.view.format, bytesitem) */ - __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 482, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; - /* "View.MemoryView":442 + /* "View.MemoryView":483 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< @@ -8849,26 +10560,28 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview * except struct.error: */ { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); __Pyx_XGOTREF(__pyx_t_4); /*try:*/ { - /* "View.MemoryView":443 + /* "View.MemoryView":484 * bytesitem = itemp[:self.view.itemsize] * try: * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< * except struct.error: * raise ValueError("Unable to convert item to object") */ - __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 484, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_5); - __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} + __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 484, __pyx_L3_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = NULL; __pyx_t_8 = 0; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_5))) { + if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_5))) { __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_5); if (likely(__pyx_t_7)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); @@ -8878,38 +10591,66 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview __pyx_t_8 = 1; } } - __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __Pyx_GOTREF(__pyx_t_9); - if (__pyx_t_7) { - PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); __pyx_t_7 = NULL; + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(__pyx_t_5)) { + PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; + __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 484, __pyx_L3_error) + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } else + #endif + #if CYTHON_FAST_PYCCALL + if (__Pyx_PyFastCFunction_Check(__pyx_t_5)) { + PyObject *__pyx_temp[3] = {__pyx_t_7, __pyx_t_6, __pyx_v_bytesitem}; + __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_5, __pyx_temp+1-__pyx_t_8, 2+__pyx_t_8); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 484, __pyx_L3_error) + __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } else + #endif + { + __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 484, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_9); + if (__pyx_t_7) { + __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __pyx_t_7 = NULL; + } + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_6); + __Pyx_INCREF(__pyx_v_bytesitem); + __Pyx_GIVEREF(__pyx_v_bytesitem); + PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_v_bytesitem); + __pyx_t_6 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 484, __pyx_L3_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } - PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_6); - __Pyx_GIVEREF(__pyx_t_6); - __Pyx_INCREF(__pyx_v_bytesitem); - PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_v_bytesitem); - __Pyx_GIVEREF(__pyx_v_bytesitem); - __pyx_t_6 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_result = __pyx_t_1; __pyx_t_1 = 0; + + /* "View.MemoryView":483 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ } - /*else:*/ { - /* "View.MemoryView":447 + /* "View.MemoryView":488 * raise ValueError("Unable to convert item to object") * else: * if len(self.view.format) == 1: # <<<<<<<<<<<<<< * return result[0] * return result */ + /*else:*/ { __pyx_t_10 = strlen(__pyx_v_self->view.format); __pyx_t_11 = ((__pyx_t_10 == 1) != 0); if (__pyx_t_11) { - /* "View.MemoryView":448 + /* "View.MemoryView":489 * else: * if len(self.view.format) == 1: * return result[0] # <<<<<<<<<<<<<< @@ -8917,14 +10658,22 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;}; + __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 489, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L6_except_return; + + /* "View.MemoryView":488 + * raise ValueError("Unable to convert item to object") + * else: + * if len(self.view.format) == 1: # <<<<<<<<<<<<<< + * return result[0] + * return result + */ } - /* "View.MemoryView":449 + /* "View.MemoryView":490 * if len(self.view.format) == 1: * return result[0] * return result # <<<<<<<<<<<<<< @@ -8943,39 +10692,47 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; - /* "View.MemoryView":444 + /* "View.MemoryView":485 * try: * result = struct.unpack(self.view.format, bytesitem) * except struct.error: # <<<<<<<<<<<<<< * raise ValueError("Unable to convert item to object") * else: */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 485, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_12 = PyErr_ExceptionMatches(__pyx_t_1); + __pyx_t_8 = __Pyx_PyErr_ExceptionMatches(__pyx_t_1); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - if (__pyx_t_12) { + if (__pyx_t_8) { __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); - if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9) < 0) __PYX_ERR(1, 485, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_9); - /* "View.MemoryView":445 + /* "View.MemoryView":486 * result = struct.unpack(self.view.format, bytesitem) * except struct.error: * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< * else: * if len(self.view.format) == 1: */ - __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__21, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 486, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_Raise(__pyx_t_6, 0, 0, 0); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} + __PYX_ERR(1, 486, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; + + /* "View.MemoryView":483 + * + * bytesitem = itemp[:self.view.itemsize] + * try: # <<<<<<<<<<<<<< + * result = struct.unpack(self.view.format, bytesitem) + * except struct.error: + */ __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); @@ -8989,7 +10746,7 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview goto __pyx_L0; } - /* "View.MemoryView":435 + /* "View.MemoryView":476 * self.assign_item_from_object(itemp, value) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< @@ -9015,7 +10772,7 @@ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview return __pyx_r; } -/* "View.MemoryView":451 +/* "View.MemoryView":492 * return result * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< @@ -9036,31 +10793,29 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; - Py_ssize_t __pyx_t_7; + int __pyx_t_7; PyObject *__pyx_t_8 = NULL; - PyObject *__pyx_t_9 = NULL; - char *__pyx_t_10; + Py_ssize_t __pyx_t_9; + PyObject *__pyx_t_10 = NULL; char *__pyx_t_11; char *__pyx_t_12; char *__pyx_t_13; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; + char *__pyx_t_14; __Pyx_RefNannySetupContext("assign_item_from_object", 0); - /* "View.MemoryView":454 + /* "View.MemoryView":495 * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" * import struct # <<<<<<<<<<<<<< * cdef char c * cdef bytes bytesvalue */ - __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 495, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; - /* "View.MemoryView":459 + /* "View.MemoryView":500 * cdef Py_ssize_t i * * if isinstance(value, tuple): # <<<<<<<<<<<<<< @@ -9071,53 +10826,61 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie __pyx_t_3 = (__pyx_t_2 != 0); if (__pyx_t_3) { - /* "View.MemoryView":460 + /* "View.MemoryView":501 * * if isinstance(value, tuple): * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< * else: * bytesvalue = struct.pack(self.view.format, value) */ - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 501, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 501, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 501, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 501, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 501, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 501, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 501, __pyx_L1_error) __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; + + /* "View.MemoryView":500 + * cdef Py_ssize_t i + * + * if isinstance(value, tuple): # <<<<<<<<<<<<<< + * bytesvalue = struct.pack(self.view.format, *value) + * else: + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":462 + /* "View.MemoryView":503 * bytesvalue = struct.pack(self.view.format, *value) * else: * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< * * for i, c in enumerate(bytesvalue): */ - __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*else*/ { + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 503, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); - __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 503, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_5 = NULL; __pyx_t_7 = 0; - if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_6))) { + if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_6))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_6); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); @@ -9127,66 +10890,86 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie __pyx_t_7 = 1; } } - __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_8); - if (__pyx_t_5) { - PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(__pyx_t_6)) { + PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; + __pyx_t_4 = __Pyx_PyFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 503, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else + #endif + #if CYTHON_FAST_PYCCALL + if (__Pyx_PyFastCFunction_Check(__pyx_t_6)) { + PyObject *__pyx_temp[3] = {__pyx_t_5, __pyx_t_1, __pyx_v_value}; + __pyx_t_4 = __Pyx_PyCFunction_FastCall(__pyx_t_6, __pyx_temp+1-__pyx_t_7, 2+__pyx_t_7); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 503, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + } else + #endif + { + __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 503, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_8); + if (__pyx_t_5) { + __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __pyx_t_5 = NULL; + } + __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); + __Pyx_INCREF(__pyx_v_value); + __Pyx_GIVEREF(__pyx_v_value); + PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_value); + __pyx_t_1 = 0; + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 503, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; } - PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); - __Pyx_GIVEREF(__pyx_t_1); - __Pyx_INCREF(__pyx_v_value); - PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_value); - __Pyx_GIVEREF(__pyx_v_value); - __pyx_t_1 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; - if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) __PYX_ERR(1, 503, __pyx_L1_error) __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; } __pyx_L3:; - /* "View.MemoryView":464 + /* "View.MemoryView":505 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< * itemp[i] = c * */ - __pyx_t_7 = 0; + __pyx_t_9 = 0; if (unlikely(__pyx_v_bytesvalue == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 505, __pyx_L1_error) } __Pyx_INCREF(__pyx_v_bytesvalue); - __pyx_t_9 = __pyx_v_bytesvalue; - __pyx_t_11 = PyBytes_AS_STRING(__pyx_t_9); - __pyx_t_12 = (__pyx_t_11 + PyBytes_GET_SIZE(__pyx_t_9)); - for (__pyx_t_13 = __pyx_t_11; __pyx_t_13 < __pyx_t_12; __pyx_t_13++) { - __pyx_t_10 = __pyx_t_13; - __pyx_v_c = (__pyx_t_10[0]); + __pyx_t_10 = __pyx_v_bytesvalue; + __pyx_t_12 = PyBytes_AS_STRING(__pyx_t_10); + __pyx_t_13 = (__pyx_t_12 + PyBytes_GET_SIZE(__pyx_t_10)); + for (__pyx_t_14 = __pyx_t_12; __pyx_t_14 < __pyx_t_13; __pyx_t_14++) { + __pyx_t_11 = __pyx_t_14; + __pyx_v_c = (__pyx_t_11[0]); - /* "View.MemoryView":465 + /* "View.MemoryView":506 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< * * @cname('getbuffer') */ - __pyx_v_i = __pyx_t_7; + __pyx_v_i = __pyx_t_9; - /* "View.MemoryView":464 + /* "View.MemoryView":505 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< * itemp[i] = c * */ - __pyx_t_7 = (__pyx_t_7 + 1); + __pyx_t_9 = (__pyx_t_9 + 1); - /* "View.MemoryView":465 + /* "View.MemoryView":506 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< @@ -9195,9 +10978,9 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie */ (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; } - __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; - /* "View.MemoryView":451 + /* "View.MemoryView":492 * return result * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< @@ -9214,7 +10997,7 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_8); - __Pyx_XDECREF(__pyx_t_9); + __Pyx_XDECREF(__pyx_t_10); __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; @@ -9225,7 +11008,7 @@ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryvie return __pyx_r; } -/* "View.MemoryView":468 +/* "View.MemoryView":509 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< @@ -9239,14 +11022,14 @@ static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_b int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { +static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; @@ -9261,7 +11044,7 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str __Pyx_GIVEREF(__pyx_v_info->obj); } - /* "View.MemoryView":469 + /* "View.MemoryView":510 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< @@ -9271,7 +11054,7 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); if (__pyx_t_1) { - /* "View.MemoryView":470 + /* "View.MemoryView":511 * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_STRIDES: * info.shape = self.view.shape # <<<<<<<<<<<<<< @@ -9280,22 +11063,30 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str */ __pyx_t_2 = __pyx_v_self->view.shape; __pyx_v_info->shape = __pyx_t_2; + + /* "View.MemoryView":510 + * @cname('getbuffer') + * def __getbuffer__(self, Py_buffer *info, int flags): + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.shape = self.view.shape + * else: + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":472 + /* "View.MemoryView":513 * info.shape = self.view.shape * else: * info.shape = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_STRIDES: */ + /*else*/ { __pyx_v_info->shape = NULL; } __pyx_L3:; - /* "View.MemoryView":474 + /* "View.MemoryView":515 * info.shape = NULL * * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< @@ -9305,7 +11096,7 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); if (__pyx_t_1) { - /* "View.MemoryView":475 + /* "View.MemoryView":516 * * if flags & PyBUF_STRIDES: * info.strides = self.view.strides # <<<<<<<<<<<<<< @@ -9314,22 +11105,30 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str */ __pyx_t_2 = __pyx_v_self->view.strides; __pyx_v_info->strides = __pyx_t_2; + + /* "View.MemoryView":515 + * info.shape = NULL + * + * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< + * info.strides = self.view.strides + * else: + */ goto __pyx_L4; } - /*else*/ { - /* "View.MemoryView":477 + /* "View.MemoryView":518 * info.strides = self.view.strides * else: * info.strides = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_INDIRECT: */ + /*else*/ { __pyx_v_info->strides = NULL; } __pyx_L4:; - /* "View.MemoryView":479 + /* "View.MemoryView":520 * info.strides = NULL * * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< @@ -9339,7 +11138,7 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); if (__pyx_t_1) { - /* "View.MemoryView":480 + /* "View.MemoryView":521 * * if flags & PyBUF_INDIRECT: * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< @@ -9348,22 +11147,30 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str */ __pyx_t_2 = __pyx_v_self->view.suboffsets; __pyx_v_info->suboffsets = __pyx_t_2; + + /* "View.MemoryView":520 + * info.strides = NULL + * + * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< + * info.suboffsets = self.view.suboffsets + * else: + */ goto __pyx_L5; } - /*else*/ { - /* "View.MemoryView":482 + /* "View.MemoryView":523 * info.suboffsets = self.view.suboffsets * else: * info.suboffsets = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ + /*else*/ { __pyx_v_info->suboffsets = NULL; } __pyx_L5:; - /* "View.MemoryView":484 + /* "View.MemoryView":525 * info.suboffsets = NULL * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< @@ -9373,7 +11180,7 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { - /* "View.MemoryView":485 + /* "View.MemoryView":526 * * if flags & PyBUF_FORMAT: * info.format = self.view.format # <<<<<<<<<<<<<< @@ -9382,22 +11189,30 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str */ __pyx_t_3 = __pyx_v_self->view.format; __pyx_v_info->format = __pyx_t_3; + + /* "View.MemoryView":525 + * info.suboffsets = NULL + * + * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< + * info.format = self.view.format + * else: + */ goto __pyx_L6; } - /*else*/ { - /* "View.MemoryView":487 + /* "View.MemoryView":528 * info.format = self.view.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.buf = self.view.buf */ + /*else*/ { __pyx_v_info->format = NULL; } __pyx_L6:; - /* "View.MemoryView":489 + /* "View.MemoryView":530 * info.format = NULL * * info.buf = self.view.buf # <<<<<<<<<<<<<< @@ -9407,7 +11222,7 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str __pyx_t_4 = __pyx_v_self->view.buf; __pyx_v_info->buf = __pyx_t_4; - /* "View.MemoryView":490 + /* "View.MemoryView":531 * * info.buf = self.view.buf * info.ndim = self.view.ndim # <<<<<<<<<<<<<< @@ -9417,7 +11232,7 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str __pyx_t_5 = __pyx_v_self->view.ndim; __pyx_v_info->ndim = __pyx_t_5; - /* "View.MemoryView":491 + /* "View.MemoryView":532 * info.buf = self.view.buf * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< @@ -9427,7 +11242,7 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str __pyx_t_6 = __pyx_v_self->view.itemsize; __pyx_v_info->itemsize = __pyx_t_6; - /* "View.MemoryView":492 + /* "View.MemoryView":533 * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize * info.len = self.view.len # <<<<<<<<<<<<<< @@ -9437,7 +11252,7 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str __pyx_t_6 = __pyx_v_self->view.len; __pyx_v_info->len = __pyx_t_6; - /* "View.MemoryView":493 + /* "View.MemoryView":534 * info.itemsize = self.view.itemsize * info.len = self.view.len * info.readonly = 0 # <<<<<<<<<<<<<< @@ -9446,7 +11261,7 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str */ __pyx_v_info->readonly = 0; - /* "View.MemoryView":494 + /* "View.MemoryView":535 * info.len = self.view.len * info.readonly = 0 * info.obj = self # <<<<<<<<<<<<<< @@ -9459,7 +11274,7 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); - /* "View.MemoryView":468 + /* "View.MemoryView":509 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< @@ -9477,78 +11292,75 @@ static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(str return __pyx_r; } -/* "View.MemoryView":501 - * property T: - * @cname('__pyx_memoryview_transpose') - * def __get__(self): # <<<<<<<<<<<<<< - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) +/* "View.MemoryView":541 + * + * @property + * def T(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) */ /* Python wrapper */ -static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":502 - * @cname('__pyx_memoryview_transpose') - * def __get__(self): - * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< - * transpose_memslice(&result.from_slice) - * return result + /* "View.MemoryView":542 + * @property + * def T(self): + * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< + * transpose_memslice(&result.from_slice) + * return result */ - __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 542, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) __PYX_ERR(1, 542, __pyx_L1_error) __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); __pyx_t_1 = 0; - /* "View.MemoryView":503 - * def __get__(self): - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< - * return result + /* "View.MemoryView":543 + * def T(self): + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< + * return result * */ - __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(1, 543, __pyx_L1_error) - /* "View.MemoryView":504 - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) - * return result # <<<<<<<<<<<<<< + /* "View.MemoryView":544 + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) + * return result # <<<<<<<<<<<<<< * - * property base: + * @property */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; - /* "View.MemoryView":501 - * property T: - * @cname('__pyx_memoryview_transpose') - * def __get__(self): # <<<<<<<<<<<<<< - * cdef _memoryviewslice result = memoryview_copy(self) - * transpose_memslice(&result.from_slice) + /* "View.MemoryView":541 + * + * @property + * def T(self): # <<<<<<<<<<<<<< + * cdef _memoryviewslice result = memoryview_copy(self) + * transpose_memslice(&result.from_slice) */ /* function exit code */ @@ -9563,49 +11375,49 @@ static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(s return __pyx_r; } -/* "View.MemoryView":508 - * property base: - * @cname('__pyx_memoryview__get__base') - * def __get__(self): # <<<<<<<<<<<<<< - * return self.obj +/* "View.MemoryView":547 + * + * @property + * def base(self): # <<<<<<<<<<<<<< + * return self.obj * */ /* Python wrapper */ -static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":509 - * @cname('__pyx_memoryview__get__base') - * def __get__(self): - * return self.obj # <<<<<<<<<<<<<< + /* "View.MemoryView":548 + * @property + * def base(self): + * return self.obj # <<<<<<<<<<<<<< * - * property shape: + * @property */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->obj); __pyx_r = __pyx_v_self->obj; goto __pyx_L0; - /* "View.MemoryView":508 - * property base: - * @cname('__pyx_memoryview__get__base') - * def __get__(self): # <<<<<<<<<<<<<< - * return self.obj + /* "View.MemoryView":547 + * + * @property + * def base(self): # <<<<<<<<<<<<<< + * return self.obj * */ @@ -9616,77 +11428,76 @@ static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get return __pyx_r; } -/* "View.MemoryView":513 - * property shape: - * @cname('__pyx_memoryview_get_shape') - * def __get__(self): # <<<<<<<<<<<<<< - * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) +/* "View.MemoryView":551 + * + * @property + * def shape(self): # <<<<<<<<<<<<<< + * return tuple([length for length in self.view.shape[:self.view.ndim]]) * */ /* Python wrapper */ -static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - int __pyx_v_i; +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_v_length; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; + Py_ssize_t *__pyx_t_2; + Py_ssize_t *__pyx_t_3; + Py_ssize_t *__pyx_t_4; + PyObject *__pyx_t_5 = NULL; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":514 - * @cname('__pyx_memoryview_get_shape') - * def __get__(self): - * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + /* "View.MemoryView":552 + * @property + * def shape(self): + * return tuple([length for length in self.view.shape[:self.view.ndim]]) # <<<<<<<<<<<<<< * - * property strides: + * @property */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 552, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __pyx_v_self->view.ndim; - for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { - __pyx_v_i = __pyx_t_3; - __pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->view.shape[__pyx_v_i])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_4))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __pyx_t_3 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); + for (__pyx_t_4 = __pyx_v_self->view.shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { + __pyx_t_2 = __pyx_t_4; + __pyx_v_length = (__pyx_t_2[0]); + __pyx_t_5 = PyInt_FromSsize_t(__pyx_v_length); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 552, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) __PYX_ERR(1, 552, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } - __pyx_t_4 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); + __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 552, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_r = __pyx_t_4; - __pyx_t_4 = 0; + __pyx_r = __pyx_t_5; + __pyx_t_5 = 0; goto __pyx_L0; - /* "View.MemoryView":513 - * property shape: - * @cname('__pyx_memoryview_get_shape') - * def __get__(self): # <<<<<<<<<<<<<< - * return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) + /* "View.MemoryView":551 + * + * @property + * def shape(self): # <<<<<<<<<<<<<< + * return tuple([length for length in self.view.shape[:self.view.ndim]]) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); - __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -9695,102 +11506,109 @@ static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get return __pyx_r; } -/* "View.MemoryView":518 - * property strides: - * @cname('__pyx_memoryview_get_strides') - * def __get__(self): # <<<<<<<<<<<<<< - * if self.view.strides == NULL: +/* "View.MemoryView":555 + * + * @property + * def strides(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: * */ /* Python wrapper */ -static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - int __pyx_v_i; +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_v_stride; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; + Py_ssize_t *__pyx_t_3; + Py_ssize_t *__pyx_t_4; + Py_ssize_t *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":519 - * @cname('__pyx_memoryview_get_strides') - * def __get__(self): - * if self.view.strides == NULL: # <<<<<<<<<<<<<< + /* "View.MemoryView":556 + * @property + * def strides(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< * - * raise ValueError("Buffer view does not expose strides") + * raise ValueError("Buffer view does not expose strides") */ __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":521 - * if self.view.strides == NULL: + /* "View.MemoryView":558 + * if self.view.strides == NULL: * - * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< * - * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) */ - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__17, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__22, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 558, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 558, __pyx_L1_error) + + /* "View.MemoryView":556 + * @property + * def strides(self): + * if self.view.strides == NULL: # <<<<<<<<<<<<<< + * + * raise ValueError("Buffer view does not expose strides") + */ } - /* "View.MemoryView":523 - * raise ValueError("Buffer view does not expose strides") + /* "View.MemoryView":560 + * raise ValueError("Buffer view does not expose strides") * - * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) # <<<<<<<<<<<<<< * - * property suboffsets: + * @property */ __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 560, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_v_self->view.ndim; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.strides[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_4 = (__pyx_v_self->view.strides + __pyx_v_self->view.ndim); + for (__pyx_t_5 = __pyx_v_self->view.strides; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { + __pyx_t_3 = __pyx_t_5; + __pyx_v_stride = (__pyx_t_3[0]); + __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_stride); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 560, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) __PYX_ERR(1, 560, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } - __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); + __pyx_t_6 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 560, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; + __pyx_r = __pyx_t_6; + __pyx_t_6 = 0; goto __pyx_L0; - /* "View.MemoryView":518 - * property strides: - * @cname('__pyx_memoryview_get_strides') - * def __get__(self): # <<<<<<<<<<<<<< - * if self.view.strides == NULL: + /* "View.MemoryView":555 + * + * @property + * def strides(self): # <<<<<<<<<<<<<< + * if self.view.strides == NULL: * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -9799,110 +11617,113 @@ static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides__ return __pyx_r; } -/* "View.MemoryView":527 - * property suboffsets: - * @cname('__pyx_memoryview_get_suboffsets') - * def __get__(self): # <<<<<<<<<<<<<< - * if self.view.suboffsets == NULL: - * return [-1] * self.view.ndim +/* "View.MemoryView":563 + * + * @property + * def suboffsets(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return (-1,) * self.view.ndim */ /* Python wrapper */ -static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { - int __pyx_v_i; +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { + Py_ssize_t __pyx_v_suboffset; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; - int __pyx_t_3; - int __pyx_t_4; - PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; + PyObject *__pyx_t_3 = NULL; + Py_ssize_t *__pyx_t_4; + Py_ssize_t *__pyx_t_5; + Py_ssize_t *__pyx_t_6; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":528 - * @cname('__pyx_memoryview_get_suboffsets') - * def __get__(self): - * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< - * return [-1] * self.view.ndim + /* "View.MemoryView":564 + * @property + * def suboffsets(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return (-1,) * self.view.ndim * */ __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":529 - * def __get__(self): - * if self.view.suboffsets == NULL: - * return [-1] * self.view.ndim # <<<<<<<<<<<<<< + /* "View.MemoryView":565 + * def suboffsets(self): + * if self.view.suboffsets == NULL: + * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< * - * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) + * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) */ __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyList_New(1 * ((__pyx_v_self->view.ndim<0) ? 0:__pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 565, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - { Py_ssize_t __pyx_temp; - for (__pyx_temp=0; __pyx_temp < __pyx_v_self->view.ndim; __pyx_temp++) { - __Pyx_INCREF(__pyx_int_neg_1); - PyList_SET_ITEM(__pyx_t_2, __pyx_temp, __pyx_int_neg_1); - __Pyx_GIVEREF(__pyx_int_neg_1); - } - } - __pyx_r = __pyx_t_2; - __pyx_t_2 = 0; + __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__23, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 565, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_r = __pyx_t_3; + __pyx_t_3 = 0; goto __pyx_L0; + + /* "View.MemoryView":564 + * @property + * def suboffsets(self): + * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< + * return (-1,) * self.view.ndim + * + */ } - /* "View.MemoryView":531 - * return [-1] * self.view.ndim + /* "View.MemoryView":567 + * return (-1,) * self.view.ndim * - * return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<< + * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) # <<<<<<<<<<<<<< * - * property ndim: + * @property */ __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __pyx_v_self->view.ndim; - for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) { - __pyx_v_i = __pyx_t_4; - __pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.suboffsets[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 567, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __pyx_t_5 = (__pyx_v_self->view.suboffsets + __pyx_v_self->view.ndim); + for (__pyx_t_6 = __pyx_v_self->view.suboffsets; __pyx_t_6 < __pyx_t_5; __pyx_t_6++) { + __pyx_t_4 = __pyx_t_6; + __pyx_v_suboffset = (__pyx_t_4[0]); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_suboffset); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 567, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) __PYX_ERR(1, 567, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } - __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_r = __pyx_t_5; - __pyx_t_5 = 0; + __pyx_t_2 = PyList_AsTuple(((PyObject*)__pyx_t_3)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 567, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_r = __pyx_t_2; + __pyx_t_2 = 0; goto __pyx_L0; - /* "View.MemoryView":527 - * property suboffsets: - * @cname('__pyx_memoryview_get_suboffsets') - * def __get__(self): # <<<<<<<<<<<<<< - * if self.view.suboffsets == NULL: - * return [-1] * self.view.ndim + /* "View.MemoryView":563 + * + * @property + * def suboffsets(self): # <<<<<<<<<<<<<< + * if self.view.suboffsets == NULL: + * return (-1,) * self.view.ndim */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); - __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -9911,55 +11732,52 @@ static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10subof return __pyx_r; } -/* "View.MemoryView":535 - * property ndim: - * @cname('__pyx_memoryview_get_ndim') - * def __get__(self): # <<<<<<<<<<<<<< - * return self.view.ndim +/* "View.MemoryView":570 + * + * @property + * def ndim(self): # <<<<<<<<<<<<<< + * return self.view.ndim * */ /* Python wrapper */ -static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":536 - * @cname('__pyx_memoryview_get_ndim') - * def __get__(self): - * return self.view.ndim # <<<<<<<<<<<<<< + /* "View.MemoryView":571 + * @property + * def ndim(self): + * return self.view.ndim # <<<<<<<<<<<<<< * - * property itemsize: + * @property */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 571, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - /* "View.MemoryView":535 - * property ndim: - * @cname('__pyx_memoryview_get_ndim') - * def __get__(self): # <<<<<<<<<<<<<< - * return self.view.ndim + /* "View.MemoryView":570 + * + * @property + * def ndim(self): # <<<<<<<<<<<<<< + * return self.view.ndim * */ @@ -9974,55 +11792,52 @@ static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__ return __pyx_r; } -/* "View.MemoryView":540 - * property itemsize: - * @cname('__pyx_memoryview_get_itemsize') - * def __get__(self): # <<<<<<<<<<<<<< - * return self.view.itemsize +/* "View.MemoryView":574 + * + * @property + * def itemsize(self): # <<<<<<<<<<<<<< + * return self.view.itemsize * */ /* Python wrapper */ -static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":541 - * @cname('__pyx_memoryview_get_itemsize') - * def __get__(self): - * return self.view.itemsize # <<<<<<<<<<<<<< + /* "View.MemoryView":575 + * @property + * def itemsize(self): + * return self.view.itemsize # <<<<<<<<<<<<<< * - * property nbytes: + * @property */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 541; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 575, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - /* "View.MemoryView":540 - * property itemsize: - * @cname('__pyx_memoryview_get_itemsize') - * def __get__(self): # <<<<<<<<<<<<<< - * return self.view.itemsize + /* "View.MemoryView":574 + * + * @property + * def itemsize(self): # <<<<<<<<<<<<<< + * return self.view.itemsize * */ @@ -10037,51 +11852,48 @@ static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize return __pyx_r; } -/* "View.MemoryView":545 - * property nbytes: - * @cname('__pyx_memoryview_get_nbytes') - * def __get__(self): # <<<<<<<<<<<<<< - * return self.size * self.view.itemsize +/* "View.MemoryView":578 + * + * @property + * def nbytes(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize * */ /* Python wrapper */ -static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":546 - * @cname('__pyx_memoryview_get_nbytes') - * def __get__(self): - * return self.size * self.view.itemsize # <<<<<<<<<<<<<< + /* "View.MemoryView":579 + * @property + * def nbytes(self): + * return self.size * self.view.itemsize # <<<<<<<<<<<<<< * - * property size: + * @property */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 579, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 579, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 579, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; @@ -10089,11 +11901,11 @@ static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___g __pyx_t_3 = 0; goto __pyx_L0; - /* "View.MemoryView":545 - * property nbytes: - * @cname('__pyx_memoryview_get_nbytes') - * def __get__(self): # <<<<<<<<<<<<<< - * return self.size * self.view.itemsize + /* "View.MemoryView":578 + * + * @property + * def nbytes(self): # <<<<<<<<<<<<<< + * return self.size * self.view.itemsize * */ @@ -10110,156 +11922,115 @@ static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___g return __pyx_r; } -/* "View.MemoryView":550 - * property size: - * @cname('__pyx_memoryview_get_size') - * def __get__(self): # <<<<<<<<<<<<<< - * if self._size is None: - * result = 1 +/* "View.MemoryView":582 + * + * @property + * def size(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 */ /* Python wrapper */ -static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { +static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_v_result = NULL; PyObject *__pyx_v_length = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; - PyObject *__pyx_t_3 = NULL; - PyObject *__pyx_t_4 = NULL; - Py_ssize_t __pyx_t_5; - PyObject *(*__pyx_t_6)(PyObject *); - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; + Py_ssize_t *__pyx_t_3; + Py_ssize_t *__pyx_t_4; + Py_ssize_t *__pyx_t_5; + PyObject *__pyx_t_6 = NULL; __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":551 - * @cname('__pyx_memoryview_get_size') - * def __get__(self): - * if self._size is None: # <<<<<<<<<<<<<< - * result = 1 + /* "View.MemoryView":583 + * @property + * def size(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 * */ __pyx_t_1 = (__pyx_v_self->_size == Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":552 - * def __get__(self): - * if self._size is None: - * result = 1 # <<<<<<<<<<<<<< + /* "View.MemoryView":584 + * def size(self): + * if self._size is None: + * result = 1 # <<<<<<<<<<<<<< * - * for length in self.shape: + * for length in self.view.shape[:self.view.ndim]: */ __Pyx_INCREF(__pyx_int_1); __pyx_v_result = __pyx_int_1; - /* "View.MemoryView":554 - * result = 1 - * - * for length in self.shape: # <<<<<<<<<<<<<< - * result *= length - * - */ - __pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - if (likely(PyList_CheckExact(__pyx_t_3)) || PyTuple_CheckExact(__pyx_t_3)) { - __pyx_t_4 = __pyx_t_3; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; - __pyx_t_6 = NULL; - } else { - __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - for (;;) { - if (likely(!__pyx_t_6)) { - if (likely(PyList_CheckExact(__pyx_t_4))) { - if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - } else { - if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - } - } else { - __pyx_t_3 = __pyx_t_6(__pyx_t_4); - if (unlikely(!__pyx_t_3)) { - PyObject* exc_type = PyErr_Occurred(); - if (exc_type) { - if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[1]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - } - break; - } - __Pyx_GOTREF(__pyx_t_3); - } - __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_3); - __pyx_t_3 = 0; - - /* "View.MemoryView":555 + /* "View.MemoryView":586 + * result = 1 * - * for length in self.shape: - * result *= length # <<<<<<<<<<<<<< + * for length in self.view.shape[:self.view.ndim]: # <<<<<<<<<<<<<< + * result *= length * - * self._size = result */ - __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 555; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_3); - __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_3); - __pyx_t_3 = 0; + __pyx_t_4 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); + for (__pyx_t_5 = __pyx_v_self->view.shape; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { + __pyx_t_3 = __pyx_t_5; + __pyx_t_6 = PyInt_FromSsize_t((__pyx_t_3[0])); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 586, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); + __pyx_t_6 = 0; - /* "View.MemoryView":554 - * result = 1 + /* "View.MemoryView":587 * - * for length in self.shape: # <<<<<<<<<<<<<< - * result *= length + * for length in self.view.shape[:self.view.ndim]: + * result *= length # <<<<<<<<<<<<<< * + * self._size = result */ + __pyx_t_6 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 587, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); + __pyx_t_6 = 0; } - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - /* "View.MemoryView":557 - * result *= length + /* "View.MemoryView":589 + * result *= length * - * self._size = result # <<<<<<<<<<<<<< + * self._size = result # <<<<<<<<<<<<<< * - * return self._size + * return self._size */ __Pyx_INCREF(__pyx_v_result); __Pyx_GIVEREF(__pyx_v_result); __Pyx_GOTREF(__pyx_v_self->_size); __Pyx_DECREF(__pyx_v_self->_size); __pyx_v_self->_size = __pyx_v_result; - goto __pyx_L3; + + /* "View.MemoryView":583 + * @property + * def size(self): + * if self._size is None: # <<<<<<<<<<<<<< + * result = 1 + * + */ } - __pyx_L3:; - /* "View.MemoryView":559 - * self._size = result + /* "View.MemoryView":591 + * self._size = result * - * return self._size # <<<<<<<<<<<<<< + * return self._size # <<<<<<<<<<<<<< * * def __len__(self): */ @@ -10268,18 +12039,17 @@ static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__ __pyx_r = __pyx_v_self->_size; goto __pyx_L0; - /* "View.MemoryView":550 - * property size: - * @cname('__pyx_memoryview_get_size') - * def __get__(self): # <<<<<<<<<<<<<< - * if self._size is None: - * result = 1 + /* "View.MemoryView":582 + * + * @property + * def size(self): # <<<<<<<<<<<<<< + * if self._size is None: + * result = 1 */ /* function exit code */ __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_3); - __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; @@ -10290,8 +12060,8 @@ static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__ return __pyx_r; } -/* "View.MemoryView":561 - * return self._size +/* "View.MemoryView":593 + * return self._size * * def __len__(self): # <<<<<<<<<<<<<< * if self.view.ndim >= 1: @@ -10304,20 +12074,20 @@ static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { +static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__len__", 0); - /* "View.MemoryView":562 + /* "View.MemoryView":594 * * def __len__(self): * if self.view.ndim >= 1: # <<<<<<<<<<<<<< @@ -10327,7 +12097,7 @@ static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __py __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); if (__pyx_t_1) { - /* "View.MemoryView":563 + /* "View.MemoryView":595 * def __len__(self): * if self.view.ndim >= 1: * return self.view.shape[0] # <<<<<<<<<<<<<< @@ -10336,9 +12106,17 @@ static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __py */ __pyx_r = (__pyx_v_self->view.shape[0]); goto __pyx_L0; + + /* "View.MemoryView":594 + * + * def __len__(self): + * if self.view.ndim >= 1: # <<<<<<<<<<<<<< + * return self.view.shape[0] + * + */ } - /* "View.MemoryView":565 + /* "View.MemoryView":597 * return self.view.shape[0] * * return 0 # <<<<<<<<<<<<<< @@ -10348,8 +12126,8 @@ static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __py __pyx_r = 0; goto __pyx_L0; - /* "View.MemoryView":561 - * return self._size + /* "View.MemoryView":593 + * return self._size * * def __len__(self): # <<<<<<<<<<<<<< * if self.view.ndim >= 1: @@ -10362,7 +12140,7 @@ static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __py return __pyx_r; } -/* "View.MemoryView":567 +/* "View.MemoryView":599 * return 0 * * def __repr__(self): # <<<<<<<<<<<<<< @@ -10376,25 +12154,22 @@ static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__repr__", 0); - /* "View.MemoryView":568 + /* "View.MemoryView":600 * * def __repr__(self): * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< @@ -10402,54 +12177,54 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __py * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 600, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 600, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 600, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "View.MemoryView":569 + /* "View.MemoryView":601 * def __repr__(self): * return "" % (self.base.__class__.__name__, * id(self)) # <<<<<<<<<<<<<< * * def __str__(self): */ - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 601, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(((PyObject *)__pyx_v_self)); - PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_id, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_id, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 601, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - /* "View.MemoryView":568 + /* "View.MemoryView":600 * * def __repr__(self): * return "" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< * id(self)) * */ - __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 600, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); __pyx_t_1 = 0; __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 600, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; - /* "View.MemoryView":567 + /* "View.MemoryView":599 * return 0 * * def __repr__(self): # <<<<<<<<<<<<<< @@ -10470,7 +12245,7 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __py return __pyx_r; } -/* "View.MemoryView":571 +/* "View.MemoryView":603 * id(self)) * * def __str__(self): # <<<<<<<<<<<<<< @@ -10484,24 +12259,21 @@ static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); - __pyx_r = __pyx_memoryview_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__str__", 0); - /* "View.MemoryView":572 + /* "View.MemoryView":604 * * def __str__(self): * return "" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< @@ -10509,27 +12281,27 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 604, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 604, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 604, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 604, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __pyx_t_1 = 0; - __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 604, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - /* "View.MemoryView":571 + /* "View.MemoryView":603 * id(self)) * * def __str__(self): # <<<<<<<<<<<<<< @@ -10549,7 +12321,7 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx return __pyx_r; } -/* "View.MemoryView":575 +/* "View.MemoryView":607 * * * def is_c_contig(self): # <<<<<<<<<<<<<< @@ -10563,48 +12335,45 @@ static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNU PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); - __pyx_r = __pyx_memoryview_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice *__pyx_v_mslice; __Pyx_memviewslice __pyx_v_tmp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("is_c_contig", 0); - /* "View.MemoryView":578 + /* "View.MemoryView":610 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< - * return slice_is_contig(mslice, 'C', self.view.ndim) + * return slice_is_contig(mslice[0], 'C', self.view.ndim) * */ __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); - /* "View.MemoryView":579 + /* "View.MemoryView":611 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) - * return slice_is_contig(mslice, 'C', self.view.ndim) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice[0], 'C', self.view.ndim) # <<<<<<<<<<<<<< * * def is_f_contig(self): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 611, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - /* "View.MemoryView":575 + /* "View.MemoryView":607 * * * def is_c_contig(self): # <<<<<<<<<<<<<< @@ -10623,8 +12392,8 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct _ return __pyx_r; } -/* "View.MemoryView":581 - * return slice_is_contig(mslice, 'C', self.view.ndim) +/* "View.MemoryView":613 + * return slice_is_contig(mslice[0], 'C', self.view.ndim) * * def is_f_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice @@ -10637,49 +12406,46 @@ static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNU PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); - __pyx_r = __pyx_memoryview_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice *__pyx_v_mslice; __Pyx_memviewslice __pyx_v_tmp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("is_f_contig", 0); - /* "View.MemoryView":584 + /* "View.MemoryView":616 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< - * return slice_is_contig(mslice, 'F', self.view.ndim) + * return slice_is_contig(mslice[0], 'F', self.view.ndim) * */ __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); - /* "View.MemoryView":585 + /* "View.MemoryView":617 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) - * return slice_is_contig(mslice, 'F', self.view.ndim) # <<<<<<<<<<<<<< + * return slice_is_contig(mslice[0], 'F', self.view.ndim) # <<<<<<<<<<<<<< * * def copy(self): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig((__pyx_v_mslice[0]), 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 617, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - /* "View.MemoryView":581 - * return slice_is_contig(mslice, 'C', self.view.ndim) + /* "View.MemoryView":613 + * return slice_is_contig(mslice[0], 'C', self.view.ndim) * * def is_f_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice @@ -10697,8 +12463,8 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct _ return __pyx_r; } -/* "View.MemoryView":587 - * return slice_is_contig(mslice, 'F', self.view.ndim) +/* "View.MemoryView":619 + * return slice_is_contig(mslice[0], 'F', self.view.ndim) * * def copy(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice mslice @@ -10711,26 +12477,23 @@ static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyO PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("copy (wrapper)", 0); - __pyx_r = __pyx_memoryview_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice __pyx_v_mslice; int __pyx_v_flags; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_memviewslice __pyx_t_1; PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("copy", 0); - /* "View.MemoryView":589 + /* "View.MemoryView":621 * def copy(self): * cdef __Pyx_memviewslice mslice * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< @@ -10739,7 +12502,7 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_me */ __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); - /* "View.MemoryView":591 + /* "View.MemoryView":623 * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS * * slice_copy(self, &mslice) # <<<<<<<<<<<<<< @@ -10748,17 +12511,17 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_me */ __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); - /* "View.MemoryView":592 + /* "View.MemoryView":624 * * slice_copy(self, &mslice) * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<< * self.view.itemsize, * flags|PyBUF_C_CONTIGUOUS, */ - __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), __pyx_k_c, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), ((char *)"c"), __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) __PYX_ERR(1, 624, __pyx_L1_error) __pyx_v_mslice = __pyx_t_1; - /* "View.MemoryView":597 + /* "View.MemoryView":629 * self.dtype_is_object) * * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< @@ -10766,14 +12529,14 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_me * def copy_fortran(self): */ __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 629, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; - /* "View.MemoryView":587 - * return slice_is_contig(mslice, 'F', self.view.ndim) + /* "View.MemoryView":619 + * return slice_is_contig(mslice[0], 'F', self.view.ndim) * * def copy(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice mslice @@ -10791,7 +12554,7 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_me return __pyx_r; } -/* "View.MemoryView":599 +/* "View.MemoryView":631 * return memoryview_copy_from_slice(self, &mslice) * * def copy_fortran(self): # <<<<<<<<<<<<<< @@ -10805,14 +12568,14 @@ static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UN PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); - __pyx_r = __pyx_memoryview_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); + __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { +static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice __pyx_v_src; __Pyx_memviewslice __pyx_v_dst; int __pyx_v_flags; @@ -10820,12 +12583,9 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __Pyx_RefNannyDeclarations __Pyx_memviewslice __pyx_t_1; PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("copy_fortran", 0); - /* "View.MemoryView":601 + /* "View.MemoryView":633 * def copy_fortran(self): * cdef __Pyx_memviewslice src, dst * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< @@ -10834,7 +12594,7 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct */ __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); - /* "View.MemoryView":603 + /* "View.MemoryView":635 * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS * * slice_copy(self, &src) # <<<<<<<<<<<<<< @@ -10843,17 +12603,17 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct */ __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); - /* "View.MemoryView":604 + /* "View.MemoryView":636 * * slice_copy(self, &src) * dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<< * self.view.itemsize, * flags|PyBUF_F_CONTIGUOUS, */ - __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), __pyx_k_fortran, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), ((char *)"fortran"), __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) __PYX_ERR(1, 636, __pyx_L1_error) __pyx_v_dst = __pyx_t_1; - /* "View.MemoryView":609 + /* "View.MemoryView":641 * self.dtype_is_object) * * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< @@ -10861,13 +12621,13 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct * */ __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 641, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; - /* "View.MemoryView":599 + /* "View.MemoryView":631 * return memoryview_copy_from_slice(self, &mslice) * * def copy_fortran(self): # <<<<<<<<<<<<<< @@ -10886,55 +12646,159 @@ static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct return __pyx_r; } -/* "View.MemoryView":613 - * - * @cname('__pyx_memoryview_new') - * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< - * cdef memoryview result = memoryview(o, flags, dtype_is_object) - * result.typeinfo = typeinfo +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): */ -static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { - struct __pyx_memoryview_obj *__pyx_v_result = 0; +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw___pyx_memoryview_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_memoryview___reduce_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_memoryview___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__24, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(1, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ +static PyObject *__pyx_pw___pyx_memoryview_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_memoryview_2__setstate_cython__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_memoryview_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryview_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":4 + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__25, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(1, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView.memoryview.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":645 + * + * @cname('__pyx_memoryview_new') + * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< + * cdef memoryview result = memoryview(o, flags, dtype_is_object) + * result.typeinfo = typeinfo + */ + +static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { + struct __pyx_memoryview_obj *__pyx_v_result = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); - /* "View.MemoryView":614 + /* "View.MemoryView":646 * @cname('__pyx_memoryview_new') * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< * result.typeinfo = typeinfo * return result */ - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 646, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 646, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 646, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_o); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); __Pyx_GIVEREF(__pyx_v_o); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryview_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 646, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); __pyx_t_2 = 0; - /* "View.MemoryView":615 + /* "View.MemoryView":647 * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo # <<<<<<<<<<<<<< @@ -10943,7 +12807,7 @@ static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, in */ __pyx_v_result->typeinfo = __pyx_v_typeinfo; - /* "View.MemoryView":616 + /* "View.MemoryView":648 * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo * return result # <<<<<<<<<<<<<< @@ -10955,7 +12819,7 @@ static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, in __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; - /* "View.MemoryView":613 + /* "View.MemoryView":645 * * @cname('__pyx_memoryview_new') * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< @@ -10977,7 +12841,7 @@ static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, in return __pyx_r; } -/* "View.MemoryView":619 +/* "View.MemoryView":651 * * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< @@ -10991,18 +12855,18 @@ static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { int __pyx_t_1; __Pyx_RefNannySetupContext("memoryview_check", 0); - /* "View.MemoryView":620 + /* "View.MemoryView":652 * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): * return isinstance(o, memoryview) # <<<<<<<<<<<<<< * * cdef tuple _unellipsify(object index, int ndim): */ - __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, ((PyObject *)__pyx_memoryview_type)); + __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, __pyx_memoryview_type); __pyx_r = __pyx_t_1; goto __pyx_L0; - /* "View.MemoryView":619 + /* "View.MemoryView":651 * * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< @@ -11016,7 +12880,7 @@ static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { return __pyx_r; } -/* "View.MemoryView":622 +/* "View.MemoryView":654 * return isinstance(o, memoryview) * * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< @@ -11045,12 +12909,9 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { int __pyx_t_9; int __pyx_t_10; PyObject *__pyx_t_11 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_unellipsify", 0); - /* "View.MemoryView":627 + /* "View.MemoryView":659 * full slices. * """ * if not isinstance(index, tuple): # <<<<<<<<<<<<<< @@ -11061,49 +12922,57 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":628 + /* "View.MemoryView":660 * """ * if not isinstance(index, tuple): * tup = (index,) # <<<<<<<<<<<<<< * else: * tup = index */ - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 660, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_index); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); __Pyx_GIVEREF(__pyx_v_index); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); __pyx_v_tup = __pyx_t_3; __pyx_t_3 = 0; + + /* "View.MemoryView":659 + * full slices. + * """ + * if not isinstance(index, tuple): # <<<<<<<<<<<<<< + * tup = (index,) + * else: + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":630 + /* "View.MemoryView":662 * tup = (index,) * else: * tup = index # <<<<<<<<<<<<<< * * result = [] */ + /*else*/ { __Pyx_INCREF(__pyx_v_index); __pyx_v_tup = __pyx_v_index; } __pyx_L3:; - /* "View.MemoryView":632 + /* "View.MemoryView":664 * tup = index * * result = [] # <<<<<<<<<<<<<< * have_slices = False * seen_ellipsis = False */ - __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 664, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_v_result = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; - /* "View.MemoryView":633 + /* "View.MemoryView":665 * * result = [] * have_slices = False # <<<<<<<<<<<<<< @@ -11112,7 +12981,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { */ __pyx_v_have_slices = 0; - /* "View.MemoryView":634 + /* "View.MemoryView":666 * result = [] * have_slices = False * seen_ellipsis = False # <<<<<<<<<<<<<< @@ -11121,7 +12990,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { */ __pyx_v_seen_ellipsis = 0; - /* "View.MemoryView":635 + /* "View.MemoryView":667 * have_slices = False * seen_ellipsis = False * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< @@ -11134,25 +13003,27 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; __pyx_t_6 = NULL; } else { - __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 667, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 667, __pyx_L1_error) } for (;;) { if (likely(!__pyx_t_6)) { if (likely(PyList_CheckExact(__pyx_t_4))) { if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(1, 667, __pyx_L1_error) #else - __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 667, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); #endif } else { if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) __PYX_ERR(1, 667, __pyx_L1_error) #else - __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 667, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); #endif } } else { @@ -11160,8 +13031,8 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { if (unlikely(!__pyx_t_7)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { - if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[1]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(1, 667, __pyx_L1_error) } break; } @@ -11171,13 +13042,13 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_t_7 = 0; __Pyx_INCREF(__pyx_t_3); __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3); - __pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyInt_AddObjC(__pyx_t_3, __pyx_int_1, 1, 0); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 667, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = __pyx_t_7; __pyx_t_7 = 0; - /* "View.MemoryView":636 + /* "View.MemoryView":668 * seen_ellipsis = False * for idx, item in enumerate(tup): * if item is Ellipsis: # <<<<<<<<<<<<<< @@ -11188,7 +13059,7 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { - /* "View.MemoryView":637 + /* "View.MemoryView":669 * for idx, item in enumerate(tup): * if item is Ellipsis: * if not seen_ellipsis: # <<<<<<<<<<<<<< @@ -11198,27 +13069,27 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); if (__pyx_t_1) { - /* "View.MemoryView":638 + /* "View.MemoryView":670 * if item is Ellipsis: * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< * seen_ellipsis = True * else: */ - __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_t_7 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == ((Py_ssize_t)-1))) __PYX_ERR(1, 670, __pyx_L1_error) + __pyx_t_7 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 670, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); { Py_ssize_t __pyx_temp; for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) { - __Pyx_INCREF(__pyx_slice__18); - PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__18); - __Pyx_GIVEREF(__pyx_slice__18); + __Pyx_INCREF(__pyx_slice__26); + __Pyx_GIVEREF(__pyx_slice__26); + PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__26); } } - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 670, __pyx_L1_error) __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - /* "View.MemoryView":639 + /* "View.MemoryView":671 * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) * seen_ellipsis = True # <<<<<<<<<<<<<< @@ -11226,22 +13097,30 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { * result.append(slice(None)) */ __pyx_v_seen_ellipsis = 1; + + /* "View.MemoryView":669 + * for idx, item in enumerate(tup): + * if item is Ellipsis: + * if not seen_ellipsis: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + * seen_ellipsis = True + */ goto __pyx_L7; } - /*else*/ { - /* "View.MemoryView":641 + /* "View.MemoryView":673 * seen_ellipsis = True * else: * result.append(slice(None)) # <<<<<<<<<<<<<< * have_slices = True * else: */ - __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__19); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*else*/ { + __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__27); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 673, __pyx_L1_error) } __pyx_L7:; - /* "View.MemoryView":642 + /* "View.MemoryView":674 * else: * result.append(slice(None)) * have_slices = True # <<<<<<<<<<<<<< @@ -11249,17 +13128,25 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { * if not isinstance(item, slice) and not PyIndex_Check(item): */ __pyx_v_have_slices = 1; + + /* "View.MemoryView":668 + * seen_ellipsis = False + * for idx, item in enumerate(tup): + * if item is Ellipsis: # <<<<<<<<<<<<<< + * if not seen_ellipsis: + * result.extend([slice(None)] * (ndim - len(tup) + 1)) + */ goto __pyx_L6; } - /*else*/ { - /* "View.MemoryView":644 + /* "View.MemoryView":676 * have_slices = True * else: * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< * raise TypeError("Cannot index with type '%s'" % type(item)) * */ + /*else*/ { __pyx_t_2 = PySlice_Check(__pyx_v_item); __pyx_t_10 = ((!(__pyx_t_2 != 0)) != 0); if (__pyx_t_10) { @@ -11272,29 +13159,37 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_L9_bool_binop_done:; if (__pyx_t_1) { - /* "View.MemoryView":645 + /* "View.MemoryView":677 * else: * if not isinstance(item, slice) and not PyIndex_Check(item): * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< * * have_slices = have_slices or isinstance(item, slice) */ - __pyx_t_7 = __Pyx_PyString_Format(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyString_Format(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 677, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); - __pyx_t_11 = PyTuple_New(1); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = PyTuple_New(1); if (unlikely(!__pyx_t_11)) __PYX_ERR(1, 677, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_11); - PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); + PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_7); __pyx_t_7 = 0; - __pyx_t_7 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_11, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_11, NULL); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 677, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; __Pyx_Raise(__pyx_t_7, 0, 0, 0); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 677, __pyx_L1_error) + + /* "View.MemoryView":676 + * have_slices = True + * else: + * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< + * raise TypeError("Cannot index with type '%s'" % type(item)) + * + */ } - /* "View.MemoryView":647 + /* "View.MemoryView":679 * raise TypeError("Cannot index with type '%s'" % type(item)) * * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< @@ -11313,18 +13208,18 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_L11_bool_binop_done:; __pyx_v_have_slices = __pyx_t_1; - /* "View.MemoryView":648 + /* "View.MemoryView":680 * * have_slices = have_slices or isinstance(item, slice) * result.append(item) # <<<<<<<<<<<<<< * * nslices = ndim - len(result) */ - __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 680, __pyx_L1_error) } __pyx_L6:; - /* "View.MemoryView":635 + /* "View.MemoryView":667 * have_slices = False * seen_ellipsis = False * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< @@ -11335,17 +13230,17 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "View.MemoryView":650 + /* "View.MemoryView":682 * result.append(item) * * nslices = ndim - len(result) # <<<<<<<<<<<<<< * if nslices: * result.extend([slice(None)] * nslices) */ - __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == ((Py_ssize_t)-1))) __PYX_ERR(1, 682, __pyx_L1_error) __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); - /* "View.MemoryView":651 + /* "View.MemoryView":683 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< @@ -11355,29 +13250,35 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __pyx_t_1 = (__pyx_v_nslices != 0); if (__pyx_t_1) { - /* "View.MemoryView":652 + /* "View.MemoryView":684 * nslices = ndim - len(result) * if nslices: * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< * * return have_slices or nslices, tuple(result) */ - __pyx_t_3 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 684, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); { Py_ssize_t __pyx_temp; for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { - __Pyx_INCREF(__pyx_slice__20); - PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__20); - __Pyx_GIVEREF(__pyx_slice__20); + __Pyx_INCREF(__pyx_slice__28); + __Pyx_GIVEREF(__pyx_slice__28); + PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__28); } } - __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == ((int)-1))) __PYX_ERR(1, 684, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - goto __pyx_L13; + + /* "View.MemoryView":683 + * + * nslices = ndim - len(result) + * if nslices: # <<<<<<<<<<<<<< + * result.extend([slice(None)] * nslices) + * + */ } - __pyx_L13:; - /* "View.MemoryView":654 + /* "View.MemoryView":686 * result.extend([slice(None)] * nslices) * * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< @@ -11387,32 +13288,32 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { __Pyx_XDECREF(__pyx_r); if (!__pyx_v_have_slices) { } else { - __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 686, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __pyx_t_4; __pyx_t_4 = 0; goto __pyx_L14_bool_binop_done; } - __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 686, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __pyx_t_4; __pyx_t_4 = 0; __pyx_L14_bool_binop_done:; - __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 686, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 686, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); - PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_4); __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_r = ((PyObject*)__pyx_t_7); __pyx_t_7 = 0; goto __pyx_L0; - /* "View.MemoryView":622 + /* "View.MemoryView":654 * return isinstance(o, memoryview) * * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< @@ -11438,76 +13339,83 @@ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { return __pyx_r; } -/* "View.MemoryView":656 +/* "View.MemoryView":688 * return have_slices or nslices, tuple(result) * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< - * cdef int i - * for i in range(ndim): + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: */ static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { - int __pyx_v_i; + Py_ssize_t __pyx_v_suboffset; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations - int __pyx_t_1; - int __pyx_t_2; - int __pyx_t_3; - PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; + Py_ssize_t *__pyx_t_1; + Py_ssize_t *__pyx_t_2; + Py_ssize_t *__pyx_t_3; + int __pyx_t_4; + PyObject *__pyx_t_5 = NULL; __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); - /* "View.MemoryView":658 + /* "View.MemoryView":689 + * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): - * cdef int i - * for i in range(ndim): # <<<<<<<<<<<<<< - * if suboffsets[i] >= 0: + * for suboffset in suboffsets[:ndim]: # <<<<<<<<<<<<<< + * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") */ - __pyx_t_1 = __pyx_v_ndim; - for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { - __pyx_v_i = __pyx_t_2; + __pyx_t_2 = (__pyx_v_suboffsets + __pyx_v_ndim); + for (__pyx_t_3 = __pyx_v_suboffsets; __pyx_t_3 < __pyx_t_2; __pyx_t_3++) { + __pyx_t_1 = __pyx_t_3; + __pyx_v_suboffset = (__pyx_t_1[0]); - /* "View.MemoryView":659 - * cdef int i - * for i in range(ndim): - * if suboffsets[i] >= 0: # <<<<<<<<<<<<<< + /* "View.MemoryView":690 + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: # <<<<<<<<<<<<<< * raise ValueError("Indirect dimensions not supported") * */ - __pyx_t_3 = (((__pyx_v_suboffsets[__pyx_v_i]) >= 0) != 0); - if (__pyx_t_3) { + __pyx_t_4 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_4) { - /* "View.MemoryView":660 - * for i in range(ndim): - * if suboffsets[i] >= 0: + /* "View.MemoryView":691 + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< * * */ - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__21, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_4); - __Pyx_Raise(__pyx_t_4, 0, 0, 0); - __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__29, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 691, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_Raise(__pyx_t_5, 0, 0, 0); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + __PYX_ERR(1, 691, __pyx_L1_error) + + /* "View.MemoryView":690 + * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: # <<<<<<<<<<<<<< + * raise ValueError("Indirect dimensions not supported") + * + */ } } - /* "View.MemoryView":656 + /* "View.MemoryView":688 * return have_slices or nslices, tuple(result) * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< - * cdef int i - * for i in range(ndim): + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; - __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; @@ -11516,7 +13424,7 @@ static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __ return __pyx_r; } -/* "View.MemoryView":667 +/* "View.MemoryView":698 * * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< @@ -11555,12 +13463,9 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ Py_ssize_t __pyx_t_10; int __pyx_t_11; Py_ssize_t __pyx_t_12; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memview_slice", 0); - /* "View.MemoryView":668 + /* "View.MemoryView":699 * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< @@ -11570,7 +13475,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_v_new_ndim = 0; __pyx_v_suboffset_dim = -1; - /* "View.MemoryView":675 + /* "View.MemoryView":706 * * * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< @@ -11579,7 +13484,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst))); - /* "View.MemoryView":679 + /* "View.MemoryView":710 * cdef _memoryviewslice memviewsliceobj * * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< @@ -11590,36 +13495,36 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ if (unlikely(!Py_OptimizeFlag)) { if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { PyErr_SetNone(PyExc_AssertionError); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 679; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 710, __pyx_L1_error) } } #endif - /* "View.MemoryView":681 + /* "View.MemoryView":712 * assert memview.view.ndim > 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":682 + /* "View.MemoryView":713 * * if isinstance(memview, _memoryviewslice): * memviewsliceobj = memview # <<<<<<<<<<<<<< * p_src = &memviewsliceobj.from_slice * else: */ - if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 682; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(1, 713, __pyx_L1_error) __pyx_t_3 = ((PyObject *)__pyx_v_memview); __Pyx_INCREF(__pyx_t_3); __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); __pyx_t_3 = 0; - /* "View.MemoryView":683 + /* "View.MemoryView":714 * if isinstance(memview, _memoryviewslice): * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< @@ -11627,20 +13532,28 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ * slice_copy(memview, &src) */ __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); + + /* "View.MemoryView":712 + * assert memview.view.ndim > 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * memviewsliceobj = memview + * p_src = &memviewsliceobj.from_slice + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":685 + /* "View.MemoryView":716 * p_src = &memviewsliceobj.from_slice * else: * slice_copy(memview, &src) # <<<<<<<<<<<<<< * p_src = &src * */ + /*else*/ { __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); - /* "View.MemoryView":686 + /* "View.MemoryView":717 * else: * slice_copy(memview, &src) * p_src = &src # <<<<<<<<<<<<<< @@ -11651,7 +13564,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ } __pyx_L3:; - /* "View.MemoryView":692 + /* "View.MemoryView":723 * * * dst.memview = p_src.memview # <<<<<<<<<<<<<< @@ -11661,7 +13574,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_t_4 = __pyx_v_p_src->memview; __pyx_v_dst.memview = __pyx_t_4; - /* "View.MemoryView":693 + /* "View.MemoryView":724 * * dst.memview = p_src.memview * dst.data = p_src.data # <<<<<<<<<<<<<< @@ -11671,7 +13584,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_t_5 = __pyx_v_p_src->data; __pyx_v_dst.data = __pyx_t_5; - /* "View.MemoryView":698 + /* "View.MemoryView":729 * * * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< @@ -11680,7 +13593,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ __pyx_v_p_dst = (&__pyx_v_dst); - /* "View.MemoryView":699 + /* "View.MemoryView":730 * * cdef __Pyx_memviewslice *p_dst = &dst * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< @@ -11689,7 +13602,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); - /* "View.MemoryView":703 + /* "View.MemoryView":734 * cdef bint have_start, have_stop, have_step * * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< @@ -11701,25 +13614,27 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; __pyx_t_8 = NULL; } else { - __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 734, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 734, __pyx_L1_error) } for (;;) { if (likely(!__pyx_t_8)) { if (likely(PyList_CheckExact(__pyx_t_3))) { if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) __PYX_ERR(1, 734, __pyx_L1_error) #else - __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 734, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); #endif } else { if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; - #if CYTHON_COMPILING_IN_CPYTHON - __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) __PYX_ERR(1, 734, __pyx_L1_error) #else - __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 734, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); #endif } } else { @@ -11727,8 +13642,8 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ if (unlikely(!__pyx_t_9)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { - if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); - else {__pyx_filename = __pyx_f[1]; __pyx_lineno = 703; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); + else __PYX_ERR(1, 734, __pyx_L1_error) } break; } @@ -11739,7 +13654,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_v_dim = __pyx_t_6; __pyx_t_6 = (__pyx_t_6 + 1); - /* "View.MemoryView":704 + /* "View.MemoryView":735 * * for dim, index in enumerate(indices): * if PyIndex_Check(index): # <<<<<<<<<<<<<< @@ -11749,27 +13664,35 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_t_2 = (PyIndex_Check(__pyx_v_index) != 0); if (__pyx_t_2) { - /* "View.MemoryView":708 + /* "View.MemoryView":739 * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< * 0, 0, 0, # have_{start,stop,step} * False) */ - __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 708; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 739, __pyx_L1_error) - /* "View.MemoryView":705 + /* "View.MemoryView":736 * for dim, index in enumerate(indices): * if PyIndex_Check(index): * slice_memviewslice( # <<<<<<<<<<<<<< * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, */ - __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 705; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(1, 736, __pyx_L1_error) + + /* "View.MemoryView":735 + * + * for dim, index in enumerate(indices): + * if PyIndex_Check(index): # <<<<<<<<<<<<<< + * slice_memviewslice( + * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], + */ goto __pyx_L6; } - /* "View.MemoryView":711 + /* "View.MemoryView":742 * 0, 0, 0, # have_{start,stop,step} * False) * elif index is None: # <<<<<<<<<<<<<< @@ -11780,7 +13703,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { - /* "View.MemoryView":712 + /* "View.MemoryView":743 * False) * elif index is None: * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< @@ -11789,7 +13712,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; - /* "View.MemoryView":713 + /* "View.MemoryView":744 * elif index is None: * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< @@ -11798,16 +13721,16 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; - /* "View.MemoryView":714 + /* "View.MemoryView":745 * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< * new_ndim += 1 * else: */ - (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1; + (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1L; - /* "View.MemoryView":715 + /* "View.MemoryView":746 * p_dst.strides[new_ndim] = 0 * p_dst.suboffsets[new_ndim] = -1 * new_ndim += 1 # <<<<<<<<<<<<<< @@ -11815,24 +13738,32 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ * start = index.start or 0 */ __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); + + /* "View.MemoryView":742 + * 0, 0, 0, # have_{start,stop,step} + * False) + * elif index is None: # <<<<<<<<<<<<<< + * p_dst.shape[new_ndim] = 1 + * p_dst.strides[new_ndim] = 0 + */ goto __pyx_L6; } - /*else*/ { - /* "View.MemoryView":717 + /* "View.MemoryView":748 * new_ndim += 1 * else: * start = index.start or 0 # <<<<<<<<<<<<<< * stop = index.stop or 0 * step = index.step or 0 */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*else*/ { + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 748, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 748, __pyx_L1_error) if (!__pyx_t_1) { __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } else { - __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 748, __pyx_L1_error) __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L7_bool_binop_done; @@ -11841,20 +13772,20 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_L7_bool_binop_done:; __pyx_v_start = __pyx_t_10; - /* "View.MemoryView":718 + /* "View.MemoryView":749 * else: * start = index.start or 0 * stop = index.stop or 0 # <<<<<<<<<<<<<< * step = index.step or 0 * */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 749, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 749, __pyx_L1_error) if (!__pyx_t_1) { __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } else { - __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 749, __pyx_L1_error) __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L9_bool_binop_done; @@ -11863,20 +13794,20 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_L9_bool_binop_done:; __pyx_v_stop = __pyx_t_10; - /* "View.MemoryView":719 + /* "View.MemoryView":750 * start = index.start or 0 * stop = index.stop or 0 * step = index.step or 0 # <<<<<<<<<<<<<< * * have_start = index.start is not None */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 750, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); - __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(1, 750, __pyx_L1_error) if (!__pyx_t_1) { __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } else { - __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 719; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 750, __pyx_L1_error) __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L11_bool_binop_done; @@ -11885,55 +13816,55 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ __pyx_L11_bool_binop_done:; __pyx_v_step = __pyx_t_10; - /* "View.MemoryView":721 + /* "View.MemoryView":752 * step = index.step or 0 * * have_start = index.start is not None # <<<<<<<<<<<<<< * have_stop = index.stop is not None * have_step = index.step is not None */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 721; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 752, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = (__pyx_t_9 != Py_None); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_have_start = __pyx_t_1; - /* "View.MemoryView":722 + /* "View.MemoryView":753 * * have_start = index.start is not None * have_stop = index.stop is not None # <<<<<<<<<<<<<< * have_step = index.step is not None * */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 753, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = (__pyx_t_9 != Py_None); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_have_stop = __pyx_t_1; - /* "View.MemoryView":723 + /* "View.MemoryView":754 * have_start = index.start is not None * have_stop = index.stop is not None * have_step = index.step is not None # <<<<<<<<<<<<<< * * slice_memviewslice( */ - __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 723; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 754, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = (__pyx_t_9 != Py_None); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_have_step = __pyx_t_1; - /* "View.MemoryView":725 + /* "View.MemoryView":756 * have_step = index.step is not None * * slice_memviewslice( # <<<<<<<<<<<<<< * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, */ - __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 725; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == ((int)-1))) __PYX_ERR(1, 756, __pyx_L1_error) - /* "View.MemoryView":731 + /* "View.MemoryView":762 * have_start, have_stop, have_step, * True) * new_ndim += 1 # <<<<<<<<<<<<<< @@ -11944,7 +13875,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ } __pyx_L6:; - /* "View.MemoryView":703 + /* "View.MemoryView":734 * cdef bint have_start, have_stop, have_step * * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< @@ -11954,18 +13885,18 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - /* "View.MemoryView":733 + /* "View.MemoryView":764 * new_ndim += 1 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":734 + /* "View.MemoryView":765 * * if isinstance(memview, _memoryviewslice): * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< @@ -11974,73 +13905,81 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ */ __Pyx_XDECREF(((PyObject *)__pyx_r)); - /* "View.MemoryView":735 + /* "View.MemoryView":766 * if isinstance(memview, _memoryviewslice): * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< * memviewsliceobj.to_dtype_func, * memview.dtype_is_object) */ - if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 735; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(1, 766, __pyx_L1_error) } - /* "View.MemoryView":736 + /* "View.MemoryView":767 * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, * memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<< * memview.dtype_is_object) * else: */ - if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 736; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } + if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); __PYX_ERR(1, 767, __pyx_L1_error) } - /* "View.MemoryView":734 + /* "View.MemoryView":765 * * if isinstance(memview, _memoryviewslice): * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< * memviewsliceobj.to_object_func, * memviewsliceobj.to_dtype_func, */ - __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 734; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 765, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 734; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(1, 765, __pyx_L1_error) __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; + + /* "View.MemoryView":764 + * new_ndim += 1 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * return memoryview_fromslice(dst, new_ndim, + * memviewsliceobj.to_object_func, + */ } - /*else*/ { - /* "View.MemoryView":739 + /* "View.MemoryView":770 * memview.dtype_is_object) * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< * memview.dtype_is_object) * */ + /*else*/ { __Pyx_XDECREF(((PyObject *)__pyx_r)); - /* "View.MemoryView":740 + /* "View.MemoryView":771 * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, * memview.dtype_is_object) # <<<<<<<<<<<<<< * * */ - __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 770, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - /* "View.MemoryView":739 + /* "View.MemoryView":770 * memview.dtype_is_object) * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< * memview.dtype_is_object) * */ - if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 739; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) __PYX_ERR(1, 770, __pyx_L1_error) __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; } - /* "View.MemoryView":667 + /* "View.MemoryView":698 * * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< @@ -12062,7 +14001,7 @@ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_ return __pyx_r; } -/* "View.MemoryView":764 +/* "View.MemoryView":795 * * @cname('__pyx_memoryview_slice_memviewslice') * cdef int slice_memviewslice( # <<<<<<<<<<<<<< @@ -12077,11 +14016,8 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - /* "View.MemoryView":784 + /* "View.MemoryView":815 * cdef bint negative_step * * if not is_slice: # <<<<<<<<<<<<<< @@ -12091,7 +14027,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); if (__pyx_t_1) { - /* "View.MemoryView":786 + /* "View.MemoryView":817 * if not is_slice: * * if start < 0: # <<<<<<<<<<<<<< @@ -12101,7 +14037,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_1 = ((__pyx_v_start < 0) != 0); if (__pyx_t_1) { - /* "View.MemoryView":787 + /* "View.MemoryView":818 * * if start < 0: * start += shape # <<<<<<<<<<<<<< @@ -12109,11 +14045,17 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) */ __pyx_v_start = (__pyx_v_start + __pyx_v_shape); - goto __pyx_L4; + + /* "View.MemoryView":817 + * if not is_slice: + * + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if not 0 <= start < shape: + */ } - __pyx_L4:; - /* "View.MemoryView":788 + /* "View.MemoryView":819 * if start < 0: * start += shape * if not 0 <= start < shape: # <<<<<<<<<<<<<< @@ -12127,28 +14069,42 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":789 + /* "View.MemoryView":820 * start += shape * if not 0 <= start < shape: * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< * else: * */ - __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_Index_out_of_bounds_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 789; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"Index out of bounds (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 820, __pyx_L1_error) + + /* "View.MemoryView":819 + * if start < 0: + * start += shape + * if not 0 <= start < shape: # <<<<<<<<<<<<<< + * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) + * else: + */ } - __pyx_L5:; + + /* "View.MemoryView":815 + * cdef bint negative_step + * + * if not is_slice: # <<<<<<<<<<<<<< + * + * if start < 0: + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":792 + /* "View.MemoryView":823 * else: * * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< * * if have_step and step == 0: */ + /*else*/ { __pyx_t_1 = ((__pyx_v_have_step != 0) != 0); if (__pyx_t_1) { } else { @@ -12160,7 +14116,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_L6_bool_binop_done:; __pyx_v_negative_step = __pyx_t_2; - /* "View.MemoryView":794 + /* "View.MemoryView":825 * negative_step = have_step != 0 and step < 0 * * if have_step and step == 0: # <<<<<<<<<<<<<< @@ -12178,19 +14134,25 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_L9_bool_binop_done:; if (__pyx_t_2) { - /* "View.MemoryView":795 + /* "View.MemoryView":826 * * if have_step and step == 0: * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< * * */ - __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Step_may_not_be_zero_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; - } - __pyx_L8:; + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Step may not be zero (axis %d)"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 826, __pyx_L1_error) + + /* "View.MemoryView":825 + * negative_step = have_step != 0 and step < 0 + * + * if have_step and step == 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) + * + */ + } - /* "View.MemoryView":798 + /* "View.MemoryView":829 * * * if have_start: # <<<<<<<<<<<<<< @@ -12200,7 +14162,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = (__pyx_v_have_start != 0); if (__pyx_t_2) { - /* "View.MemoryView":799 + /* "View.MemoryView":830 * * if have_start: * if start < 0: # <<<<<<<<<<<<<< @@ -12210,7 +14172,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_start < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":800 + /* "View.MemoryView":831 * if have_start: * if start < 0: * start += shape # <<<<<<<<<<<<<< @@ -12219,7 +14181,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_start = (__pyx_v_start + __pyx_v_shape); - /* "View.MemoryView":801 + /* "View.MemoryView":832 * if start < 0: * start += shape * if start < 0: # <<<<<<<<<<<<<< @@ -12229,7 +14191,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_start < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":802 + /* "View.MemoryView":833 * start += shape * if start < 0: * start = 0 # <<<<<<<<<<<<<< @@ -12237,13 +14199,27 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, * if negative_step: */ __pyx_v_start = 0; - goto __pyx_L13; + + /* "View.MemoryView":832 + * if start < 0: + * start += shape + * if start < 0: # <<<<<<<<<<<<<< + * start = 0 + * elif start >= shape: + */ } - __pyx_L13:; + + /* "View.MemoryView":830 + * + * if have_start: + * if start < 0: # <<<<<<<<<<<<<< + * start += shape + * if start < 0: + */ goto __pyx_L12; } - /* "View.MemoryView":803 + /* "View.MemoryView":834 * if start < 0: * start = 0 * elif start >= shape: # <<<<<<<<<<<<<< @@ -12253,7 +14229,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); if (__pyx_t_2) { - /* "View.MemoryView":804 + /* "View.MemoryView":835 * start = 0 * elif start >= shape: * if negative_step: # <<<<<<<<<<<<<< @@ -12263,7 +14239,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { - /* "View.MemoryView":805 + /* "View.MemoryView":836 * elif start >= shape: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< @@ -12271,38 +14247,61 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, * start = shape */ __pyx_v_start = (__pyx_v_shape - 1); + + /* "View.MemoryView":835 + * start = 0 + * elif start >= shape: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ goto __pyx_L14; } - /*else*/ { - /* "View.MemoryView":807 + /* "View.MemoryView":838 * start = shape - 1 * else: * start = shape # <<<<<<<<<<<<<< * else: * if negative_step: */ + /*else*/ { __pyx_v_start = __pyx_v_shape; } __pyx_L14:; - goto __pyx_L12; + + /* "View.MemoryView":834 + * if start < 0: + * start = 0 + * elif start >= shape: # <<<<<<<<<<<<<< + * if negative_step: + * start = shape - 1 + */ } __pyx_L12:; + + /* "View.MemoryView":829 + * + * + * if have_start: # <<<<<<<<<<<<<< + * if start < 0: + * start += shape + */ goto __pyx_L11; } - /*else*/ { - /* "View.MemoryView":809 + /* "View.MemoryView":840 * start = shape * else: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ + /*else*/ { __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { - /* "View.MemoryView":810 + /* "View.MemoryView":841 * else: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< @@ -12310,24 +14309,32 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, * start = 0 */ __pyx_v_start = (__pyx_v_shape - 1); + + /* "View.MemoryView":840 + * start = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * start = shape - 1 + * else: + */ goto __pyx_L15; } - /*else*/ { - /* "View.MemoryView":812 + /* "View.MemoryView":843 * start = shape - 1 * else: * start = 0 # <<<<<<<<<<<<<< * * if have_stop: */ + /*else*/ { __pyx_v_start = 0; } __pyx_L15:; } __pyx_L11:; - /* "View.MemoryView":814 + /* "View.MemoryView":845 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< @@ -12337,7 +14344,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = (__pyx_v_have_stop != 0); if (__pyx_t_2) { - /* "View.MemoryView":815 + /* "View.MemoryView":846 * * if have_stop: * if stop < 0: # <<<<<<<<<<<<<< @@ -12347,7 +14354,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_stop < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":816 + /* "View.MemoryView":847 * if have_stop: * if stop < 0: * stop += shape # <<<<<<<<<<<<<< @@ -12356,7 +14363,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); - /* "View.MemoryView":817 + /* "View.MemoryView":848 * if stop < 0: * stop += shape * if stop < 0: # <<<<<<<<<<<<<< @@ -12366,7 +14373,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_stop < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":818 + /* "View.MemoryView":849 * stop += shape * if stop < 0: * stop = 0 # <<<<<<<<<<<<<< @@ -12374,13 +14381,27 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, * stop = shape */ __pyx_v_stop = 0; - goto __pyx_L18; + + /* "View.MemoryView":848 + * if stop < 0: + * stop += shape + * if stop < 0: # <<<<<<<<<<<<<< + * stop = 0 + * elif stop > shape: + */ } - __pyx_L18:; + + /* "View.MemoryView":846 + * + * if have_stop: + * if stop < 0: # <<<<<<<<<<<<<< + * stop += shape + * if stop < 0: + */ goto __pyx_L17; } - /* "View.MemoryView":819 + /* "View.MemoryView":850 * if stop < 0: * stop = 0 * elif stop > shape: # <<<<<<<<<<<<<< @@ -12390,7 +14411,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); if (__pyx_t_2) { - /* "View.MemoryView":820 + /* "View.MemoryView":851 * stop = 0 * elif stop > shape: * stop = shape # <<<<<<<<<<<<<< @@ -12398,49 +14419,72 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, * if negative_step: */ __pyx_v_stop = __pyx_v_shape; - goto __pyx_L17; + + /* "View.MemoryView":850 + * if stop < 0: + * stop = 0 + * elif stop > shape: # <<<<<<<<<<<<<< + * stop = shape + * else: + */ } __pyx_L17:; + + /* "View.MemoryView":845 + * start = 0 + * + * if have_stop: # <<<<<<<<<<<<<< + * if stop < 0: + * stop += shape + */ goto __pyx_L16; } - /*else*/ { - /* "View.MemoryView":822 + /* "View.MemoryView":853 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< * stop = -1 * else: */ + /*else*/ { __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { - /* "View.MemoryView":823 + /* "View.MemoryView":854 * else: * if negative_step: * stop = -1 # <<<<<<<<<<<<<< * else: * stop = shape */ - __pyx_v_stop = -1; + __pyx_v_stop = -1L; + + /* "View.MemoryView":853 + * stop = shape + * else: + * if negative_step: # <<<<<<<<<<<<<< + * stop = -1 + * else: + */ goto __pyx_L19; } - /*else*/ { - /* "View.MemoryView":825 + /* "View.MemoryView":856 * stop = -1 * else: * stop = shape # <<<<<<<<<<<<<< * * if not have_step: */ + /*else*/ { __pyx_v_stop = __pyx_v_shape; } __pyx_L19:; } __pyx_L16:; - /* "View.MemoryView":827 + /* "View.MemoryView":858 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< @@ -12450,7 +14494,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":828 + /* "View.MemoryView":859 * * if not have_step: * step = 1 # <<<<<<<<<<<<<< @@ -12458,11 +14502,17 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, * */ __pyx_v_step = 1; - goto __pyx_L20; + + /* "View.MemoryView":858 + * stop = shape + * + * if not have_step: # <<<<<<<<<<<<<< + * step = 1 + * + */ } - __pyx_L20:; - /* "View.MemoryView":832 + /* "View.MemoryView":863 * * with cython.cdivision(True): * new_shape = (stop - start) // step # <<<<<<<<<<<<<< @@ -12471,7 +14521,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); - /* "View.MemoryView":834 + /* "View.MemoryView":865 * new_shape = (stop - start) // step * * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< @@ -12481,7 +14531,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":835 + /* "View.MemoryView":866 * * if (stop - start) - step * new_shape: * new_shape += 1 # <<<<<<<<<<<<<< @@ -12489,11 +14539,17 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, * if new_shape < 0: */ __pyx_v_new_shape = (__pyx_v_new_shape + 1); - goto __pyx_L21; + + /* "View.MemoryView":865 + * new_shape = (stop - start) // step + * + * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< + * new_shape += 1 + * + */ } - __pyx_L21:; - /* "View.MemoryView":837 + /* "View.MemoryView":868 * new_shape += 1 * * if new_shape < 0: # <<<<<<<<<<<<<< @@ -12503,7 +14559,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":838 + /* "View.MemoryView":869 * * if new_shape < 0: * new_shape = 0 # <<<<<<<<<<<<<< @@ -12511,11 +14567,17 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, * */ __pyx_v_new_shape = 0; - goto __pyx_L22; + + /* "View.MemoryView":868 + * new_shape += 1 + * + * if new_shape < 0: # <<<<<<<<<<<<<< + * new_shape = 0 + * + */ } - __pyx_L22:; - /* "View.MemoryView":841 + /* "View.MemoryView":872 * * * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< @@ -12524,7 +14586,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); - /* "View.MemoryView":842 + /* "View.MemoryView":873 * * dst.strides[new_ndim] = stride * step * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< @@ -12533,7 +14595,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, */ (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; - /* "View.MemoryView":843 + /* "View.MemoryView":874 * dst.strides[new_ndim] = stride * step * dst.shape[new_ndim] = new_shape * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< @@ -12544,7 +14606,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, } __pyx_L3:; - /* "View.MemoryView":846 + /* "View.MemoryView":877 * * * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< @@ -12554,7 +14616,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":847 + /* "View.MemoryView":878 * * if suboffset_dim[0] < 0: * dst.data += start * stride # <<<<<<<<<<<<<< @@ -12562,23 +14624,31 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, * dst.suboffsets[suboffset_dim[0]] += start * stride */ __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); + + /* "View.MemoryView":877 + * + * + * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< + * dst.data += start * stride + * else: + */ goto __pyx_L23; } - /*else*/ { - /* "View.MemoryView":849 + /* "View.MemoryView":880 * dst.data += start * stride * else: * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< * * if suboffset >= 0: */ + /*else*/ { __pyx_t_3 = (__pyx_v_suboffset_dim[0]); (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); } __pyx_L23:; - /* "View.MemoryView":851 + /* "View.MemoryView":882 * dst.suboffsets[suboffset_dim[0]] += start * stride * * if suboffset >= 0: # <<<<<<<<<<<<<< @@ -12588,7 +14658,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":852 + /* "View.MemoryView":883 * * if suboffset >= 0: * if not is_slice: # <<<<<<<<<<<<<< @@ -12598,7 +14668,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":853 + /* "View.MemoryView":884 * if suboffset >= 0: * if not is_slice: * if new_ndim == 0: # <<<<<<<<<<<<<< @@ -12608,7 +14678,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":854 + /* "View.MemoryView":885 * if not is_slice: * if new_ndim == 0: * dst.data = ( dst.data)[0] + suboffset # <<<<<<<<<<<<<< @@ -12616,39 +14686,69 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, * _err_dim(IndexError, "All dimensions preceding dimension %d " */ __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); + + /* "View.MemoryView":884 + * if suboffset >= 0: + * if not is_slice: + * if new_ndim == 0: # <<<<<<<<<<<<<< + * dst.data = ( dst.data)[0] + suboffset + * else: + */ goto __pyx_L26; } - /*else*/ { - /* "View.MemoryView":856 + /* "View.MemoryView":887 * dst.data = ( dst.data)[0] + suboffset * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< * "must be indexed and not sliced", dim) * else: */ - __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_All_dimensions_preceding_dimensi, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 856; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*else*/ { + + /* "View.MemoryView":888 + * else: + * _err_dim(IndexError, "All dimensions preceding dimension %d " + * "must be indexed and not sliced", dim) # <<<<<<<<<<<<<< + * else: + * suboffset_dim[0] = new_ndim + */ + __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, ((char *)"All dimensions preceding dimension %d must be indexed and not sliced"), __pyx_v_dim); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 887, __pyx_L1_error) } __pyx_L26:; + + /* "View.MemoryView":883 + * + * if suboffset >= 0: + * if not is_slice: # <<<<<<<<<<<<<< + * if new_ndim == 0: + * dst.data = ( dst.data)[0] + suboffset + */ goto __pyx_L25; } - /*else*/ { - /* "View.MemoryView":859 + /* "View.MemoryView":890 * "must be indexed and not sliced", dim) * else: * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< * * return 0 */ + /*else*/ { (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; } __pyx_L25:; - goto __pyx_L24; + + /* "View.MemoryView":882 + * dst.suboffsets[suboffset_dim[0]] += start * stride + * + * if suboffset >= 0: # <<<<<<<<<<<<<< + * if not is_slice: + * if new_ndim == 0: + */ } - __pyx_L24:; - /* "View.MemoryView":861 + /* "View.MemoryView":892 * suboffset_dim[0] = new_ndim * * return 0 # <<<<<<<<<<<<<< @@ -12658,7 +14758,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_r = 0; goto __pyx_L0; - /* "View.MemoryView":764 + /* "View.MemoryView":795 * * @cname('__pyx_memoryview_slice_memviewslice') * cdef int slice_memviewslice( # <<<<<<<<<<<<<< @@ -12670,11 +14770,11 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, __pyx_L1_error:; { #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); + __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; @@ -12682,7 +14782,7 @@ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, return __pyx_r; } -/* "View.MemoryView":867 +/* "View.MemoryView":898 * * @cname('__pyx_pybuffer_index') * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< @@ -12702,21 +14802,18 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("pybuffer_index", 0); - /* "View.MemoryView":869 + /* "View.MemoryView":900 * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< * cdef Py_ssize_t itemsize = view.itemsize * cdef char *resultp */ - __pyx_v_suboffset = -1; + __pyx_v_suboffset = -1L; - /* "View.MemoryView":870 + /* "View.MemoryView":901 * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< @@ -12726,7 +14823,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_1 = __pyx_v_view->itemsize; __pyx_v_itemsize = __pyx_t_1; - /* "View.MemoryView":873 + /* "View.MemoryView":904 * cdef char *resultp * * if view.ndim == 0: # <<<<<<<<<<<<<< @@ -12736,7 +14833,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":874 + /* "View.MemoryView":905 * * if view.ndim == 0: * shape = view.len / itemsize # <<<<<<<<<<<<<< @@ -12744,28 +14841,16 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P * else: */ if (unlikely(__pyx_v_itemsize == 0)) { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); - #endif PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); - #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); - #endif - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 874; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 905, __pyx_L1_error) } - else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { - #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); - #endif + else if (sizeof(Py_ssize_t) == sizeof(long) && (!(((Py_ssize_t)-1) > 0)) && unlikely(__pyx_v_itemsize == (Py_ssize_t)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); - #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); - #endif - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 874; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 905, __pyx_L1_error) } __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); - /* "View.MemoryView":875 + /* "View.MemoryView":906 * if view.ndim == 0: * shape = view.len / itemsize * stride = itemsize # <<<<<<<<<<<<<< @@ -12773,20 +14858,28 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P * shape = view.shape[dim] */ __pyx_v_stride = __pyx_v_itemsize; + + /* "View.MemoryView":904 + * cdef char *resultp + * + * if view.ndim == 0: # <<<<<<<<<<<<<< + * shape = view.len / itemsize + * stride = itemsize + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":877 + /* "View.MemoryView":908 * stride = itemsize * else: * shape = view.shape[dim] # <<<<<<<<<<<<<< * stride = view.strides[dim] * if view.suboffsets != NULL: */ + /*else*/ { __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); - /* "View.MemoryView":878 + /* "View.MemoryView":909 * else: * shape = view.shape[dim] * stride = view.strides[dim] # <<<<<<<<<<<<<< @@ -12795,7 +14888,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); - /* "View.MemoryView":879 + /* "View.MemoryView":910 * shape = view.shape[dim] * stride = view.strides[dim] * if view.suboffsets != NULL: # <<<<<<<<<<<<<< @@ -12805,7 +14898,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); if (__pyx_t_2) { - /* "View.MemoryView":880 + /* "View.MemoryView":911 * stride = view.strides[dim] * if view.suboffsets != NULL: * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< @@ -12813,13 +14906,19 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P * if index < 0: */ __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); - goto __pyx_L4; + + /* "View.MemoryView":910 + * shape = view.shape[dim] + * stride = view.strides[dim] + * if view.suboffsets != NULL: # <<<<<<<<<<<<<< + * suboffset = view.suboffsets[dim] + * + */ } - __pyx_L4:; } __pyx_L3:; - /* "View.MemoryView":882 + /* "View.MemoryView":913 * suboffset = view.suboffsets[dim] * * if index < 0: # <<<<<<<<<<<<<< @@ -12829,7 +14928,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_2 = ((__pyx_v_index < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":883 + /* "View.MemoryView":914 * * if index < 0: * index += view.shape[dim] # <<<<<<<<<<<<<< @@ -12838,7 +14937,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); - /* "View.MemoryView":884 + /* "View.MemoryView":915 * if index < 0: * index += view.shape[dim] * if index < 0: # <<<<<<<<<<<<<< @@ -12848,35 +14947,49 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_2 = ((__pyx_v_index < 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":885 + /* "View.MemoryView":916 * index += view.shape[dim] * if index < 0: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< * * if index >= shape: */ - __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 916, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 916, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 916, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 916, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 885; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 916, __pyx_L1_error) + + /* "View.MemoryView":915 + * if index < 0: + * index += view.shape[dim] + * if index < 0: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ } - goto __pyx_L5; + + /* "View.MemoryView":913 + * suboffset = view.suboffsets[dim] + * + * if index < 0: # <<<<<<<<<<<<<< + * index += view.shape[dim] + * if index < 0: + */ } - __pyx_L5:; - /* "View.MemoryView":887 + /* "View.MemoryView":918 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * if index >= shape: # <<<<<<<<<<<<<< @@ -12886,32 +14999,40 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); if (__pyx_t_2) { - /* "View.MemoryView":888 + /* "View.MemoryView":919 * * if index >= shape: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< * * resultp = bufp + index * stride */ - __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 919, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 919, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 919, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 919, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 888; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 919, __pyx_L1_error) + + /* "View.MemoryView":918 + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + * if index >= shape: # <<<<<<<<<<<<<< + * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) + * + */ } - /* "View.MemoryView":890 + /* "View.MemoryView":921 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * resultp = bufp + index * stride # <<<<<<<<<<<<<< @@ -12920,7 +15041,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P */ __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); - /* "View.MemoryView":891 + /* "View.MemoryView":922 * * resultp = bufp + index * stride * if suboffset >= 0: # <<<<<<<<<<<<<< @@ -12930,7 +15051,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":892 + /* "View.MemoryView":923 * resultp = bufp + index * stride * if suboffset >= 0: * resultp = ( resultp)[0] + suboffset # <<<<<<<<<<<<<< @@ -12938,11 +15059,17 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P * return resultp */ __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); - goto __pyx_L8; + + /* "View.MemoryView":922 + * + * resultp = bufp + index * stride + * if suboffset >= 0: # <<<<<<<<<<<<<< + * resultp = ( resultp)[0] + suboffset + * + */ } - __pyx_L8:; - /* "View.MemoryView":894 + /* "View.MemoryView":925 * resultp = ( resultp)[0] + suboffset * * return resultp # <<<<<<<<<<<<<< @@ -12952,7 +15079,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P __pyx_r = __pyx_v_resultp; goto __pyx_L0; - /* "View.MemoryView":867 + /* "View.MemoryView":898 * * @cname('__pyx_pybuffer_index') * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< @@ -12971,7 +15098,7 @@ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, P return __pyx_r; } -/* "View.MemoryView":900 +/* "View.MemoryView":931 * * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< @@ -12994,11 +15121,8 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { int __pyx_t_6; int __pyx_t_7; int __pyx_t_8; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - /* "View.MemoryView":901 + /* "View.MemoryView":932 * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< @@ -13008,7 +15132,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; __pyx_v_ndim = __pyx_t_1; - /* "View.MemoryView":903 + /* "View.MemoryView":934 * cdef int ndim = memslice.memview.view.ndim * * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< @@ -13018,7 +15142,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { __pyx_t_2 = __pyx_v_memslice->shape; __pyx_v_shape = __pyx_t_2; - /* "View.MemoryView":904 + /* "View.MemoryView":935 * * cdef Py_ssize_t *shape = memslice.shape * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< @@ -13028,7 +15152,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { __pyx_t_2 = __pyx_v_memslice->strides; __pyx_v_strides = __pyx_t_2; - /* "View.MemoryView":908 + /* "View.MemoryView":939 * * cdef int i, j * for i in range(ndim / 2): # <<<<<<<<<<<<<< @@ -13039,7 +15163,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) { __pyx_v_i = __pyx_t_1; - /* "View.MemoryView":909 + /* "View.MemoryView":940 * cdef int i, j * for i in range(ndim / 2): * j = ndim - 1 - i # <<<<<<<<<<<<<< @@ -13048,7 +15172,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { */ __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); - /* "View.MemoryView":910 + /* "View.MemoryView":941 * for i in range(ndim / 2): * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< @@ -13060,7 +15184,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { (__pyx_v_strides[__pyx_v_i]) = __pyx_t_4; (__pyx_v_strides[__pyx_v_j]) = __pyx_t_5; - /* "View.MemoryView":911 + /* "View.MemoryView":942 * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< @@ -13072,7 +15196,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { (__pyx_v_shape[__pyx_v_i]) = __pyx_t_5; (__pyx_v_shape[__pyx_v_j]) = __pyx_t_4; - /* "View.MemoryView":913 + /* "View.MemoryView":944 * shape[i], shape[j] = shape[j], shape[i] * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< @@ -13090,20 +15214,26 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { __pyx_L6_bool_binop_done:; if (__pyx_t_6) { - /* "View.MemoryView":914 + /* "View.MemoryView":945 * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< * * return 1 */ - __pyx_t_8 = __pyx_memoryview_err(__pyx_builtin_ValueError, __pyx_k_Cannot_transpose_memoryview_with); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 914; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L5; - } - __pyx_L5:; - } + __pyx_t_8 = __pyx_memoryview_err(__pyx_builtin_ValueError, ((char *)"Cannot transpose memoryview with indirect dimensions")); if (unlikely(__pyx_t_8 == ((int)-1))) __PYX_ERR(1, 945, __pyx_L1_error) - /* "View.MemoryView":916 + /* "View.MemoryView":944 + * shape[i], shape[j] = shape[j], shape[i] + * + * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< + * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") + * + */ + } + } + + /* "View.MemoryView":947 * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * * return 1 # <<<<<<<<<<<<<< @@ -13113,7 +15243,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { __pyx_r = 1; goto __pyx_L0; - /* "View.MemoryView":900 + /* "View.MemoryView":931 * * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< @@ -13125,11 +15255,11 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { __pyx_L1_error:; { #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); + __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = 0; @@ -13137,7 +15267,7 @@ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { return __pyx_r; } -/* "View.MemoryView":933 +/* "View.MemoryView":964 * cdef int (*to_dtype_func)(char *, object) except 0 * * def __dealloc__(self): # <<<<<<<<<<<<<< @@ -13150,17 +15280,17 @@ static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); - __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } -static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { +static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__", 0); - /* "View.MemoryView":934 + /* "View.MemoryView":965 * * def __dealloc__(self): * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< @@ -13169,7 +15299,7 @@ static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(stru */ __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); - /* "View.MemoryView":933 + /* "View.MemoryView":964 * cdef int (*to_dtype_func)(char *, object) except 0 * * def __dealloc__(self): # <<<<<<<<<<<<<< @@ -13181,7 +15311,7 @@ static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(stru __Pyx_RefNannyFinishContext(); } -/* "View.MemoryView":936 +/* "View.MemoryView":967 * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< @@ -13194,12 +15324,9 @@ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memor __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("convert_item_to_object", 0); - /* "View.MemoryView":937 + /* "View.MemoryView":968 * * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: # <<<<<<<<<<<<<< @@ -13209,7 +15336,7 @@ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memor __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":938 + /* "View.MemoryView":969 * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: * return self.to_object_func(itemp) # <<<<<<<<<<<<<< @@ -13217,30 +15344,38 @@ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memor * return memoryview.convert_item_to_object(self, itemp) */ __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 938; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 969, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; + + /* "View.MemoryView":968 + * + * cdef convert_item_to_object(self, char *itemp): + * if self.to_object_func != NULL: # <<<<<<<<<<<<<< + * return self.to_object_func(itemp) + * else: + */ } - /*else*/ { - /* "View.MemoryView":940 + /* "View.MemoryView":971 * return self.to_object_func(itemp) * else: * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< * * cdef assign_item_from_object(self, char *itemp, object value): */ + /*else*/ { __Pyx_XDECREF(__pyx_r); - __pyx_t_2 = __pyx_memoryview_convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 940; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_memoryview_convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 971, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; } - /* "View.MemoryView":936 + /* "View.MemoryView":967 * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< @@ -13259,7 +15394,7 @@ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memor return __pyx_r; } -/* "View.MemoryView":942 +/* "View.MemoryView":973 * return memoryview.convert_item_to_object(self, itemp) * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< @@ -13273,12 +15408,9 @@ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memo int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("assign_item_from_object", 0); - /* "View.MemoryView":943 + /* "View.MemoryView":974 * * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< @@ -13288,32 +15420,40 @@ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memo __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":944 + /* "View.MemoryView":975 * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< * else: * memoryview.assign_item_from_object(self, itemp, value) */ - __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 944; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == ((int)0))) __PYX_ERR(1, 975, __pyx_L1_error) + + /* "View.MemoryView":974 + * + * cdef assign_item_from_object(self, char *itemp, object value): + * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< + * self.to_dtype_func(itemp, value) + * else: + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":946 + /* "View.MemoryView":977 * self.to_dtype_func(itemp, value) * else: * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< * - * property base: + * @property */ - __pyx_t_3 = __pyx_memoryview_assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 946; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*else*/ { + __pyx_t_3 = __pyx_memoryview_assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 977, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } __pyx_L3:; - /* "View.MemoryView":942 + /* "View.MemoryView":973 * return memoryview.convert_item_to_object(self, itemp) * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< @@ -13334,36 +15474,36 @@ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memo return __pyx_r; } -/* "View.MemoryView":950 - * property base: - * @cname('__pyx_memoryviewslice__get__base') - * def __get__(self): # <<<<<<<<<<<<<< - * return self.from_object +/* "View.MemoryView":980 + * + * @property + * def base(self): # <<<<<<<<<<<<<< + * return self.from_object * */ /* Python wrapper */ -static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ -static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self) { +static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self); /*proto*/ +static PyObject *__pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); - __pyx_r = __pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + __pyx_r = __pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } -static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { +static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__", 0); - /* "View.MemoryView":951 - * @cname('__pyx_memoryviewslice__get__base') - * def __get__(self): - * return self.from_object # <<<<<<<<<<<<<< + /* "View.MemoryView":981 + * @property + * def base(self): + * return self.from_object # <<<<<<<<<<<<<< * * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") */ @@ -13372,11 +15512,11 @@ static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_ __pyx_r = __pyx_v_self->from_object; goto __pyx_L0; - /* "View.MemoryView":950 - * property base: - * @cname('__pyx_memoryviewslice__get__base') - * def __get__(self): # <<<<<<<<<<<<<< - * return self.from_object + /* "View.MemoryView":980 + * + * @property + * def base(self): # <<<<<<<<<<<<<< + * return self.from_object * */ @@ -13387,7 +15527,114 @@ static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_ return __pyx_r; } -/* "View.MemoryView":957 +/* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ +static PyObject *__pyx_pw___pyx_memoryviewslice_1__reduce_cython__(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__reduce_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_memoryviewslice___reduce_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_memoryviewslice___reduce_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __Pyx_RefNannySetupContext("__reduce_cython__", 0); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__30, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(1, 2, __pyx_L1_error) + + /* "(tree fragment)":1 + * def __reduce_cython__(self): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__reduce_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + +/* Python wrapper */ +static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state); /*proto*/ +static PyObject *__pyx_pw___pyx_memoryviewslice_3__setstate_cython__(PyObject *__pyx_v_self, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__setstate_cython__ (wrapper)", 0); + __pyx_r = __pyx_pf___pyx_memoryviewslice_2__setstate_cython__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self), ((PyObject *)__pyx_v___pyx_state)); + + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +static PyObject *__pyx_pf___pyx_memoryviewslice_2__setstate_cython__(CYTHON_UNUSED struct __pyx_memoryviewslice_obj *__pyx_v_self, CYTHON_UNUSED PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + __Pyx_RefNannySetupContext("__setstate_cython__", 0); + + /* "(tree fragment)":4 + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + */ + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__31, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_Raise(__pyx_t_1, 0, 0, 0); + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + __PYX_ERR(1, 4, __pyx_L1_error) + + /* "(tree fragment)":3 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): # <<<<<<<<<<<<<< + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_AddTraceback("View.MemoryView._memoryviewslice.__setstate_cython__", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "View.MemoryView":987 * * @cname('__pyx_memoryview_fromslice') * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< @@ -13397,7 +15644,8 @@ static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; - int __pyx_v_i; + Py_ssize_t __pyx_v_suboffset; + PyObject *__pyx_v_length = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; @@ -13405,16 +15653,14 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl PyObject *__pyx_t_3 = NULL; __Pyx_TypeInfo *__pyx_t_4; Py_buffer __pyx_t_5; - Py_ssize_t __pyx_t_6; - int __pyx_t_7; - int __pyx_t_8; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; + Py_ssize_t *__pyx_t_6; + Py_ssize_t *__pyx_t_7; + Py_ssize_t *__pyx_t_8; + Py_ssize_t __pyx_t_9; __Pyx_RefNannySetupContext("memoryview_fromslice", 0); - /* "View.MemoryView":966 - * cdef int i + /* "View.MemoryView":995 + * cdef _memoryviewslice result * * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< * return None @@ -13423,7 +15669,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); if (__pyx_t_1) { - /* "View.MemoryView":967 + /* "View.MemoryView":996 * * if memviewslice.memview == Py_None: * return None # <<<<<<<<<<<<<< @@ -13434,35 +15680,43 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; + + /* "View.MemoryView":995 + * cdef _memoryviewslice result + * + * if memviewslice.memview == Py_None: # <<<<<<<<<<<<<< + * return None + * + */ } - /* "View.MemoryView":972 + /* "View.MemoryView":1001 * * * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< * * result.from_slice = memviewslice */ - __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1001, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1001, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(Py_None); - PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); __Pyx_GIVEREF(Py_None); + PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); __Pyx_INCREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); - PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); __Pyx_GIVEREF(__pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryviewslice_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 972; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)__pyx_memoryviewslice_type), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1001, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); __pyx_t_2 = 0; - /* "View.MemoryView":974 + /* "View.MemoryView":1003 * result = _memoryviewslice(None, 0, dtype_is_object) * * result.from_slice = memviewslice # <<<<<<<<<<<<<< @@ -13471,7 +15725,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->from_slice = __pyx_v_memviewslice; - /* "View.MemoryView":975 + /* "View.MemoryView":1004 * * result.from_slice = memviewslice * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< @@ -13480,14 +15734,14 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); - /* "View.MemoryView":977 + /* "View.MemoryView":1006 * __PYX_INC_MEMVIEW(&memviewslice, 1) * * result.from_object = ( memviewslice.memview).base # <<<<<<<<<<<<<< * result.typeinfo = memviewslice.memview.typeinfo * */ - __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 977; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1006, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __Pyx_GOTREF(__pyx_v_result->from_object); @@ -13495,7 +15749,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_v_result->from_object = __pyx_t_2; __pyx_t_2 = 0; - /* "View.MemoryView":978 + /* "View.MemoryView":1007 * * result.from_object = ( memviewslice.memview).base * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< @@ -13505,7 +15759,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; - /* "View.MemoryView":980 + /* "View.MemoryView":1009 * result.typeinfo = memviewslice.memview.typeinfo * * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< @@ -13515,7 +15769,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_t_5 = __pyx_v_memviewslice.memview->view; __pyx_v_result->__pyx_base.view = __pyx_t_5; - /* "View.MemoryView":981 + /* "View.MemoryView":1010 * * result.view = memviewslice.memview.view * result.view.buf = memviewslice.data # <<<<<<<<<<<<<< @@ -13524,7 +15778,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); - /* "View.MemoryView":982 + /* "View.MemoryView":1011 * result.view = memviewslice.memview.view * result.view.buf = memviewslice.data * result.view.ndim = ndim # <<<<<<<<<<<<<< @@ -13533,7 +15787,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; - /* "View.MemoryView":983 + /* "View.MemoryView":1012 * result.view.buf = memviewslice.data * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< @@ -13542,7 +15796,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; - /* "View.MemoryView":984 + /* "View.MemoryView":1013 * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< @@ -13551,7 +15805,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ Py_INCREF(Py_None); - /* "View.MemoryView":986 + /* "View.MemoryView":1015 * Py_INCREF(Py_None) * * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< @@ -13560,66 +15814,128 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; - /* "View.MemoryView":988 + /* "View.MemoryView":1017 * result.flags = PyBUF_RECORDS * * result.view.shape = result.from_slice.shape # <<<<<<<<<<<<<< * result.view.strides = result.from_slice.strides - * result.view.suboffsets = result.from_slice.suboffsets + * */ __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); - /* "View.MemoryView":989 + /* "View.MemoryView":1018 * * result.view.shape = result.from_slice.shape * result.view.strides = result.from_slice.strides # <<<<<<<<<<<<<< - * result.view.suboffsets = result.from_slice.suboffsets + * * */ __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); - /* "View.MemoryView":990 - * result.view.shape = result.from_slice.shape - * result.view.strides = result.from_slice.strides - * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< + /* "View.MemoryView":1021 + * + * + * result.view.suboffsets = NULL # <<<<<<<<<<<<<< + * for suboffset in result.from_slice.suboffsets[:ndim]: + * if suboffset >= 0: + */ + __pyx_v_result->__pyx_base.view.suboffsets = NULL; + + /* "View.MemoryView":1022 + * + * result.view.suboffsets = NULL + * for suboffset in result.from_slice.suboffsets[:ndim]: # <<<<<<<<<<<<<< + * if suboffset >= 0: + * result.view.suboffsets = result.from_slice.suboffsets + */ + __pyx_t_7 = (__pyx_v_result->from_slice.suboffsets + __pyx_v_ndim); + for (__pyx_t_8 = __pyx_v_result->from_slice.suboffsets; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { + __pyx_t_6 = __pyx_t_8; + __pyx_v_suboffset = (__pyx_t_6[0]); + + /* "View.MemoryView":1023 + * result.view.suboffsets = NULL + * for suboffset in result.from_slice.suboffsets[:ndim]: + * if suboffset >= 0: # <<<<<<<<<<<<<< + * result.view.suboffsets = result.from_slice.suboffsets + * break + */ + __pyx_t_1 = ((__pyx_v_suboffset >= 0) != 0); + if (__pyx_t_1) { + + /* "View.MemoryView":1024 + * for suboffset in result.from_slice.suboffsets[:ndim]: + * if suboffset >= 0: + * result.view.suboffsets = result.from_slice.suboffsets # <<<<<<<<<<<<<< + * break + * + */ + __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); + + /* "View.MemoryView":1025 + * if suboffset >= 0: + * result.view.suboffsets = result.from_slice.suboffsets + * break # <<<<<<<<<<<<<< * * result.view.len = result.view.itemsize */ - __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); + goto __pyx_L5_break; + + /* "View.MemoryView":1023 + * result.view.suboffsets = NULL + * for suboffset in result.from_slice.suboffsets[:ndim]: + * if suboffset >= 0: # <<<<<<<<<<<<<< + * result.view.suboffsets = result.from_slice.suboffsets + * break + */ + } + } + __pyx_L5_break:; - /* "View.MemoryView":992 - * result.view.suboffsets = result.from_slice.suboffsets + /* "View.MemoryView":1027 + * break * * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< - * for i in range(ndim): - * result.view.len *= result.view.shape[i] + * for length in result.view.shape[:ndim]: + * result.view.len *= length */ - __pyx_t_6 = __pyx_v_result->__pyx_base.view.itemsize; - __pyx_v_result->__pyx_base.view.len = __pyx_t_6; + __pyx_t_9 = __pyx_v_result->__pyx_base.view.itemsize; + __pyx_v_result->__pyx_base.view.len = __pyx_t_9; - /* "View.MemoryView":993 + /* "View.MemoryView":1028 * * result.view.len = result.view.itemsize - * for i in range(ndim): # <<<<<<<<<<<<<< - * result.view.len *= result.view.shape[i] + * for length in result.view.shape[:ndim]: # <<<<<<<<<<<<<< + * result.view.len *= length * */ - __pyx_t_7 = __pyx_v_ndim; - for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) { - __pyx_v_i = __pyx_t_8; + __pyx_t_7 = (__pyx_v_result->__pyx_base.view.shape + __pyx_v_ndim); + for (__pyx_t_8 = __pyx_v_result->__pyx_base.view.shape; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { + __pyx_t_6 = __pyx_t_8; + __pyx_t_2 = PyInt_FromSsize_t((__pyx_t_6[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1028, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); + __pyx_t_2 = 0; - /* "View.MemoryView":994 + /* "View.MemoryView":1029 * result.view.len = result.view.itemsize - * for i in range(ndim): - * result.view.len *= result.view.shape[i] # <<<<<<<<<<<<<< + * for length in result.view.shape[:ndim]: + * result.view.len *= length # <<<<<<<<<<<<<< * * result.to_object_func = to_object_func */ - __pyx_v_result->__pyx_base.view.len = (__pyx_v_result->__pyx_base.view.len * (__pyx_v_result->__pyx_base.view.shape[__pyx_v_i])); + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_result->__pyx_base.view.len); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1029, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_t_2, __pyx_v_length); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1029, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(1, 1029, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __pyx_v_result->__pyx_base.view.len = __pyx_t_9; } - /* "View.MemoryView":996 - * result.view.len *= result.view.shape[i] + /* "View.MemoryView":1031 + * result.view.len *= length * * result.to_object_func = to_object_func # <<<<<<<<<<<<<< * result.to_dtype_func = to_dtype_func @@ -13627,7 +15943,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->to_object_func = __pyx_v_to_object_func; - /* "View.MemoryView":997 + /* "View.MemoryView":1032 * * result.to_object_func = to_object_func * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< @@ -13636,7 +15952,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl */ __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; - /* "View.MemoryView":999 + /* "View.MemoryView":1034 * result.to_dtype_func = to_dtype_func * * return result # <<<<<<<<<<<<<< @@ -13648,7 +15964,7 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; - /* "View.MemoryView":957 + /* "View.MemoryView":987 * * @cname('__pyx_memoryview_fromslice') * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< @@ -13664,12 +15980,13 @@ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewsl __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_result); + __Pyx_XDECREF(__pyx_v_length); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } -/* "View.MemoryView":1002 +/* "View.MemoryView":1037 * * @cname('__pyx_memoryview_get_slice_from_memoryview') * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< @@ -13684,36 +16001,33 @@ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __p int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_slice_from_memview", 0); - /* "View.MemoryView":1005 + /* "View.MemoryView":1040 * __Pyx_memviewslice *mslice): * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * obj = memview * return &obj.from_slice */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":1006 + /* "View.MemoryView":1041 * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): * obj = memview # <<<<<<<<<<<<<< * return &obj.from_slice * else: */ - if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1006; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) __PYX_ERR(1, 1041, __pyx_L1_error) __pyx_t_3 = ((PyObject *)__pyx_v_memview); __Pyx_INCREF(__pyx_t_3); __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); __pyx_t_3 = 0; - /* "View.MemoryView":1007 + /* "View.MemoryView":1042 * if isinstance(memview, _memoryviewslice): * obj = memview * return &obj.from_slice # <<<<<<<<<<<<<< @@ -13722,19 +16036,27 @@ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __p */ __pyx_r = (&__pyx_v_obj->from_slice); goto __pyx_L0; + + /* "View.MemoryView":1040 + * __Pyx_memviewslice *mslice): + * cdef _memoryviewslice obj + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * obj = memview + * return &obj.from_slice + */ } - /*else*/ { - /* "View.MemoryView":1009 + /* "View.MemoryView":1044 * return &obj.from_slice * else: * slice_copy(memview, mslice) # <<<<<<<<<<<<<< * return mslice * */ + /*else*/ { __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); - /* "View.MemoryView":1010 + /* "View.MemoryView":1045 * else: * slice_copy(memview, mslice) * return mslice # <<<<<<<<<<<<<< @@ -13745,7 +16067,7 @@ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __p goto __pyx_L0; } - /* "View.MemoryView":1002 + /* "View.MemoryView":1037 * * @cname('__pyx_memoryview_get_slice_from_memoryview') * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< @@ -13756,7 +16078,7 @@ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __p /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); - __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); + __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_obj); @@ -13764,7 +16086,7 @@ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __p return __pyx_r; } -/* "View.MemoryView":1013 +/* "View.MemoryView":1048 * * @cname('__pyx_memoryview_slice_copy') * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< @@ -13781,10 +16103,10 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem Py_ssize_t *__pyx_t_1; int __pyx_t_2; int __pyx_t_3; - int __pyx_t_4; + Py_ssize_t __pyx_t_4; __Pyx_RefNannySetupContext("slice_copy", 0); - /* "View.MemoryView":1017 + /* "View.MemoryView":1052 * cdef (Py_ssize_t*) shape, strides, suboffsets * * shape = memview.view.shape # <<<<<<<<<<<<<< @@ -13794,7 +16116,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem __pyx_t_1 = __pyx_v_memview->view.shape; __pyx_v_shape = __pyx_t_1; - /* "View.MemoryView":1018 + /* "View.MemoryView":1053 * * shape = memview.view.shape * strides = memview.view.strides # <<<<<<<<<<<<<< @@ -13804,7 +16126,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem __pyx_t_1 = __pyx_v_memview->view.strides; __pyx_v_strides = __pyx_t_1; - /* "View.MemoryView":1019 + /* "View.MemoryView":1054 * shape = memview.view.shape * strides = memview.view.strides * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< @@ -13814,7 +16136,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem __pyx_t_1 = __pyx_v_memview->view.suboffsets; __pyx_v_suboffsets = __pyx_t_1; - /* "View.MemoryView":1021 + /* "View.MemoryView":1056 * suboffsets = memview.view.suboffsets * * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< @@ -13823,7 +16145,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem */ __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); - /* "View.MemoryView":1022 + /* "View.MemoryView":1057 * * dst.memview = <__pyx_memoryview *> memview * dst.data = memview.view.buf # <<<<<<<<<<<<<< @@ -13832,7 +16154,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem */ __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); - /* "View.MemoryView":1024 + /* "View.MemoryView":1059 * dst.data = memview.view.buf * * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< @@ -13843,59 +16165,40 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_dim = __pyx_t_3; - /* "View.MemoryView":1025 + /* "View.MemoryView":1060 * * for dim in range(memview.view.ndim): * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< * dst.strides[dim] = strides[dim] - * if suboffsets == NULL: + * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 */ (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); - /* "View.MemoryView":1026 + /* "View.MemoryView":1061 * for dim in range(memview.view.ndim): * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< - * if suboffsets == NULL: - * dst.suboffsets[dim] = -1 + * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 + * */ (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); - /* "View.MemoryView":1027 + /* "View.MemoryView":1062 * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] - * if suboffsets == NULL: # <<<<<<<<<<<<<< - * dst.suboffsets[dim] = -1 - * else: - */ - __pyx_t_4 = ((__pyx_v_suboffsets == NULL) != 0); - if (__pyx_t_4) { - - /* "View.MemoryView":1028 - * dst.strides[dim] = strides[dim] - * if suboffsets == NULL: - * dst.suboffsets[dim] = -1 # <<<<<<<<<<<<<< - * else: - * dst.suboffsets[dim] = suboffsets[dim] - */ - (__pyx_v_dst->suboffsets[__pyx_v_dim]) = -1; - goto __pyx_L5; - } - /*else*/ { - - /* "View.MemoryView":1030 - * dst.suboffsets[dim] = -1 - * else: - * dst.suboffsets[dim] = suboffsets[dim] # <<<<<<<<<<<<<< + * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_object') */ - (__pyx_v_dst->suboffsets[__pyx_v_dim]) = (__pyx_v_suboffsets[__pyx_v_dim]); + if ((__pyx_v_suboffsets != 0)) { + __pyx_t_4 = (__pyx_v_suboffsets[__pyx_v_dim]); + } else { + __pyx_t_4 = -1L; } - __pyx_L5:; + (__pyx_v_dst->suboffsets[__pyx_v_dim]) = __pyx_t_4; } - /* "View.MemoryView":1013 + /* "View.MemoryView":1048 * * @cname('__pyx_memoryview_slice_copy') * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< @@ -13907,7 +16210,7 @@ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_mem __Pyx_RefNannyFinishContext(); } -/* "View.MemoryView":1033 +/* "View.MemoryView":1065 * * @cname('__pyx_memoryview_copy_object') * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< @@ -13920,12 +16223,9 @@ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_copy", 0); - /* "View.MemoryView":1036 + /* "View.MemoryView":1068 * "Create a new memoryview object" * cdef __Pyx_memviewslice memviewslice * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< @@ -13934,7 +16234,7 @@ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx */ __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); - /* "View.MemoryView":1037 + /* "View.MemoryView":1069 * cdef __Pyx_memviewslice memviewslice * slice_copy(memview, &memviewslice) * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< @@ -13942,13 +16242,13 @@ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx * @cname('__pyx_memoryview_copy_object_from_slice') */ __Pyx_XDECREF(__pyx_r); - __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1037; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1069, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; - /* "View.MemoryView":1033 + /* "View.MemoryView":1065 * * @cname('__pyx_memoryview_copy_object') * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< @@ -13967,7 +16267,7 @@ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx return __pyx_r; } -/* "View.MemoryView":1040 +/* "View.MemoryView":1072 * * @cname('__pyx_memoryview_copy_object_from_slice') * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< @@ -13985,23 +16285,20 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview PyObject *(*__pyx_t_3)(char *); int (*__pyx_t_4)(char *, PyObject *); PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); - /* "View.MemoryView":1047 + /* "View.MemoryView":1079 * cdef int (*to_dtype_func)(char *, object) except 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * to_object_func = (<_memoryviewslice> memview).to_object_func * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func */ - __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); + __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { - /* "View.MemoryView":1048 + /* "View.MemoryView":1080 * * if isinstance(memview, _memoryviewslice): * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< @@ -14011,7 +16308,7 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; __pyx_v_to_object_func = __pyx_t_3; - /* "View.MemoryView":1049 + /* "View.MemoryView":1081 * if isinstance(memview, _memoryviewslice): * to_object_func = (<_memoryviewslice> memview).to_object_func * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< @@ -14020,20 +16317,28 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview */ __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; __pyx_v_to_dtype_func = __pyx_t_4; + + /* "View.MemoryView":1079 + * cdef int (*to_dtype_func)(char *, object) except 0 + * + * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< + * to_object_func = (<_memoryviewslice> memview).to_object_func + * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":1051 + /* "View.MemoryView":1083 * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func * else: * to_object_func = NULL # <<<<<<<<<<<<<< * to_dtype_func = NULL * */ + /*else*/ { __pyx_v_to_object_func = NULL; - /* "View.MemoryView":1052 + /* "View.MemoryView":1084 * else: * to_object_func = NULL * to_dtype_func = NULL # <<<<<<<<<<<<<< @@ -14044,7 +16349,7 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview } __pyx_L3:; - /* "View.MemoryView":1054 + /* "View.MemoryView":1086 * to_dtype_func = NULL * * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< @@ -14053,20 +16358,20 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview */ __Pyx_XDECREF(__pyx_r); - /* "View.MemoryView":1056 + /* "View.MemoryView":1088 * return memoryview_fromslice(memviewslice[0], memview.view.ndim, * to_object_func, to_dtype_func, * memview.dtype_is_object) # <<<<<<<<<<<<<< * * */ - __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1054; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 1086, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; - /* "View.MemoryView":1040 + /* "View.MemoryView":1072 * * @cname('__pyx_memoryview_copy_object_from_slice') * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< @@ -14085,7 +16390,7 @@ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview return __pyx_r; } -/* "View.MemoryView":1062 +/* "View.MemoryView":1094 * * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< @@ -14097,7 +16402,7 @@ static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { Py_ssize_t __pyx_r; int __pyx_t_1; - /* "View.MemoryView":1063 + /* "View.MemoryView":1095 * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: # <<<<<<<<<<<<<< @@ -14107,7 +16412,7 @@ static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { __pyx_t_1 = ((__pyx_v_arg < 0) != 0); if (__pyx_t_1) { - /* "View.MemoryView":1064 + /* "View.MemoryView":1096 * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: * return -arg # <<<<<<<<<<<<<< @@ -14116,21 +16421,29 @@ static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { */ __pyx_r = (-__pyx_v_arg); goto __pyx_L0; + + /* "View.MemoryView":1095 + * + * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: + * if arg < 0: # <<<<<<<<<<<<<< + * return -arg + * else: + */ } - /*else*/ { - /* "View.MemoryView":1066 + /* "View.MemoryView":1098 * return -arg * else: * return arg # <<<<<<<<<<<<<< * * @cname('__pyx_get_best_slice_order') */ + /*else*/ { __pyx_r = __pyx_v_arg; goto __pyx_L0; } - /* "View.MemoryView":1062 + /* "View.MemoryView":1094 * * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< @@ -14143,7 +16456,7 @@ static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { return __pyx_r; } -/* "View.MemoryView":1069 +/* "View.MemoryView":1101 * * @cname('__pyx_get_best_slice_order') * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< @@ -14160,7 +16473,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ int __pyx_t_2; int __pyx_t_3; - /* "View.MemoryView":1074 + /* "View.MemoryView":1106 * """ * cdef int i * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< @@ -14169,7 +16482,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ */ __pyx_v_c_stride = 0; - /* "View.MemoryView":1075 + /* "View.MemoryView":1107 * cdef int i * cdef Py_ssize_t c_stride = 0 * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< @@ -14178,17 +16491,17 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ */ __pyx_v_f_stride = 0; - /* "View.MemoryView":1077 + /* "View.MemoryView":1109 * cdef Py_ssize_t f_stride = 0 * * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] */ - for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1L; __pyx_t_1-=1) { __pyx_v_i = __pyx_t_1; - /* "View.MemoryView":1078 + /* "View.MemoryView":1110 * * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< @@ -14198,7 +16511,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1079 + /* "View.MemoryView":1111 * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< @@ -14207,7 +16520,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ */ __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); - /* "View.MemoryView":1080 + /* "View.MemoryView":1112 * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] * break # <<<<<<<<<<<<<< @@ -14215,11 +16528,19 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ * for i in range(ndim): */ goto __pyx_L4_break; + + /* "View.MemoryView":1110 + * + * for i in range(ndim - 1, -1, -1): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * c_stride = mslice.strides[i] + * break + */ } } __pyx_L4_break:; - /* "View.MemoryView":1082 + /* "View.MemoryView":1114 * break * * for i in range(ndim): # <<<<<<<<<<<<<< @@ -14230,7 +16551,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; - /* "View.MemoryView":1083 + /* "View.MemoryView":1115 * * for i in range(ndim): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< @@ -14240,7 +16561,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1084 + /* "View.MemoryView":1116 * for i in range(ndim): * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< @@ -14249,7 +16570,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ */ __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); - /* "View.MemoryView":1085 + /* "View.MemoryView":1117 * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] * break # <<<<<<<<<<<<<< @@ -14257,11 +16578,19 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): */ goto __pyx_L7_break; + + /* "View.MemoryView":1115 + * + * for i in range(ndim): + * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< + * f_stride = mslice.strides[i] + * break + */ } } __pyx_L7_break:; - /* "View.MemoryView":1087 + /* "View.MemoryView":1119 * break * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< @@ -14271,7 +16600,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1088 + /* "View.MemoryView":1120 * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): * return 'C' # <<<<<<<<<<<<<< @@ -14280,21 +16609,29 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ */ __pyx_r = 'C'; goto __pyx_L0; + + /* "View.MemoryView":1119 + * break + * + * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< + * return 'C' + * else: + */ } - /*else*/ { - /* "View.MemoryView":1090 + /* "View.MemoryView":1122 * return 'C' * else: * return 'F' # <<<<<<<<<<<<<< * * @cython.cdivision(True) */ + /*else*/ { __pyx_r = 'F'; goto __pyx_L0; } - /* "View.MemoryView":1069 + /* "View.MemoryView":1101 * * @cname('__pyx_get_best_slice_order') * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< @@ -14307,7 +16644,7 @@ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int _ return __pyx_r; } -/* "View.MemoryView":1093 +/* "View.MemoryView":1125 * * @cython.cdivision(True) * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< @@ -14327,7 +16664,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; - /* "View.MemoryView":1100 + /* "View.MemoryView":1132 * * cdef Py_ssize_t i * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< @@ -14336,7 +16673,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ __pyx_v_src_extent = (__pyx_v_src_shape[0]); - /* "View.MemoryView":1101 + /* "View.MemoryView":1133 * cdef Py_ssize_t i * cdef Py_ssize_t src_extent = src_shape[0] * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< @@ -14345,7 +16682,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); - /* "View.MemoryView":1102 + /* "View.MemoryView":1134 * cdef Py_ssize_t src_extent = src_shape[0] * cdef Py_ssize_t dst_extent = dst_shape[0] * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< @@ -14354,7 +16691,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ __pyx_v_src_stride = (__pyx_v_src_strides[0]); - /* "View.MemoryView":1103 + /* "View.MemoryView":1135 * cdef Py_ssize_t dst_extent = dst_shape[0] * cdef Py_ssize_t src_stride = src_strides[0] * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< @@ -14363,7 +16700,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); - /* "View.MemoryView":1105 + /* "View.MemoryView":1137 * cdef Py_ssize_t dst_stride = dst_strides[0] * * if ndim == 1: # <<<<<<<<<<<<<< @@ -14373,7 +16710,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_1) { - /* "View.MemoryView":1106 + /* "View.MemoryView":1138 * * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< @@ -14393,7 +16730,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v goto __pyx_L5_bool_binop_done; } - /* "View.MemoryView":1107 + /* "View.MemoryView":1139 * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and * src_stride == itemsize == dst_stride): # <<<<<<<<<<<<<< @@ -14407,32 +16744,48 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v __pyx_t_3 = (__pyx_t_2 != 0); __pyx_t_1 = __pyx_t_3; __pyx_L5_bool_binop_done:; - if (__pyx_t_1) { - /* "View.MemoryView":1108 - * if (src_stride > 0 and dst_stride > 0 and + /* "View.MemoryView":1138 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< * src_stride == itemsize == dst_stride): - * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ + if (__pyx_t_1) { + + /* "View.MemoryView":1140 + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< * else: * for i in range(dst_extent): */ memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent)); + + /* "View.MemoryView":1138 + * + * if ndim == 1: + * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< + * src_stride == itemsize == dst_stride): + * memcpy(dst_data, src_data, itemsize * dst_extent) + */ goto __pyx_L4; } - /*else*/ { - /* "View.MemoryView":1110 + /* "View.MemoryView":1142 * memcpy(dst_data, src_data, itemsize * dst_extent) * else: * for i in range(dst_extent): # <<<<<<<<<<<<<< * memcpy(dst_data, src_data, itemsize) * src_data += src_stride */ + /*else*/ { __pyx_t_4 = __pyx_v_dst_extent; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; - /* "View.MemoryView":1111 + /* "View.MemoryView":1143 * else: * for i in range(dst_extent): * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< @@ -14441,7 +16794,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize); - /* "View.MemoryView":1112 + /* "View.MemoryView":1144 * for i in range(dst_extent): * memcpy(dst_data, src_data, itemsize) * src_data += src_stride # <<<<<<<<<<<<<< @@ -14450,7 +16803,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); - /* "View.MemoryView":1113 + /* "View.MemoryView":1145 * memcpy(dst_data, src_data, itemsize) * src_data += src_stride * dst_data += dst_stride # <<<<<<<<<<<<<< @@ -14461,22 +16814,30 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v } } __pyx_L4:; + + /* "View.MemoryView":1137 + * cdef Py_ssize_t dst_stride = dst_strides[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * if (src_stride > 0 and dst_stride > 0 and + * src_stride == itemsize == dst_stride): + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":1115 + /* "View.MemoryView":1147 * dst_data += dst_stride * else: * for i in range(dst_extent): # <<<<<<<<<<<<<< * _copy_strided_to_strided(src_data, src_strides + 1, * dst_data, dst_strides + 1, */ + /*else*/ { __pyx_t_4 = __pyx_v_dst_extent; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; - /* "View.MemoryView":1116 + /* "View.MemoryView":1148 * else: * for i in range(dst_extent): * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< @@ -14485,7 +16846,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); - /* "View.MemoryView":1120 + /* "View.MemoryView":1152 * src_shape + 1, dst_shape + 1, * ndim - 1, itemsize) * src_data += src_stride # <<<<<<<<<<<<<< @@ -14494,7 +16855,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v */ __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); - /* "View.MemoryView":1121 + /* "View.MemoryView":1153 * ndim - 1, itemsize) * src_data += src_stride * dst_data += dst_stride # <<<<<<<<<<<<<< @@ -14506,7 +16867,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v } __pyx_L3:; - /* "View.MemoryView":1093 + /* "View.MemoryView":1125 * * @cython.cdivision(True) * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< @@ -14517,7 +16878,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v /* function exit code */ } -/* "View.MemoryView":1123 +/* "View.MemoryView":1155 * dst_data += dst_stride * * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< @@ -14527,7 +16888,7 @@ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { - /* "View.MemoryView":1126 + /* "View.MemoryView":1158 * __Pyx_memviewslice *dst, * int ndim, size_t itemsize) nogil: * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< @@ -14536,7 +16897,7 @@ static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memvi */ _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); - /* "View.MemoryView":1123 + /* "View.MemoryView":1155 * dst_data += dst_stride * * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< @@ -14547,7 +16908,7 @@ static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memvi /* function exit code */ } -/* "View.MemoryView":1130 +/* "View.MemoryView":1162 * * @cname('__pyx_memoryview_slice_get_size') * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< @@ -14563,7 +16924,7 @@ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_sr int __pyx_t_2; int __pyx_t_3; - /* "View.MemoryView":1133 + /* "View.MemoryView":1165 * "Return the size of the memory occupied by the slice in number of bytes" * cdef int i * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< @@ -14573,7 +16934,7 @@ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_sr __pyx_t_1 = __pyx_v_src->memview->view.itemsize; __pyx_v_size = __pyx_t_1; - /* "View.MemoryView":1135 + /* "View.MemoryView":1167 * cdef Py_ssize_t size = src.memview.view.itemsize * * for i in range(ndim): # <<<<<<<<<<<<<< @@ -14584,7 +16945,7 @@ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_sr for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; - /* "View.MemoryView":1136 + /* "View.MemoryView":1168 * * for i in range(ndim): * size *= src.shape[i] # <<<<<<<<<<<<<< @@ -14594,7 +16955,7 @@ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_sr __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); } - /* "View.MemoryView":1138 + /* "View.MemoryView":1170 * size *= src.shape[i] * * return size # <<<<<<<<<<<<<< @@ -14604,7 +16965,7 @@ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_sr __pyx_r = __pyx_v_size; goto __pyx_L0; - /* "View.MemoryView":1130 + /* "View.MemoryView":1162 * * @cname('__pyx_memoryview_slice_get_size') * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< @@ -14617,7 +16978,7 @@ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_sr return __pyx_r; } -/* "View.MemoryView":1141 +/* "View.MemoryView":1173 * * @cname('__pyx_fill_contig_strides_array') * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< @@ -14632,7 +16993,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ int __pyx_t_2; int __pyx_t_3; - /* "View.MemoryView":1150 + /* "View.MemoryView":1182 * cdef int idx * * if order == 'F': # <<<<<<<<<<<<<< @@ -14642,7 +17003,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ __pyx_t_1 = ((__pyx_v_order == 'F') != 0); if (__pyx_t_1) { - /* "View.MemoryView":1151 + /* "View.MemoryView":1183 * * if order == 'F': * for idx in range(ndim): # <<<<<<<<<<<<<< @@ -14653,7 +17014,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_idx = __pyx_t_3; - /* "View.MemoryView":1152 + /* "View.MemoryView":1184 * if order == 'F': * for idx in range(ndim): * strides[idx] = stride # <<<<<<<<<<<<<< @@ -14662,7 +17023,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ */ (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; - /* "View.MemoryView":1153 + /* "View.MemoryView":1185 * for idx in range(ndim): * strides[idx] = stride * stride = stride * shape[idx] # <<<<<<<<<<<<<< @@ -14671,21 +17032,29 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ */ __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); } + + /* "View.MemoryView":1182 + * cdef int idx + * + * if order == 'F': # <<<<<<<<<<<<<< + * for idx in range(ndim): + * strides[idx] = stride + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":1155 + /* "View.MemoryView":1187 * stride = stride * shape[idx] * else: * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< * strides[idx] = stride * stride = stride * shape[idx] */ - for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { + /*else*/ { + for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1L; __pyx_t_2-=1) { __pyx_v_idx = __pyx_t_2; - /* "View.MemoryView":1156 + /* "View.MemoryView":1188 * else: * for idx in range(ndim - 1, -1, -1): * strides[idx] = stride # <<<<<<<<<<<<<< @@ -14694,7 +17063,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ */ (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; - /* "View.MemoryView":1157 + /* "View.MemoryView":1189 * for idx in range(ndim - 1, -1, -1): * strides[idx] = stride * stride = stride * shape[idx] # <<<<<<<<<<<<<< @@ -14706,7 +17075,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ } __pyx_L3:; - /* "View.MemoryView":1159 + /* "View.MemoryView":1191 * stride = stride * shape[idx] * * return stride # <<<<<<<<<<<<<< @@ -14716,7 +17085,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ __pyx_r = __pyx_v_stride; goto __pyx_L0; - /* "View.MemoryView":1141 + /* "View.MemoryView":1173 * * @cname('__pyx_fill_contig_strides_array') * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< @@ -14729,7 +17098,7 @@ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ return __pyx_r; } -/* "View.MemoryView":1162 +/* "View.MemoryView":1194 * * @cname('__pyx_memoryview_copy_data_to_temp') * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< @@ -14748,11 +17117,8 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, int __pyx_t_3; struct __pyx_memoryview_obj *__pyx_t_4; int __pyx_t_5; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - /* "View.MemoryView":1173 + /* "View.MemoryView":1205 * cdef void *result * * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< @@ -14762,7 +17128,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __pyx_t_1 = __pyx_v_src->memview->view.itemsize; __pyx_v_itemsize = __pyx_t_1; - /* "View.MemoryView":1174 + /* "View.MemoryView":1206 * * cdef size_t itemsize = src.memview.view.itemsize * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< @@ -14771,7 +17137,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, */ __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); - /* "View.MemoryView":1176 + /* "View.MemoryView":1208 * cdef size_t size = slice_get_size(src, ndim) * * result = malloc(size) # <<<<<<<<<<<<<< @@ -14780,7 +17146,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, */ __pyx_v_result = malloc(__pyx_v_size); - /* "View.MemoryView":1177 + /* "View.MemoryView":1209 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< @@ -14790,19 +17156,25 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1178 + /* "View.MemoryView":1210 * result = malloc(size) * if not result: * _err(MemoryError, NULL) # <<<<<<<<<<<<<< * * */ - __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1178; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L3; + __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == ((int)-1))) __PYX_ERR(1, 1210, __pyx_L1_error) + + /* "View.MemoryView":1209 + * + * result = malloc(size) + * if not result: # <<<<<<<<<<<<<< + * _err(MemoryError, NULL) + * + */ } - __pyx_L3:; - /* "View.MemoryView":1181 + /* "View.MemoryView":1213 * * * tmpslice.data = result # <<<<<<<<<<<<<< @@ -14811,7 +17183,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, */ __pyx_v_tmpslice->data = ((char *)__pyx_v_result); - /* "View.MemoryView":1182 + /* "View.MemoryView":1214 * * tmpslice.data = result * tmpslice.memview = src.memview # <<<<<<<<<<<<<< @@ -14821,7 +17193,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __pyx_t_4 = __pyx_v_src->memview; __pyx_v_tmpslice->memview = __pyx_t_4; - /* "View.MemoryView":1183 + /* "View.MemoryView":1215 * tmpslice.data = result * tmpslice.memview = src.memview * for i in range(ndim): # <<<<<<<<<<<<<< @@ -14832,7 +17204,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; - /* "View.MemoryView":1184 + /* "View.MemoryView":1216 * tmpslice.memview = src.memview * for i in range(ndim): * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< @@ -14841,17 +17213,17 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, */ (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); - /* "View.MemoryView":1185 + /* "View.MemoryView":1217 * for i in range(ndim): * tmpslice.shape[i] = src.shape[i] * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< * * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, */ - (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1; + (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1L; } - /* "View.MemoryView":1187 + /* "View.MemoryView":1219 * tmpslice.suboffsets[i] = -1 * * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< @@ -14860,7 +17232,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, */ __pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order); - /* "View.MemoryView":1191 + /* "View.MemoryView":1223 * * * for i in range(ndim): # <<<<<<<<<<<<<< @@ -14871,7 +17243,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; - /* "View.MemoryView":1192 + /* "View.MemoryView":1224 * * for i in range(ndim): * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< @@ -14881,53 +17253,67 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1193 + /* "View.MemoryView":1225 * for i in range(ndim): * if tmpslice.shape[i] == 1: * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< * - * if slice_is_contig(src, order, ndim): + * if slice_is_contig(src[0], order, ndim): */ (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; - goto __pyx_L8; + + /* "View.MemoryView":1224 + * + * for i in range(ndim): + * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< + * tmpslice.strides[i] = 0 + * + */ } - __pyx_L8:; } - /* "View.MemoryView":1195 + /* "View.MemoryView":1227 * tmpslice.strides[i] = 0 * - * if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< * memcpy(result, src.data, size) * else: */ - __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0); + __pyx_t_2 = (__pyx_memviewslice_is_contig((__pyx_v_src[0]), __pyx_v_order, __pyx_v_ndim) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1196 + /* "View.MemoryView":1228 * - * if slice_is_contig(src, order, ndim): + * if slice_is_contig(src[0], order, ndim): * memcpy(result, src.data, size) # <<<<<<<<<<<<<< * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) */ memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size); + + /* "View.MemoryView":1227 + * tmpslice.strides[i] = 0 + * + * if slice_is_contig(src[0], order, ndim): # <<<<<<<<<<<<<< + * memcpy(result, src.data, size) + * else: + */ goto __pyx_L9; } - /*else*/ { - /* "View.MemoryView":1198 + /* "View.MemoryView":1230 * memcpy(result, src.data, size) * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< * * return result */ + /*else*/ { copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); } __pyx_L9:; - /* "View.MemoryView":1200 + /* "View.MemoryView":1232 * copy_strided_to_strided(src, tmpslice, ndim, itemsize) * * return result # <<<<<<<<<<<<<< @@ -14937,7 +17323,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __pyx_r = __pyx_v_result; goto __pyx_L0; - /* "View.MemoryView":1162 + /* "View.MemoryView":1194 * * @cname('__pyx_memoryview_copy_data_to_temp') * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< @@ -14949,11 +17335,11 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __pyx_L1_error:; { #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); + __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = NULL; @@ -14961,7 +17347,7 @@ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, return __pyx_r; } -/* "View.MemoryView":1205 +/* "View.MemoryView":1237 * * @cname('__pyx_memoryview_err_extents') * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< @@ -14976,62 +17362,59 @@ static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_extents", 0); - /* "View.MemoryView":1208 + /* "View.MemoryView":1240 * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % * (i, extent1, extent2)) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_err_dim') */ - __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1240, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1240, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1240, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1240, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); - PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_2); - PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_3 = 0; - /* "View.MemoryView":1207 + /* "View.MemoryView":1239 * cdef int _err_extents(int i, Py_ssize_t extent1, * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<< * (i, extent1, extent2)) * */ - __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1239, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1239, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); - PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = 0; - __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1239, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1207; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 1239, __pyx_L1_error) - /* "View.MemoryView":1205 + /* "View.MemoryView":1237 * * @cname('__pyx_memoryview_err_extents') * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< @@ -15049,12 +17432,12 @@ static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent __pyx_r = -1; __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); + __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } -/* "View.MemoryView":1211 +/* "View.MemoryView":1243 * * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< @@ -15070,33 +17453,30 @@ static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_dim", 0); __Pyx_INCREF(__pyx_v_error); - /* "View.MemoryView":1212 + /* "View.MemoryView":1244 * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_err') */ - __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1244, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); - __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1244, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = PyUnicode_Format(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = PyUnicode_Format(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 1244, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_INCREF(__pyx_v_error); __pyx_t_3 = __pyx_v_error; __pyx_t_2 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_2)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); @@ -15106,26 +17486,46 @@ static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, } } if (!__pyx_t_2) { - __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1244, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_GOTREF(__pyx_t_1); } else { - __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_5); - PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = NULL; - PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_t_4); - __Pyx_GIVEREF(__pyx_t_4); - __pyx_t_4 = 0; - __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_1); - __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(__pyx_t_3)) { + PyObject *__pyx_temp[2] = {__pyx_t_2, __pyx_t_4}; + __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1244, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else + #endif + #if CYTHON_FAST_PYCCALL + if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { + PyObject *__pyx_temp[2] = {__pyx_t_2, __pyx_t_4}; + __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1244, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else + #endif + { + __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 1244, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __pyx_t_2 = NULL; + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 1244, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + } } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1212; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 1244, __pyx_L1_error) - /* "View.MemoryView":1211 + /* "View.MemoryView":1243 * * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< @@ -15145,12 +17545,12 @@ static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); + __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } -/* "View.MemoryView":1215 +/* "View.MemoryView":1247 * * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< @@ -15167,16 +17567,13 @@ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err", 0); __Pyx_INCREF(__pyx_v_error); - /* "View.MemoryView":1216 + /* "View.MemoryView":1248 * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: # <<<<<<<<<<<<<< @@ -15186,18 +17583,18 @@ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); if (__pyx_t_1) { - /* "View.MemoryView":1217 + /* "View.MemoryView":1249 * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< * else: * raise error */ - __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 1249, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_error); __pyx_t_4 = __pyx_v_error; __pyx_t_5 = NULL; - if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_4))) { + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_4))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); @@ -15207,39 +17604,67 @@ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { } } if (!__pyx_t_5) { - __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1249, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_2); } else { - __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_6); - PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; - PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_t_3); - __Pyx_GIVEREF(__pyx_t_3); - __pyx_t_3 = 0; - __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_t_2); - __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(__pyx_t_4)) { + PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_3}; + __pyx_t_2 = __Pyx_PyFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1249, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else + #endif + #if CYTHON_FAST_PYCCALL + if (__Pyx_PyFastCFunction_Check(__pyx_t_4)) { + PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_3}; + __pyx_t_2 = __Pyx_PyCFunction_FastCall(__pyx_t_4, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1249, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + } else + #endif + { + __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 1249, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __pyx_t_5 = NULL; + __Pyx_GIVEREF(__pyx_t_3); + PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_t_3); + __pyx_t_3 = 0; + __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 1249, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1217; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 1249, __pyx_L1_error) + + /* "View.MemoryView":1248 + * @cname('__pyx_memoryview_err') + * cdef int _err(object error, char *msg) except -1 with gil: + * if msg != NULL: # <<<<<<<<<<<<<< + * raise error(msg.decode('ascii')) + * else: + */ } - /*else*/ { - /* "View.MemoryView":1219 + /* "View.MemoryView":1251 * raise error(msg.decode('ascii')) * else: * raise error # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_contents') */ + /*else*/ { __Pyx_Raise(__pyx_v_error, 0, 0, 0); - {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1219; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __PYX_ERR(1, 1251, __pyx_L1_error) } - /* "View.MemoryView":1215 + /* "View.MemoryView":1247 * * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< @@ -15259,12 +17684,12 @@ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); + __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } -/* "View.MemoryView":1222 +/* "View.MemoryView":1254 * * @cname('__pyx_memoryview_copy_contents') * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< @@ -15289,11 +17714,8 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ int __pyx_t_5; void *__pyx_t_6; int __pyx_t_7; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; - /* "View.MemoryView":1230 + /* "View.MemoryView":1262 * Check for overlapping memory and verify the shapes. * """ * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< @@ -15302,7 +17724,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_tmpdata = NULL; - /* "View.MemoryView":1231 + /* "View.MemoryView":1263 * """ * cdef void *tmpdata = NULL * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< @@ -15312,7 +17734,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_1 = __pyx_v_src.memview->view.itemsize; __pyx_v_itemsize = __pyx_t_1; - /* "View.MemoryView":1233 + /* "View.MemoryView":1265 * cdef size_t itemsize = src.memview.view.itemsize * cdef int i * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< @@ -15321,7 +17743,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); - /* "View.MemoryView":1234 + /* "View.MemoryView":1266 * cdef int i * cdef char order = get_best_order(&src, src_ndim) * cdef bint broadcasting = False # <<<<<<<<<<<<<< @@ -15330,7 +17752,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_broadcasting = 0; - /* "View.MemoryView":1235 + /* "View.MemoryView":1267 * cdef char order = get_best_order(&src, src_ndim) * cdef bint broadcasting = False * cdef bint direct_copy = False # <<<<<<<<<<<<<< @@ -15339,7 +17761,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_direct_copy = 0; - /* "View.MemoryView":1238 + /* "View.MemoryView":1270 * cdef __Pyx_memviewslice tmp * * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< @@ -15349,7 +17771,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1239 + /* "View.MemoryView":1271 * * if src_ndim < dst_ndim: * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< @@ -15357,10 +17779,18 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ * broadcast_leading(&dst, dst_ndim, src_ndim) */ __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); + + /* "View.MemoryView":1270 + * cdef __Pyx_memviewslice tmp + * + * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: + */ goto __pyx_L3; } - /* "View.MemoryView":1240 + /* "View.MemoryView":1272 * if src_ndim < dst_ndim: * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< @@ -15370,7 +17800,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1241 + /* "View.MemoryView":1273 * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< @@ -15378,11 +17808,18 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ * cdef int ndim = max(src_ndim, dst_ndim) */ __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); - goto __pyx_L3; + + /* "View.MemoryView":1272 + * if src_ndim < dst_ndim: + * broadcast_leading(&src, src_ndim, dst_ndim) + * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< + * broadcast_leading(&dst, dst_ndim, src_ndim) + * + */ } __pyx_L3:; - /* "View.MemoryView":1243 + /* "View.MemoryView":1275 * broadcast_leading(&dst, dst_ndim, src_ndim) * * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< @@ -15398,7 +17835,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ } __pyx_v_ndim = __pyx_t_5; - /* "View.MemoryView":1245 + /* "View.MemoryView":1277 * cdef int ndim = max(src_ndim, dst_ndim) * * for i in range(ndim): # <<<<<<<<<<<<<< @@ -15409,7 +17846,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; - /* "View.MemoryView":1246 + /* "View.MemoryView":1278 * * for i in range(ndim): * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< @@ -15419,7 +17856,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1247 + /* "View.MemoryView":1279 * for i in range(ndim): * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: # <<<<<<<<<<<<<< @@ -15429,7 +17866,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1248 + /* "View.MemoryView":1280 * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: * broadcasting = True # <<<<<<<<<<<<<< @@ -15438,7 +17875,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_v_broadcasting = 1; - /* "View.MemoryView":1249 + /* "View.MemoryView":1281 * if src.shape[i] == 1: * broadcasting = True * src.strides[i] = 0 # <<<<<<<<<<<<<< @@ -15446,25 +17883,39 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ * _err_extents(i, dst.shape[i], src.shape[i]) */ (__pyx_v_src.strides[__pyx_v_i]) = 0; + + /* "View.MemoryView":1279 + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: + * if src.shape[i] == 1: # <<<<<<<<<<<<<< + * broadcasting = True + * src.strides[i] = 0 + */ goto __pyx_L7; } - /*else*/ { - /* "View.MemoryView":1251 + /* "View.MemoryView":1283 * src.strides[i] = 0 * else: * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< * * if src.suboffsets[i] >= 0: */ - __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1251; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + /*else*/ { + __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1283, __pyx_L1_error) } __pyx_L7:; - goto __pyx_L6; + + /* "View.MemoryView":1278 + * + * for i in range(ndim): + * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< + * if src.shape[i] == 1: + * broadcasting = True + */ } - __pyx_L6:; - /* "View.MemoryView":1253 + /* "View.MemoryView":1285 * _err_extents(i, dst.shape[i], src.shape[i]) * * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< @@ -15474,62 +17925,74 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1254 + /* "View.MemoryView":1286 * * if src.suboffsets[i] >= 0: * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< * * if slices_overlap(&src, &dst, ndim, itemsize): */ - __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Dimension_d_is_not_direct, __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1254; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L8; + __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, ((char *)"Dimension %d is not direct"), __pyx_v_i); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1286, __pyx_L1_error) + + /* "View.MemoryView":1285 + * _err_extents(i, dst.shape[i], src.shape[i]) + * + * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + */ } - __pyx_L8:; } - /* "View.MemoryView":1256 + /* "View.MemoryView":1288 * _err_dim(ValueError, "Dimension %d is not direct", i) * * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< * - * if not slice_is_contig(&src, order, ndim): + * if not slice_is_contig(src, order, ndim): */ __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1258 + /* "View.MemoryView":1290 * if slices_overlap(&src, &dst, ndim, itemsize): * - * if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<< + * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< * order = get_best_order(&dst, ndim) * */ - __pyx_t_2 = ((!(__pyx_memviewslice_is_contig((&__pyx_v_src), __pyx_v_order, __pyx_v_ndim) != 0)) != 0); + __pyx_t_2 = ((!(__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1259 + /* "View.MemoryView":1291 * - * if not slice_is_contig(&src, order, ndim): + * if not slice_is_contig(src, order, ndim): * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) */ __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); - goto __pyx_L10; + + /* "View.MemoryView":1290 + * if slices_overlap(&src, &dst, ndim, itemsize): + * + * if not slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< + * order = get_best_order(&dst, ndim) + * + */ } - __pyx_L10:; - /* "View.MemoryView":1261 + /* "View.MemoryView":1293 * order = get_best_order(&dst, ndim) * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< * src = tmp * */ - __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1261; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == ((void *)NULL))) __PYX_ERR(1, 1293, __pyx_L1_error) __pyx_v_tmpdata = __pyx_t_6; - /* "View.MemoryView":1262 + /* "View.MemoryView":1294 * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) * src = tmp # <<<<<<<<<<<<<< @@ -15537,11 +18000,17 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ * if not broadcasting: */ __pyx_v_src = __pyx_v_tmp; - goto __pyx_L9; + + /* "View.MemoryView":1288 + * _err_dim(ValueError, "Dimension %d is not direct", i) + * + * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< + * + * if not slice_is_contig(src, order, ndim): + */ } - __pyx_L9:; - /* "View.MemoryView":1264 + /* "View.MemoryView":1296 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< @@ -15551,51 +18020,66 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1267 + /* "View.MemoryView":1299 * * - * if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(&dst, 'C', ndim) - * elif slice_is_contig(&src, 'F', ndim): + * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(dst, 'C', ndim) + * elif slice_is_contig(src, 'F', ndim): */ - __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'C', __pyx_v_ndim) != 0); + __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'C', __pyx_v_ndim) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1268 + /* "View.MemoryView":1300 + * + * if slice_is_contig(src, 'C', ndim): + * direct_copy = slice_is_contig(dst, 'C', ndim) # <<<<<<<<<<<<<< + * elif slice_is_contig(src, 'F', ndim): + * direct_copy = slice_is_contig(dst, 'F', ndim) + */ + __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'C', __pyx_v_ndim); + + /* "View.MemoryView":1299 + * * - * if slice_is_contig(&src, 'C', ndim): - * direct_copy = slice_is_contig(&dst, 'C', ndim) # <<<<<<<<<<<<<< - * elif slice_is_contig(&src, 'F', ndim): - * direct_copy = slice_is_contig(&dst, 'F', ndim) + * if slice_is_contig(src, 'C', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(dst, 'C', ndim) + * elif slice_is_contig(src, 'F', ndim): */ - __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'C', __pyx_v_ndim); goto __pyx_L12; } - /* "View.MemoryView":1269 - * if slice_is_contig(&src, 'C', ndim): - * direct_copy = slice_is_contig(&dst, 'C', ndim) - * elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<< - * direct_copy = slice_is_contig(&dst, 'F', ndim) + /* "View.MemoryView":1301 + * if slice_is_contig(src, 'C', ndim): + * direct_copy = slice_is_contig(dst, 'C', ndim) + * elif slice_is_contig(src, 'F', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(dst, 'F', ndim) * */ - __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'F', __pyx_v_ndim) != 0); + __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, 'F', __pyx_v_ndim) != 0); if (__pyx_t_2) { - /* "View.MemoryView":1270 - * direct_copy = slice_is_contig(&dst, 'C', ndim) - * elif slice_is_contig(&src, 'F', ndim): - * direct_copy = slice_is_contig(&dst, 'F', ndim) # <<<<<<<<<<<<<< + /* "View.MemoryView":1302 + * direct_copy = slice_is_contig(dst, 'C', ndim) + * elif slice_is_contig(src, 'F', ndim): + * direct_copy = slice_is_contig(dst, 'F', ndim) # <<<<<<<<<<<<<< * * if direct_copy: */ - __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'F', __pyx_v_ndim); - goto __pyx_L12; + __pyx_v_direct_copy = __pyx_memviewslice_is_contig(__pyx_v_dst, 'F', __pyx_v_ndim); + + /* "View.MemoryView":1301 + * if slice_is_contig(src, 'C', ndim): + * direct_copy = slice_is_contig(dst, 'C', ndim) + * elif slice_is_contig(src, 'F', ndim): # <<<<<<<<<<<<<< + * direct_copy = slice_is_contig(dst, 'F', ndim) + * + */ } __pyx_L12:; - /* "View.MemoryView":1272 - * direct_copy = slice_is_contig(&dst, 'F', ndim) + /* "View.MemoryView":1304 + * direct_copy = slice_is_contig(dst, 'F', ndim) * * if direct_copy: # <<<<<<<<<<<<<< * @@ -15604,7 +18088,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_2 = (__pyx_v_direct_copy != 0); if (__pyx_t_2) { - /* "View.MemoryView":1274 + /* "View.MemoryView":1306 * if direct_copy: * * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< @@ -15613,7 +18097,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - /* "View.MemoryView":1275 + /* "View.MemoryView":1307 * * refcount_copying(&dst, dtype_is_object, ndim, False) * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< @@ -15622,7 +18106,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim)); - /* "View.MemoryView":1276 + /* "View.MemoryView":1308 * refcount_copying(&dst, dtype_is_object, ndim, False) * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< @@ -15631,7 +18115,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - /* "View.MemoryView":1277 + /* "View.MemoryView":1309 * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) # <<<<<<<<<<<<<< @@ -15640,7 +18124,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ free(__pyx_v_tmpdata); - /* "View.MemoryView":1278 + /* "View.MemoryView":1310 * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) * return 0 # <<<<<<<<<<<<<< @@ -15649,12 +18133,26 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_r = 0; goto __pyx_L0; + + /* "View.MemoryView":1304 + * direct_copy = slice_is_contig(dst, 'F', ndim) + * + * if direct_copy: # <<<<<<<<<<<<<< + * + * refcount_copying(&dst, dtype_is_object, ndim, False) + */ } - goto __pyx_L11; + + /* "View.MemoryView":1296 + * src = tmp + * + * if not broadcasting: # <<<<<<<<<<<<<< + * + * + */ } - __pyx_L11:; - /* "View.MemoryView":1280 + /* "View.MemoryView":1312 * return 0 * * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< @@ -15668,28 +18166,34 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_t_7 = (__pyx_t_2 != 0); if (__pyx_t_7) { - /* "View.MemoryView":1283 + /* "View.MemoryView":1315 * * * transpose_memslice(&src) # <<<<<<<<<<<<<< * transpose_memslice(&dst) * */ - __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1283; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(1, 1315, __pyx_L1_error) - /* "View.MemoryView":1284 + /* "View.MemoryView":1316 * * transpose_memslice(&src) * transpose_memslice(&dst) # <<<<<<<<<<<<<< * * refcount_copying(&dst, dtype_is_object, ndim, False) */ - __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 1284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - goto __pyx_L14; + __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == ((int)0))) __PYX_ERR(1, 1316, __pyx_L1_error) + + /* "View.MemoryView":1312 + * return 0 + * + * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< + * + * + */ } - __pyx_L14:; - /* "View.MemoryView":1286 + /* "View.MemoryView":1318 * transpose_memslice(&dst) * * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< @@ -15698,7 +18202,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - /* "View.MemoryView":1287 + /* "View.MemoryView":1319 * * refcount_copying(&dst, dtype_is_object, ndim, False) * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< @@ -15707,7 +18211,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); - /* "View.MemoryView":1288 + /* "View.MemoryView":1320 * refcount_copying(&dst, dtype_is_object, ndim, False) * copy_strided_to_strided(&src, &dst, ndim, itemsize) * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< @@ -15716,7 +18220,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - /* "View.MemoryView":1290 + /* "View.MemoryView":1322 * refcount_copying(&dst, dtype_is_object, ndim, True) * * free(tmpdata) # <<<<<<<<<<<<<< @@ -15725,7 +18229,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ */ free(__pyx_v_tmpdata); - /* "View.MemoryView":1291 + /* "View.MemoryView":1323 * * free(tmpdata) * return 0 # <<<<<<<<<<<<<< @@ -15735,7 +18239,7 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_r = 0; goto __pyx_L0; - /* "View.MemoryView":1222 + /* "View.MemoryView":1254 * * @cname('__pyx_memoryview_copy_contents') * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< @@ -15747,11 +18251,11 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ __pyx_L1_error:; { #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); + __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; @@ -15759,21 +18263,21 @@ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_ return __pyx_r; } -/* "View.MemoryView":1294 +/* "View.MemoryView":1326 * * @cname('__pyx_memoryview_broadcast_leading') - * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< * int ndim, * int ndim_other) nogil: */ -static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_slice, int __pyx_v_ndim, int __pyx_v_ndim_other) { +static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim, int __pyx_v_ndim_other) { int __pyx_v_i; int __pyx_v_offset; int __pyx_t_1; int __pyx_t_2; - /* "View.MemoryView":1298 + /* "View.MemoryView":1330 * int ndim_other) nogil: * cdef int i * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< @@ -15782,87 +18286,87 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_slice */ __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); - /* "View.MemoryView":1300 + /* "View.MemoryView":1332 * cdef int offset = ndim_other - ndim * * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< - * slice.shape[i + offset] = slice.shape[i] - * slice.strides[i + offset] = slice.strides[i] + * mslice.shape[i + offset] = mslice.shape[i] + * mslice.strides[i + offset] = mslice.strides[i] */ - for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { + for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1L; __pyx_t_1-=1) { __pyx_v_i = __pyx_t_1; - /* "View.MemoryView":1301 + /* "View.MemoryView":1333 * * for i in range(ndim - 1, -1, -1): - * slice.shape[i + offset] = slice.shape[i] # <<<<<<<<<<<<<< - * slice.strides[i + offset] = slice.strides[i] - * slice.suboffsets[i + offset] = slice.suboffsets[i] + * mslice.shape[i + offset] = mslice.shape[i] # <<<<<<<<<<<<<< + * mslice.strides[i + offset] = mslice.strides[i] + * mslice.suboffsets[i + offset] = mslice.suboffsets[i] */ - (__pyx_v_slice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->shape[__pyx_v_i]); + (__pyx_v_mslice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->shape[__pyx_v_i]); - /* "View.MemoryView":1302 + /* "View.MemoryView":1334 * for i in range(ndim - 1, -1, -1): - * slice.shape[i + offset] = slice.shape[i] - * slice.strides[i + offset] = slice.strides[i] # <<<<<<<<<<<<<< - * slice.suboffsets[i + offset] = slice.suboffsets[i] + * mslice.shape[i + offset] = mslice.shape[i] + * mslice.strides[i + offset] = mslice.strides[i] # <<<<<<<<<<<<<< + * mslice.suboffsets[i + offset] = mslice.suboffsets[i] * */ - (__pyx_v_slice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->strides[__pyx_v_i]); + (__pyx_v_mslice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->strides[__pyx_v_i]); - /* "View.MemoryView":1303 - * slice.shape[i + offset] = slice.shape[i] - * slice.strides[i + offset] = slice.strides[i] - * slice.suboffsets[i + offset] = slice.suboffsets[i] # <<<<<<<<<<<<<< + /* "View.MemoryView":1335 + * mslice.shape[i + offset] = mslice.shape[i] + * mslice.strides[i + offset] = mslice.strides[i] + * mslice.suboffsets[i + offset] = mslice.suboffsets[i] # <<<<<<<<<<<<<< * * for i in range(offset): */ - (__pyx_v_slice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->suboffsets[__pyx_v_i]); + (__pyx_v_mslice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->suboffsets[__pyx_v_i]); } - /* "View.MemoryView":1305 - * slice.suboffsets[i + offset] = slice.suboffsets[i] + /* "View.MemoryView":1337 + * mslice.suboffsets[i + offset] = mslice.suboffsets[i] * * for i in range(offset): # <<<<<<<<<<<<<< - * slice.shape[i] = 1 - * slice.strides[i] = slice.strides[0] + * mslice.shape[i] = 1 + * mslice.strides[i] = mslice.strides[0] */ __pyx_t_1 = __pyx_v_offset; for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; - /* "View.MemoryView":1306 + /* "View.MemoryView":1338 * * for i in range(offset): - * slice.shape[i] = 1 # <<<<<<<<<<<<<< - * slice.strides[i] = slice.strides[0] - * slice.suboffsets[i] = -1 + * mslice.shape[i] = 1 # <<<<<<<<<<<<<< + * mslice.strides[i] = mslice.strides[0] + * mslice.suboffsets[i] = -1 */ - (__pyx_v_slice->shape[__pyx_v_i]) = 1; + (__pyx_v_mslice->shape[__pyx_v_i]) = 1; - /* "View.MemoryView":1307 + /* "View.MemoryView":1339 * for i in range(offset): - * slice.shape[i] = 1 - * slice.strides[i] = slice.strides[0] # <<<<<<<<<<<<<< - * slice.suboffsets[i] = -1 + * mslice.shape[i] = 1 + * mslice.strides[i] = mslice.strides[0] # <<<<<<<<<<<<<< + * mslice.suboffsets[i] = -1 * */ - (__pyx_v_slice->strides[__pyx_v_i]) = (__pyx_v_slice->strides[0]); + (__pyx_v_mslice->strides[__pyx_v_i]) = (__pyx_v_mslice->strides[0]); - /* "View.MemoryView":1308 - * slice.shape[i] = 1 - * slice.strides[i] = slice.strides[0] - * slice.suboffsets[i] = -1 # <<<<<<<<<<<<<< + /* "View.MemoryView":1340 + * mslice.shape[i] = 1 + * mslice.strides[i] = mslice.strides[0] + * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< * * */ - (__pyx_v_slice->suboffsets[__pyx_v_i]) = -1; + (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1L; } - /* "View.MemoryView":1294 + /* "View.MemoryView":1326 * * @cname('__pyx_memoryview_broadcast_leading') - * cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<< + * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< * int ndim, * int ndim_other) nogil: */ @@ -15870,7 +18374,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_slice /* function exit code */ } -/* "View.MemoryView":1316 +/* "View.MemoryView":1348 * * @cname('__pyx_memoryview_refcount_copying') * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< @@ -15881,7 +18385,7 @@ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_slice static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { int __pyx_t_1; - /* "View.MemoryView":1320 + /* "View.MemoryView":1352 * * * if dtype_is_object: # <<<<<<<<<<<<<< @@ -15891,7 +18395,7 @@ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, i __pyx_t_1 = (__pyx_v_dtype_is_object != 0); if (__pyx_t_1) { - /* "View.MemoryView":1321 + /* "View.MemoryView":1353 * * if dtype_is_object: * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< @@ -15899,11 +18403,17 @@ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, i * */ __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); - goto __pyx_L3; + + /* "View.MemoryView":1352 + * + * + * if dtype_is_object: # <<<<<<<<<<<<<< + * refcount_objects_in_slice_with_gil(dst.data, dst.shape, + * dst.strides, ndim, inc) + */ } - __pyx_L3:; - /* "View.MemoryView":1316 + /* "View.MemoryView":1348 * * @cname('__pyx_memoryview_refcount_copying') * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< @@ -15914,7 +18424,7 @@ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, i /* function exit code */ } -/* "View.MemoryView":1325 +/* "View.MemoryView":1357 * * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< @@ -15925,11 +18435,11 @@ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, i static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { __Pyx_RefNannyDeclarations #ifdef WITH_THREAD - PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); + PyGILState_STATE __pyx_gilstate_save = __Pyx_PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); - /* "View.MemoryView":1328 + /* "View.MemoryView":1360 * Py_ssize_t *strides, int ndim, * bint inc) with gil: * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< @@ -15938,7 +18448,7 @@ static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_da */ __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); - /* "View.MemoryView":1325 + /* "View.MemoryView":1357 * * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< @@ -15949,11 +18459,11 @@ static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_da /* function exit code */ __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD - PyGILState_Release(__pyx_gilstate_save); + __Pyx_PyGILState_Release(__pyx_gilstate_save); #endif } -/* "View.MemoryView":1331 +/* "View.MemoryView":1363 * * @cname('__pyx_memoryview_refcount_objects_in_slice') * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< @@ -15969,7 +18479,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss int __pyx_t_3; __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); - /* "View.MemoryView":1335 + /* "View.MemoryView":1367 * cdef Py_ssize_t i * * for i in range(shape[0]): # <<<<<<<<<<<<<< @@ -15980,7 +18490,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; - /* "View.MemoryView":1336 + /* "View.MemoryView":1368 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< @@ -15990,7 +18500,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss __pyx_t_3 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_3) { - /* "View.MemoryView":1337 + /* "View.MemoryView":1369 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< @@ -16000,7 +18510,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss __pyx_t_3 = (__pyx_v_inc != 0); if (__pyx_t_3) { - /* "View.MemoryView":1338 + /* "View.MemoryView":1370 * if ndim == 1: * if inc: * Py_INCREF(( data)[0]) # <<<<<<<<<<<<<< @@ -16008,36 +18518,60 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss * Py_DECREF(( data)[0]) */ Py_INCREF((((PyObject **)__pyx_v_data)[0])); - goto __pyx_L6; - } - /*else*/ { - /* "View.MemoryView":1340 + /* "View.MemoryView":1369 + * for i in range(shape[0]): + * if ndim == 1: + * if inc: # <<<<<<<<<<<<<< * Py_INCREF(( data)[0]) * else: - * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< + */ + goto __pyx_L6; + } + + /* "View.MemoryView":1372 + * Py_INCREF(( data)[0]) + * else: + * Py_DECREF(( data)[0]) # <<<<<<<<<<<<<< * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, */ + /*else*/ { Py_DECREF((((PyObject **)__pyx_v_data)[0])); } __pyx_L6:; + + /* "View.MemoryView":1368 + * + * for i in range(shape[0]): + * if ndim == 1: # <<<<<<<<<<<<<< + * if inc: + * Py_INCREF(( data)[0]) + */ goto __pyx_L5; } - /*else*/ { - /* "View.MemoryView":1342 + /* "View.MemoryView":1374 * Py_DECREF(( data)[0]) * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< * ndim - 1, inc) * + */ + /*else*/ { + + /* "View.MemoryView":1375 + * else: + * refcount_objects_in_slice(data, shape + 1, strides + 1, + * ndim - 1, inc) # <<<<<<<<<<<<<< + * + * data += strides[0] */ __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); } __pyx_L5:; - /* "View.MemoryView":1345 + /* "View.MemoryView":1377 * ndim - 1, inc) * * data += strides[0] # <<<<<<<<<<<<<< @@ -16047,7 +18581,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); } - /* "View.MemoryView":1331 + /* "View.MemoryView":1363 * * @cname('__pyx_memoryview_refcount_objects_in_slice') * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< @@ -16059,7 +18593,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss __Pyx_RefNannyFinishContext(); } -/* "View.MemoryView":1351 +/* "View.MemoryView":1383 * * @cname('__pyx_memoryview_slice_assign_scalar') * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< @@ -16069,7 +18603,7 @@ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ss static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { - /* "View.MemoryView":1354 + /* "View.MemoryView":1386 * size_t itemsize, void *item, * bint dtype_is_object) nogil: * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< @@ -16078,7 +18612,7 @@ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst */ __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); - /* "View.MemoryView":1355 + /* "View.MemoryView":1387 * bint dtype_is_object) nogil: * refcount_copying(dst, dtype_is_object, ndim, False) * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< @@ -16087,7 +18621,7 @@ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst */ __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); - /* "View.MemoryView":1357 + /* "View.MemoryView":1389 * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, * itemsize, item) * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< @@ -16096,7 +18630,7 @@ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst */ __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); - /* "View.MemoryView":1351 + /* "View.MemoryView":1383 * * @cname('__pyx_memoryview_slice_assign_scalar') * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< @@ -16107,7 +18641,7 @@ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst /* function exit code */ } -/* "View.MemoryView":1361 +/* "View.MemoryView":1393 * * @cname('__pyx_memoryview__slice_assign_scalar') * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< @@ -16123,7 +18657,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t Py_ssize_t __pyx_t_2; Py_ssize_t __pyx_t_3; - /* "View.MemoryView":1365 + /* "View.MemoryView":1397 * size_t itemsize, void *item) nogil: * cdef Py_ssize_t i * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< @@ -16132,7 +18666,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t */ __pyx_v_stride = (__pyx_v_strides[0]); - /* "View.MemoryView":1366 + /* "View.MemoryView":1398 * cdef Py_ssize_t i * cdef Py_ssize_t stride = strides[0] * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< @@ -16141,7 +18675,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t */ __pyx_v_extent = (__pyx_v_shape[0]); - /* "View.MemoryView":1368 + /* "View.MemoryView":1400 * cdef Py_ssize_t extent = shape[0] * * if ndim == 1: # <<<<<<<<<<<<<< @@ -16151,7 +18685,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_1) { - /* "View.MemoryView":1369 + /* "View.MemoryView":1401 * * if ndim == 1: * for i in range(extent): # <<<<<<<<<<<<<< @@ -16162,7 +18696,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; - /* "View.MemoryView":1370 + /* "View.MemoryView":1402 * if ndim == 1: * for i in range(extent): * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< @@ -16171,7 +18705,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t */ memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize); - /* "View.MemoryView":1371 + /* "View.MemoryView":1403 * for i in range(extent): * memcpy(data, item, itemsize) * data += stride # <<<<<<<<<<<<<< @@ -16180,22 +18714,30 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t */ __pyx_v_data = (__pyx_v_data + __pyx_v_stride); } + + /* "View.MemoryView":1400 + * cdef Py_ssize_t extent = shape[0] + * + * if ndim == 1: # <<<<<<<<<<<<<< + * for i in range(extent): + * memcpy(data, item, itemsize) + */ goto __pyx_L3; } - /*else*/ { - /* "View.MemoryView":1373 + /* "View.MemoryView":1405 * data += stride * else: * for i in range(extent): # <<<<<<<<<<<<<< * _slice_assign_scalar(data, shape + 1, strides + 1, * ndim - 1, itemsize, item) */ + /*else*/ { __pyx_t_2 = __pyx_v_extent; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; - /* "View.MemoryView":1374 + /* "View.MemoryView":1406 * else: * for i in range(extent): * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< @@ -16204,7 +18746,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t */ __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); - /* "View.MemoryView":1376 + /* "View.MemoryView":1408 * _slice_assign_scalar(data, shape + 1, strides + 1, * ndim - 1, itemsize, item) * data += stride # <<<<<<<<<<<<<< @@ -16216,7 +18758,7 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t } __pyx_L3:; - /* "View.MemoryView":1361 + /* "View.MemoryView":1393 * * @cname('__pyx_memoryview__slice_assign_scalar') * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< @@ -16227,123 +18769,606 @@ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t /* function exit code */ } -static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { - struct __pyx_array_obj *p; - PyObject *o; - if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { - o = (*t->tp_alloc)(t, 0); - } else { - o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); - } - if (unlikely(!o)) return 0; - p = ((struct __pyx_array_obj *)o); - p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); - p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); - if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) { - Py_DECREF(o); o = 0; - } - return o; -} +/* "(tree fragment)":1 + * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< + * if __pyx_checksum != 0xb068931: + * from pickle import PickleError as __pyx_PickleError + */ -static void __pyx_tp_dealloc_array(PyObject *o) { - struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; - #if PY_VERSION_HEX >= 0x030400a1 - if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { - if (PyObject_CallFinalizerFromDealloc(o)) return; - } - #endif +/* Python wrapper */ +static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ +static PyMethodDef __pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum = {"__pyx_unpickle_Enum", (PyCFunction)__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum, METH_VARARGS|METH_KEYWORDS, 0}; +static PyObject *__pyx_pw_15View_dot_MemoryView_1__pyx_unpickle_Enum(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { + PyObject *__pyx_v___pyx_type = 0; + long __pyx_v___pyx_checksum; + PyObject *__pyx_v___pyx_state = 0; + PyObject *__pyx_r = 0; + __Pyx_RefNannyDeclarations + __Pyx_RefNannySetupContext("__pyx_unpickle_Enum (wrapper)", 0); { - PyObject *etype, *eval, *etb; - PyErr_Fetch(&etype, &eval, &etb); - ++Py_REFCNT(o); - __pyx_array___dealloc__(o); - --Py_REFCNT(o); - PyErr_Restore(etype, eval, etb); + static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_pyx_type,&__pyx_n_s_pyx_checksum,&__pyx_n_s_pyx_state,0}; + PyObject* values[3] = {0,0,0}; + if (unlikely(__pyx_kwds)) { + Py_ssize_t kw_args; + const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); + switch (pos_args) { + case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + CYTHON_FALLTHROUGH; + case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + CYTHON_FALLTHROUGH; + case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + CYTHON_FALLTHROUGH; + case 0: break; + default: goto __pyx_L5_argtuple_error; + } + kw_args = PyDict_Size(__pyx_kwds); + switch (pos_args) { + case 0: + if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_pyx_type)) != 0)) kw_args--; + else goto __pyx_L5_argtuple_error; + CYTHON_FALLTHROUGH; + case 1: + if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_pyx_checksum)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 1); __PYX_ERR(1, 1, __pyx_L3_error) + } + CYTHON_FALLTHROUGH; + case 2: + if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_pyx_state)) != 0)) kw_args--; + else { + __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, 2); __PYX_ERR(1, 1, __pyx_L3_error) + } + } + if (unlikely(kw_args > 0)) { + if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_unpickle_Enum") < 0)) __PYX_ERR(1, 1, __pyx_L3_error) + } + } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { + goto __pyx_L5_argtuple_error; + } else { + values[0] = PyTuple_GET_ITEM(__pyx_args, 0); + values[1] = PyTuple_GET_ITEM(__pyx_args, 1); + values[2] = PyTuple_GET_ITEM(__pyx_args, 2); + } + __pyx_v___pyx_type = values[0]; + __pyx_v___pyx_checksum = __Pyx_PyInt_As_long(values[1]); if (unlikely((__pyx_v___pyx_checksum == (long)-1) && PyErr_Occurred())) __PYX_ERR(1, 1, __pyx_L3_error) + __pyx_v___pyx_state = values[2]; } - Py_CLEAR(p->mode); - Py_CLEAR(p->_format); - (*Py_TYPE(o)->tp_free)(o); -} -static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { - PyObject *r; - PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; - r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); - Py_DECREF(x); - return r; -} + goto __pyx_L4_argument_unpacking_done; + __pyx_L5_argtuple_error:; + __Pyx_RaiseArgtupleInvalid("__pyx_unpickle_Enum", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(1, 1, __pyx_L3_error) + __pyx_L3_error:; + __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_RefNannyFinishContext(); + return NULL; + __pyx_L4_argument_unpacking_done:; + __pyx_r = __pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(__pyx_self, __pyx_v___pyx_type, __pyx_v___pyx_checksum, __pyx_v___pyx_state); -static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { - if (v) { - return __pyx_array___setitem__(o, i, v); - } - else { - PyErr_Format(PyExc_NotImplementedError, - "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); - return -1; - } + /* function exit code */ + __Pyx_RefNannyFinishContext(); + return __pyx_r; } -static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { - PyObject *v = PyObject_GenericGetAttr(o, n); - if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { - PyErr_Clear(); - v = __pyx_array___getattr__(o, n); +static PyObject *__pyx_pf_15View_dot_MemoryView___pyx_unpickle_Enum(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v___pyx_type, long __pyx_v___pyx_checksum, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_v___pyx_PickleError = NULL; + PyObject *__pyx_v___pyx_result = NULL; + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + int __pyx_t_1; + PyObject *__pyx_t_2 = NULL; + PyObject *__pyx_t_3 = NULL; + PyObject *__pyx_t_4 = NULL; + PyObject *__pyx_t_5 = NULL; + PyObject *__pyx_t_6 = NULL; + int __pyx_t_7; + __Pyx_RefNannySetupContext("__pyx_unpickle_Enum", 0); + + /* "(tree fragment)":2 + * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): + * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) + */ + __pyx_t_1 = ((__pyx_v___pyx_checksum != 0xb068931) != 0); + if (__pyx_t_1) { + + /* "(tree fragment)":3 + * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): + * if __pyx_checksum != 0xb068931: + * from pickle import PickleError as __pyx_PickleError # <<<<<<<<<<<<<< + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) + * __pyx_result = Enum.__new__(__pyx_type) + */ + __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_n_s_PickleError); + __Pyx_GIVEREF(__pyx_n_s_PickleError); + PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_PickleError); + __pyx_t_3 = __Pyx_Import(__pyx_n_s_pickle, __pyx_t_2, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_3, __pyx_n_s_PickleError); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 3, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __Pyx_INCREF(__pyx_t_2); + __pyx_v___pyx_PickleError = __pyx_t_2; + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + + /* "(tree fragment)":4 + * if __pyx_checksum != 0xb068931: + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) # <<<<<<<<<<<<<< + * __pyx_result = Enum.__new__(__pyx_type) + * if __pyx_state is not None: + */ + __pyx_t_2 = __Pyx_PyInt_From_long(__pyx_v___pyx_checksum); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_t_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_INCREF(__pyx_v___pyx_PickleError); + __pyx_t_2 = __pyx_v___pyx_PickleError; __pyx_t_5 = NULL; + if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_5)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_5); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (!__pyx_t_5) { + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + __Pyx_GOTREF(__pyx_t_3); + } else { + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(__pyx_t_2)) { + PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_4}; + __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else + #endif + #if CYTHON_FAST_PYCCALL + if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { + PyObject *__pyx_temp[2] = {__pyx_t_5, __pyx_t_4}; + __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } else + #endif + { + __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __pyx_t_5 = NULL; + __Pyx_GIVEREF(__pyx_t_4); + PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_t_4); + __pyx_t_4 = 0; + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_6, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __Pyx_Raise(__pyx_t_3, 0, 0, 0); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; + __PYX_ERR(1, 4, __pyx_L1_error) + + /* "(tree fragment)":2 + * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): + * if __pyx_checksum != 0xb068931: # <<<<<<<<<<<<<< + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) + */ } - return v; -} -static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { - return get_memview(o); -} + /* "(tree fragment)":5 + * from pickle import PickleError as __pyx_PickleError + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) + * __pyx_result = Enum.__new__(__pyx_type) # <<<<<<<<<<<<<< + * if __pyx_state is not None: + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + */ + __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_MemviewEnum_type), __pyx_n_s_new); if (unlikely(!__pyx_t_2)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_2); + __pyx_t_6 = NULL; + if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_2))) { + __pyx_t_6 = PyMethod_GET_SELF(__pyx_t_2); + if (likely(__pyx_t_6)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_2); + __Pyx_INCREF(__pyx_t_6); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_2, function); + } + } + if (!__pyx_t_6) { + __pyx_t_3 = __Pyx_PyObject_CallOneArg(__pyx_t_2, __pyx_v___pyx_type); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + } else { + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(__pyx_t_2)) { + PyObject *__pyx_temp[2] = {__pyx_t_6, __pyx_v___pyx_type}; + __pyx_t_3 = __Pyx_PyFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_GOTREF(__pyx_t_3); + } else + #endif + #if CYTHON_FAST_PYCCALL + if (__Pyx_PyFastCFunction_Check(__pyx_t_2)) { + PyObject *__pyx_temp[2] = {__pyx_t_6, __pyx_v___pyx_type}; + __pyx_t_3 = __Pyx_PyCFunction_FastCall(__pyx_t_2, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_GOTREF(__pyx_t_3); + } else + #endif + { + __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_4); + __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_6); __pyx_t_6 = NULL; + __Pyx_INCREF(__pyx_v___pyx_type); + __Pyx_GIVEREF(__pyx_v___pyx_type); + PyTuple_SET_ITEM(__pyx_t_4, 0+1, __pyx_v___pyx_type); + __pyx_t_3 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 5, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; + } + } + __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; + __pyx_v___pyx_result = __pyx_t_3; + __pyx_t_3 = 0; -static PyMethodDef __pyx_methods_array[] = { - {"__getattr__", (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, 0}, - {0, 0, 0, 0} -}; + /* "(tree fragment)":6 + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) + * __pyx_result = Enum.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + * return __pyx_result + */ + __pyx_t_1 = (__pyx_v___pyx_state != Py_None); + __pyx_t_7 = (__pyx_t_1 != 0); + if (__pyx_t_7) { -static struct PyGetSetDef __pyx_getsets_array[] = { - {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, 0, 0}, - {0, 0, 0, 0, 0} -}; + /* "(tree fragment)":7 + * __pyx_result = Enum.__new__(__pyx_type) + * if __pyx_state is not None: + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) # <<<<<<<<<<<<<< + * return __pyx_result + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): + */ + if (!(likely(PyTuple_CheckExact(__pyx_v___pyx_state))||((__pyx_v___pyx_state) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_v___pyx_state)->tp_name), 0))) __PYX_ERR(1, 7, __pyx_L1_error) + __pyx_t_3 = __pyx_unpickle_Enum__set_state(((struct __pyx_MemviewEnum_obj *)__pyx_v___pyx_result), ((PyObject*)__pyx_v___pyx_state)); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 7, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_3); + __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; -static PySequenceMethods __pyx_tp_as_sequence_array = { - 0, /*sq_length*/ - 0, /*sq_concat*/ - 0, /*sq_repeat*/ - __pyx_sq_item_array, /*sq_item*/ - 0, /*sq_slice*/ - 0, /*sq_ass_item*/ - 0, /*sq_ass_slice*/ - 0, /*sq_contains*/ - 0, /*sq_inplace_concat*/ - 0, /*sq_inplace_repeat*/ -}; + /* "(tree fragment)":6 + * raise __pyx_PickleError("Incompatible checksums (%s vs 0xb068931 = (name))" % __pyx_checksum) + * __pyx_result = Enum.__new__(__pyx_type) + * if __pyx_state is not None: # <<<<<<<<<<<<<< + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + * return __pyx_result + */ + } -static PyMappingMethods __pyx_tp_as_mapping_array = { - 0, /*mp_length*/ - __pyx_array___getitem__, /*mp_subscript*/ - __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ -}; + /* "(tree fragment)":8 + * if __pyx_state is not None: + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + * return __pyx_result # <<<<<<<<<<<<<< + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): + * __pyx_result.name = __pyx_state[0] + */ + __Pyx_XDECREF(__pyx_r); + __Pyx_INCREF(__pyx_v___pyx_result); + __pyx_r = __pyx_v___pyx_result; + goto __pyx_L0; -static PyBufferProcs __pyx_tp_as_buffer_array = { - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getreadbuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getwritebuffer*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getsegcount*/ - #endif - #if PY_MAJOR_VERSION < 3 - 0, /*bf_getcharbuffer*/ - #endif - __pyx_array_getbuffer, /*bf_getbuffer*/ - 0, /*bf_releasebuffer*/ -}; + /* "(tree fragment)":1 + * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< + * if __pyx_checksum != 0xb068931: + * from pickle import PickleError as __pyx_PickleError + */ -static PyTypeObject __pyx_type___pyx_array = { - PyVarObject_HEAD_INIT(0, 0) + /* function exit code */ + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_2); + __Pyx_XDECREF(__pyx_t_3); + __Pyx_XDECREF(__pyx_t_4); + __Pyx_XDECREF(__pyx_t_5); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = NULL; + __pyx_L0:; + __Pyx_XDECREF(__pyx_v___pyx_PickleError); + __Pyx_XDECREF(__pyx_v___pyx_result); + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} + +/* "(tree fragment)":9 + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< + * __pyx_result.name = __pyx_state[0] + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): + */ + +static PyObject *__pyx_unpickle_Enum__set_state(struct __pyx_MemviewEnum_obj *__pyx_v___pyx_result, PyObject *__pyx_v___pyx_state) { + PyObject *__pyx_r = NULL; + __Pyx_RefNannyDeclarations + PyObject *__pyx_t_1 = NULL; + int __pyx_t_2; + Py_ssize_t __pyx_t_3; + int __pyx_t_4; + int __pyx_t_5; + PyObject *__pyx_t_6 = NULL; + PyObject *__pyx_t_7 = NULL; + PyObject *__pyx_t_8 = NULL; + PyObject *__pyx_t_9 = NULL; + __Pyx_RefNannySetupContext("__pyx_unpickle_Enum__set_state", 0); + + /* "(tree fragment)":10 + * return __pyx_result + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): + * __pyx_result.name = __pyx_state[0] # <<<<<<<<<<<<<< + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): + * __pyx_result.__dict__.update(__pyx_state[1]) + */ + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(1, 10, __pyx_L1_error) + } + __pyx_t_1 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 10, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_GIVEREF(__pyx_t_1); + __Pyx_GOTREF(__pyx_v___pyx_result->name); + __Pyx_DECREF(__pyx_v___pyx_result->name); + __pyx_v___pyx_result->name = __pyx_t_1; + __pyx_t_1 = 0; + + /* "(tree fragment)":11 + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): + * __pyx_result.name = __pyx_state[0] + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< + * __pyx_result.__dict__.update(__pyx_state[1]) + */ + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); + __PYX_ERR(1, 11, __pyx_L1_error) + } + __pyx_t_3 = PyTuple_GET_SIZE(__pyx_v___pyx_state); if (unlikely(__pyx_t_3 == ((Py_ssize_t)-1))) __PYX_ERR(1, 11, __pyx_L1_error) + __pyx_t_4 = ((__pyx_t_3 > 1) != 0); + if (__pyx_t_4) { + } else { + __pyx_t_2 = __pyx_t_4; + goto __pyx_L4_bool_binop_done; + } + __pyx_t_4 = __Pyx_HasAttr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 11, __pyx_L1_error) + __pyx_t_5 = (__pyx_t_4 != 0); + __pyx_t_2 = __pyx_t_5; + __pyx_L4_bool_binop_done:; + if (__pyx_t_2) { + + /* "(tree fragment)":12 + * __pyx_result.name = __pyx_state[0] + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): + * __pyx_result.__dict__.update(__pyx_state[1]) # <<<<<<<<<<<<<< + */ + __pyx_t_6 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v___pyx_result), __pyx_n_s_dict); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_6, __pyx_n_s_update); if (unlikely(!__pyx_t_7)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_7); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + if (unlikely(__pyx_v___pyx_state == Py_None)) { + PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); + __PYX_ERR(1, 12, __pyx_L1_error) + } + __pyx_t_6 = __Pyx_GetItemInt_Tuple(__pyx_v___pyx_state, 1, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_6); + __pyx_t_8 = NULL; + if (CYTHON_UNPACK_METHODS && likely(PyMethod_Check(__pyx_t_7))) { + __pyx_t_8 = PyMethod_GET_SELF(__pyx_t_7); + if (likely(__pyx_t_8)) { + PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); + __Pyx_INCREF(__pyx_t_8); + __Pyx_INCREF(function); + __Pyx_DECREF_SET(__pyx_t_7, function); + } + } + if (!__pyx_t_8) { + __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + __Pyx_GOTREF(__pyx_t_1); + } else { + #if CYTHON_FAST_PYCALL + if (PyFunction_Check(__pyx_t_7)) { + PyObject *__pyx_temp[2] = {__pyx_t_8, __pyx_t_6}; + __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } else + #endif + #if CYTHON_FAST_PYCCALL + if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { + PyObject *__pyx_temp[2] = {__pyx_t_8, __pyx_t_6}; + __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-1, 1+1); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; + } else + #endif + { + __pyx_t_9 = PyTuple_New(1+1); if (unlikely(!__pyx_t_9)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_9); + __Pyx_GIVEREF(__pyx_t_8); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); __pyx_t_8 = NULL; + __Pyx_GIVEREF(__pyx_t_6); + PyTuple_SET_ITEM(__pyx_t_9, 0+1, __pyx_t_6); + __pyx_t_6 = 0; + __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 12, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_1); + __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; + } + } + __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; + __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; + + /* "(tree fragment)":11 + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): + * __pyx_result.name = __pyx_state[0] + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): # <<<<<<<<<<<<<< + * __pyx_result.__dict__.update(__pyx_state[1]) + */ + } + + /* "(tree fragment)":9 + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< + * __pyx_result.name = __pyx_state[0] + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): + */ + + /* function exit code */ + __pyx_r = Py_None; __Pyx_INCREF(Py_None); + goto __pyx_L0; + __pyx_L1_error:; + __Pyx_XDECREF(__pyx_t_1); + __Pyx_XDECREF(__pyx_t_6); + __Pyx_XDECREF(__pyx_t_7); + __Pyx_XDECREF(__pyx_t_8); + __Pyx_XDECREF(__pyx_t_9); + __Pyx_AddTraceback("View.MemoryView.__pyx_unpickle_Enum__set_state", __pyx_clineno, __pyx_lineno, __pyx_filename); + __pyx_r = 0; + __pyx_L0:; + __Pyx_XGIVEREF(__pyx_r); + __Pyx_RefNannyFinishContext(); + return __pyx_r; +} +static struct __pyx_vtabstruct_array __pyx_vtable_array; + +static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { + struct __pyx_array_obj *p; + PyObject *o; + if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { + o = (*t->tp_alloc)(t, 0); + } else { + o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); + } + if (unlikely(!o)) return 0; + p = ((struct __pyx_array_obj *)o); + p->__pyx_vtab = __pyx_vtabptr_array; + p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); + p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); + if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) goto bad; + return o; + bad: + Py_DECREF(o); o = 0; + return NULL; +} + +static void __pyx_tp_dealloc_array(PyObject *o) { + struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; + #if CYTHON_USE_TP_FINALIZE + if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { + if (PyObject_CallFinalizerFromDealloc(o)) return; + } + #endif + { + PyObject *etype, *eval, *etb; + PyErr_Fetch(&etype, &eval, &etb); + ++Py_REFCNT(o); + __pyx_array___dealloc__(o); + --Py_REFCNT(o); + PyErr_Restore(etype, eval, etb); + } + Py_CLEAR(p->mode); + Py_CLEAR(p->_format); + (*Py_TYPE(o)->tp_free)(o); +} +static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { + PyObject *r; + PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; + r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); + Py_DECREF(x); + return r; +} + +static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { + if (v) { + return __pyx_array___setitem__(o, i, v); + } + else { + PyErr_Format(PyExc_NotImplementedError, + "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); + return -1; + } +} + +static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { + PyObject *v = PyObject_GenericGetAttr(o, n); + if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + v = __pyx_array___getattr__(o, n); + } + return v; +} + +static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { + return __pyx_pw_15View_dot_MemoryView_5array_7memview_1__get__(o); +} + +static PyMethodDef __pyx_methods_array[] = { + {"__getattr__", (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, 0}, + {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_array_1__reduce_cython__, METH_NOARGS, 0}, + {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_array_3__setstate_cython__, METH_O, 0}, + {0, 0, 0, 0} +}; + +static struct PyGetSetDef __pyx_getsets_array[] = { + {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, (char *)0, 0}, + {0, 0, 0, 0, 0} +}; + +static PySequenceMethods __pyx_tp_as_sequence_array = { + __pyx_array___len__, /*sq_length*/ + 0, /*sq_concat*/ + 0, /*sq_repeat*/ + __pyx_sq_item_array, /*sq_item*/ + 0, /*sq_slice*/ + 0, /*sq_ass_item*/ + 0, /*sq_ass_slice*/ + 0, /*sq_contains*/ + 0, /*sq_inplace_concat*/ + 0, /*sq_inplace_repeat*/ +}; + +static PyMappingMethods __pyx_tp_as_mapping_array = { + __pyx_array___len__, /*mp_length*/ + __pyx_array___getitem__, /*mp_subscript*/ + __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ +}; + +static PyBufferProcs __pyx_tp_as_buffer_array = { + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getreadbuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getwritebuffer*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getsegcount*/ + #endif + #if PY_MAJOR_VERSION < 3 + 0, /*bf_getcharbuffer*/ + #endif + __pyx_array_getbuffer, /*bf_getbuffer*/ + 0, /*bf_releasebuffer*/ +}; + +static PyTypeObject __pyx_type___pyx_array = { + PyVarObject_HEAD_INIT(0, 0) "utils.array", /*tp_name*/ sizeof(struct __pyx_array_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -16353,8 +19378,9 @@ static PyTypeObject __pyx_type___pyx_array = { 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ - #else - 0, /*reserved*/ + #endif + #if PY_MAJOR_VERSION >= 3 + 0, /*tp_as_async*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ @@ -16415,8 +19441,8 @@ static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, C static void __pyx_tp_dealloc_Enum(PyObject *o) { struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; - #if PY_VERSION_HEX >= 0x030400a1 - if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + #if CYTHON_USE_TP_FINALIZE + if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif @@ -16444,6 +19470,8 @@ static int __pyx_tp_clear_Enum(PyObject *o) { } static PyMethodDef __pyx_methods_Enum[] = { + {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_1__reduce_cython__, METH_NOARGS, 0}, + {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_MemviewEnum_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; @@ -16458,8 +19486,9 @@ static PyTypeObject __pyx_type___pyx_MemviewEnum = { 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ - #else - 0, /*reserved*/ + #endif + #if PY_MAJOR_VERSION >= 3 + 0, /*tp_as_async*/ #endif __pyx_MemviewEnum___repr__, /*tp_repr*/ 0, /*tp_as_number*/ @@ -16520,16 +19549,17 @@ static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject p->_size = Py_None; Py_INCREF(Py_None); p->_array_interface = Py_None; Py_INCREF(Py_None); p->view.obj = NULL; - if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) { - Py_DECREF(o); o = 0; - } + if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) goto bad; return o; + bad: + Py_DECREF(o); o = 0; + return NULL; } static void __pyx_tp_dealloc_memoryview(PyObject *o) { struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; - #if PY_VERSION_HEX >= 0x030400a1 - if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + #if CYTHON_USE_TP_FINALIZE + if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif @@ -16601,39 +19631,39 @@ static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject } static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_memoryview_transpose(o); + return __pyx_pw_15View_dot_MemoryView_10memoryview_1T_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_memoryview__get__base(o); + return __pyx_pw_15View_dot_MemoryView_10memoryview_4base_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_memoryview_get_shape(o); + return __pyx_pw_15View_dot_MemoryView_10memoryview_5shape_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_memoryview_get_strides(o); + return __pyx_pw_15View_dot_MemoryView_10memoryview_7strides_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_memoryview_get_suboffsets(o); + return __pyx_pw_15View_dot_MemoryView_10memoryview_10suboffsets_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_memoryview_get_ndim(o); + return __pyx_pw_15View_dot_MemoryView_10memoryview_4ndim_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_memoryview_get_itemsize(o); + return __pyx_pw_15View_dot_MemoryView_10memoryview_8itemsize_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_memoryview_get_nbytes(o); + return __pyx_pw_15View_dot_MemoryView_10memoryview_6nbytes_1__get__(o); } static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_memoryview_get_size(o); + return __pyx_pw_15View_dot_MemoryView_10memoryview_4size_1__get__(o); } static PyMethodDef __pyx_methods_memoryview[] = { @@ -16641,19 +19671,21 @@ static PyMethodDef __pyx_methods_memoryview[] = { {"is_f_contig", (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, 0}, {"copy", (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, 0}, {"copy_fortran", (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, 0}, + {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_1__reduce_cython__, METH_NOARGS, 0}, + {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryview_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_memoryview[] = { - {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, 0, 0}, - {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, 0, 0}, - {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, 0, 0}, - {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, 0, 0}, - {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, 0, 0}, - {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, 0, 0}, - {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, 0, 0}, - {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, 0, 0}, - {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, 0, 0}, + {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, (char *)0, 0}, + {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, (char *)0, 0}, + {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, (char *)0, 0}, + {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, (char *)0, 0}, + {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, (char *)0, 0}, + {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, (char *)0, 0}, + {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, (char *)0, 0}, + {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, (char *)0, 0}, + {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, (char *)0, 0}, {0, 0, 0, 0, 0} }; @@ -16704,8 +19736,9 @@ static PyTypeObject __pyx_type___pyx_memoryview = { 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ - #else - 0, /*reserved*/ + #endif + #if PY_MAJOR_VERSION >= 3 + 0, /*tp_as_async*/ #endif __pyx_memoryview___repr__, /*tp_repr*/ 0, /*tp_as_number*/ @@ -16764,8 +19797,8 @@ static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyO static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; - #if PY_VERSION_HEX >= 0x030400a1 - if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { + #if CYTHON_USE_TP_FINALIZE + if (unlikely(PyType_HasFeature(Py_TYPE(o), Py_TPFLAGS_HAVE_FINALIZE) && Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif @@ -16805,15 +19838,17 @@ static int __pyx_tp_clear__memoryviewslice(PyObject *o) { } static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { - return __pyx_memoryviewslice__get__base(o); + return __pyx_pw_15View_dot_MemoryView_16_memoryviewslice_4base_1__get__(o); } static PyMethodDef __pyx_methods__memoryviewslice[] = { + {"__reduce_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_1__reduce_cython__, METH_NOARGS, 0}, + {"__setstate_cython__", (PyCFunction)__pyx_pw___pyx_memoryviewslice_3__setstate_cython__, METH_O, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { - {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, 0, 0}, + {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, (char *)0, 0}, {0, 0, 0, 0, 0} }; @@ -16828,8 +19863,9 @@ static PyTypeObject __pyx_type___pyx_memoryviewslice = { 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ - #else - 0, /*reserved*/ + #endif + #if PY_MAJOR_VERSION >= 3 + 0, /*tp_as_async*/ #endif #if CYTHON_COMPILING_IN_PYPY __pyx_memoryview___repr__, /*tp_repr*/ @@ -16887,17 +19923,31 @@ static PyMethodDef __pyx_methods[] = { }; #if PY_MAJOR_VERSION >= 3 +#if CYTHON_PEP489_MULTI_PHASE_INIT +static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ +static int __pyx_pymod_exec_utils(PyObject* module); /*proto*/ +static PyModuleDef_Slot __pyx_moduledef_slots[] = { + {Py_mod_create, (void*)__pyx_pymod_create}, + {Py_mod_exec, (void*)__pyx_pymod_exec_utils}, + {0, NULL} +}; +#endif + static struct PyModuleDef __pyx_moduledef = { - #if PY_VERSION_HEX < 0x03020000 - { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, - #else PyModuleDef_HEAD_INIT, - #endif "utils", 0, /* m_doc */ + #if CYTHON_PEP489_MULTI_PHASE_INIT + 0, /* m_size */ + #else -1, /* m_size */ + #endif __pyx_methods /* m_methods */, + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_moduledef_slots, /* m_slots */ + #else NULL, /* m_reload */ + #endif NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ @@ -16906,15 +19956,15 @@ static struct PyModuleDef __pyx_moduledef = { static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_kp_s_, __pyx_k_, sizeof(__pyx_k_), 0, 0, 1, 0}, - {&__pyx_n_s_AttributeError, __pyx_k_AttributeError, sizeof(__pyx_k_AttributeError), 0, 0, 1, 1}, + {&__pyx_n_s_ASCII, __pyx_k_ASCII, sizeof(__pyx_k_ASCII), 0, 0, 1, 1}, {&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0}, {&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0}, {&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, - {&__pyx_kp_s_Expected_at_least_d_arguments, __pyx_k_Expected_at_least_d_arguments, sizeof(__pyx_k_Expected_at_least_d_arguments), 0, 0, 1, 0}, + {&__pyx_kp_s_Expected_at_least_d_argument_s_g, __pyx_k_Expected_at_least_d_argument_s_g, sizeof(__pyx_k_Expected_at_least_d_argument_s_g), 0, 0, 1, 0}, {&__pyx_kp_s_Function_call_with_ambiguous_arg, __pyx_k_Function_call_with_ambiguous_arg, sizeof(__pyx_k_Function_call_with_ambiguous_arg), 0, 0, 1, 0}, - {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, + {&__pyx_kp_s_Incompatible_checksums_s_vs_0xb0, __pyx_k_Incompatible_checksums_s_vs_0xb0, sizeof(__pyx_k_Incompatible_checksums_s_vs_0xb0), 0, 0, 1, 0}, {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, @@ -16925,34 +19975,43 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_kp_s_No_matching_signature_found, __pyx_k_No_matching_signature_found, sizeof(__pyx_k_No_matching_signature_found), 0, 0, 1, 0}, {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, + {&__pyx_n_s_PickleError, __pyx_k_PickleError, sizeof(__pyx_k_PickleError), 0, 0, 1, 1}, {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, + {&__pyx_n_s_View_MemoryView, __pyx_k_View_MemoryView, sizeof(__pyx_k_View_MemoryView), 0, 0, 1, 1}, {&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1}, {&__pyx_n_s_Y, __pyx_k_Y, sizeof(__pyx_k_Y), 0, 0, 1, 1}, + {&__pyx_kp_s__2, __pyx_k__2, sizeof(__pyx_k__2), 0, 0, 1, 0}, {&__pyx_kp_s__3, __pyx_k__3, sizeof(__pyx_k__3), 0, 0, 1, 0}, + {&__pyx_kp_s__5, __pyx_k__5, sizeof(__pyx_k__5), 0, 0, 1, 0}, {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, {&__pyx_n_s_args, __pyx_k_args, sizeof(__pyx_k_args), 0, 0, 1, 1}, {&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1}, + {&__pyx_n_s_byteorder, __pyx_k_byteorder, sizeof(__pyx_k_byteorder), 0, 0, 1, 1}, {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, {&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1}, {&__pyx_n_s_char, __pyx_k_char, sizeof(__pyx_k_char), 0, 0, 1, 1}, {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, {&__pyx_n_s_class_weight, __pyx_k_class_weight, sizeof(__pyx_k_class_weight), 0, 0, 1, 1}, + {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, {&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0}, {&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0}, {&__pyx_n_s_crammer_singer_joint_feature, __pyx_k_crammer_singer_joint_feature, sizeof(__pyx_k_crammer_singer_joint_feature), 0, 0, 1, 1}, {&__pyx_n_s_defaults, __pyx_k_defaults, sizeof(__pyx_k_defaults), 0, 0, 1, 1}, + {&__pyx_n_s_dict, __pyx_k_dict, sizeof(__pyx_k_dict), 0, 0, 1, 1}, {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, {&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1}, + {&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 0, 0, 1, 1}, {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, {&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1}, + {&__pyx_n_s_f_contiguous, __pyx_k_f_contiguous, sizeof(__pyx_k_f_contiguous), 0, 0, 1, 1}, {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, {&__pyx_n_u_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 1, 0, 1}, + {&__pyx_n_s_getstate, __pyx_k_getstate, sizeof(__pyx_k_getstate), 0, 0, 1, 1}, {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, - {&__pyx_kp_s_home_andy_checkout_pystruct_blu, __pyx_k_home_andy_checkout_pystruct_blu, sizeof(__pyx_k_home_andy_checkout_pystruct_blu), 0, 0, 1, 0}, {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, @@ -16971,17 +20030,30 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_n_states, __pyx_k_n_states, sizeof(__pyx_k_n_states), 0, 0, 1, 1}, {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, - {&__pyx_n_s_ndarray, __pyx_k_ndarray, sizeof(__pyx_k_ndarray), 0, 0, 1, 1}, {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, + {&__pyx_n_s_new, __pyx_k_new, sizeof(__pyx_k_new), 0, 0, 1, 1}, + {&__pyx_kp_s_no_default___reduce___due_to_non, __pyx_k_no_default___reduce___due_to_non, sizeof(__pyx_k_no_default___reduce___due_to_non), 0, 0, 1, 0}, {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, - {&__pyx_n_s_ord, __pyx_k_ord, sizeof(__pyx_k_ord), 0, 0, 1, 1}, {&__pyx_n_s_out, __pyx_k_out, sizeof(__pyx_k_out), 0, 0, 1, 1}, {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, + {&__pyx_n_s_pickle, __pyx_k_pickle, sizeof(__pyx_k_pickle), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_PickleError, __pyx_k_pyx_PickleError, sizeof(__pyx_k_pyx_PickleError), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_checksum, __pyx_k_pyx_checksum, sizeof(__pyx_k_pyx_checksum), 0, 0, 1, 1}, {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_result, __pyx_k_pyx_result, sizeof(__pyx_k_pyx_result), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_state, __pyx_k_pyx_state, sizeof(__pyx_k_pyx_state), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_type, __pyx_k_pyx_type, sizeof(__pyx_k_pyx_type), 0, 0, 1, 1}, + {&__pyx_n_s_pyx_unpickle_Enum, __pyx_k_pyx_unpickle_Enum, sizeof(__pyx_k_pyx_unpickle_Enum), 0, 0, 1, 1}, {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, + {&__pyx_n_s_reduce, __pyx_k_reduce, sizeof(__pyx_k_reduce), 0, 0, 1, 1}, + {&__pyx_n_s_reduce_cython, __pyx_k_reduce_cython, sizeof(__pyx_k_reduce_cython), 0, 0, 1, 1}, + {&__pyx_n_s_reduce_ex, __pyx_k_reduce_ex, sizeof(__pyx_k_reduce_ex), 0, 0, 1, 1}, + {&__pyx_n_s_reversed, __pyx_k_reversed, sizeof(__pyx_k_reversed), 0, 0, 1, 1}, {&__pyx_n_s_s, __pyx_k_s, sizeof(__pyx_k_s), 0, 0, 1, 1}, + {&__pyx_n_s_setstate, __pyx_k_setstate, sizeof(__pyx_k_setstate), 0, 0, 1, 1}, + {&__pyx_n_s_setstate_cython, __pyx_k_setstate_cython, sizeof(__pyx_k_setstate_cython), 0, 0, 1, 1}, {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, {&__pyx_n_s_short, __pyx_k_short, sizeof(__pyx_k_short), 0, 0, 1, 1}, {&__pyx_n_s_signatures, __pyx_k_signatures, sizeof(__pyx_k_signatures), 0, 0, 1, 1}, @@ -16993,6 +20065,8 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0}, {&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0}, {&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0}, + {&__pyx_n_s_strides, __pyx_k_strides, sizeof(__pyx_k_strides), 0, 0, 1, 1}, + {&__pyx_kp_s_stringsource, __pyx_k_stringsource, sizeof(__pyx_k_stringsource), 0, 0, 1, 0}, {&__pyx_n_s_strip, __pyx_k_strip, sizeof(__pyx_k_strip), 0, 0, 1, 1}, {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, @@ -17002,30 +20076,24 @@ static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, {&__pyx_kp_s_unsigned_char, __pyx_k_unsigned_char, sizeof(__pyx_k_unsigned_char), 0, 0, 1, 0}, {&__pyx_kp_s_unsigned_int, __pyx_k_unsigned_int, sizeof(__pyx_k_unsigned_int), 0, 0, 1, 0}, + {&__pyx_n_s_update, __pyx_k_update, sizeof(__pyx_k_update), 0, 0, 1, 1}, {&__pyx_n_s_utils, __pyx_k_utils, sizeof(__pyx_k_utils), 0, 0, 1, 1}, - {&__pyx_n_s_xrange, __pyx_k_xrange, sizeof(__pyx_k_xrange), 0, 0, 1, 1}, + {&__pyx_kp_s_utils_pyx, __pyx_k_utils_pyx, sizeof(__pyx_k_utils_pyx), 0, 0, 1, 0}, {&__pyx_n_s_y, __pyx_k_y, sizeof(__pyx_k_y), 0, 0, 1, 1}, {&__pyx_n_s_zip, __pyx_k_zip, sizeof(__pyx_k_zip), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { - __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_AttributeError = __Pyx_GetBuiltinName(__pyx_n_s_AttributeError); if (!__pyx_builtin_AttributeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ord = __Pyx_GetBuiltinName(__pyx_n_s_ord); if (!__pyx_builtin_ord) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_zip = __Pyx_GetBuiltinName(__pyx_n_s_zip); if (!__pyx_builtin_zip) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #if PY_MAJOR_VERSION >= 3 - __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #else - __pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - #endif - __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 24; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 789; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_builtin_zip = __Pyx_GetBuiltinName(__pyx_n_s_zip); if (!__pyx_builtin_zip) __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_builtin_reversed = __Pyx_GetBuiltinName(__pyx_n_s_reversed); if (!__pyx_builtin_reversed) __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 14, __pyx_L1_error) + __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(1, 131, __pyx_L1_error) + __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(1, 146, __pyx_L1_error) + __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) __PYX_ERR(1, 149, __pyx_L1_error) + __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) __PYX_ERR(1, 398, __pyx_L1_error) + __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) __PYX_ERR(1, 601, __pyx_L1_error) + __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) __PYX_ERR(1, 820, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; @@ -17040,20 +20108,20 @@ static int __Pyx_InitCachedConstants(void) { * * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): # <<<<<<<<<<<<<< * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): */ - __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__2); - __Pyx_GIVEREF(__pyx_tuple__2); - __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s__3); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s__3); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); - __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_s_No_matching_signature_found); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__5); - __Pyx_GIVEREF(__pyx_tuple__5); - __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_Function_call_with_ambiguous_arg); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s__5); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); + __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_No_matching_signature_found); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__7); + __Pyx_GIVEREF(__pyx_tuple__7); + __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_Function_call_with_ambiguous_arg); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__8); + __Pyx_GIVEREF(__pyx_tuple__8); /* "utils.pyx":21 * out[y, j] += X[i, j] @@ -17062,151 +20130,233 @@ static int __Pyx_InitCachedConstants(void) { * cdef int i * cdef int n_states = unary_potentials.shape[1] */ - __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__7); - __Pyx_GIVEREF(__pyx_tuple__7); - __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s__3); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__8); - __Pyx_GIVEREF(__pyx_tuple__8); - __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_No_matching_signature_found); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s__3); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__9); __Pyx_GIVEREF(__pyx_tuple__9); - __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_Function_call_with_ambiguous_arg); if (unlikely(!__pyx_tuple__10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s__5); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__10); __Pyx_GIVEREF(__pyx_tuple__10); + __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_No_matching_signature_found); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__11); + __Pyx_GIVEREF(__pyx_tuple__11); + __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_Function_call_with_ambiguous_arg); if (unlikely(!__pyx_tuple__12)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__12); + __Pyx_GIVEREF(__pyx_tuple__12); - /* "View.MemoryView":127 + /* "View.MemoryView":131 * * if not self.ndim: * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< * * if itemsize <= 0: */ - __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__11); - __Pyx_GIVEREF(__pyx_tuple__11); + __pyx_tuple__13 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(1, 131, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__13); + __Pyx_GIVEREF(__pyx_tuple__13); - /* "View.MemoryView":130 + /* "View.MemoryView":134 * * if itemsize <= 0: * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< * - * if isinstance(format, unicode): + * if not isinstance(format, bytes): */ - __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__12); - __Pyx_GIVEREF(__pyx_tuple__12); + __pyx_tuple__14 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__14)) __PYX_ERR(1, 134, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__14); + __Pyx_GIVEREF(__pyx_tuple__14); - /* "View.MemoryView":142 + /* "View.MemoryView":137 * - * if not self._shape: + * if not isinstance(format, bytes): + * format = format.encode('ASCII') # <<<<<<<<<<<<<< + * self._format = format # keep a reference to the byte string + * self.format = self._format + */ + __pyx_tuple__15 = PyTuple_Pack(1, __pyx_n_s_ASCII); if (unlikely(!__pyx_tuple__15)) __PYX_ERR(1, 137, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__15); + __Pyx_GIVEREF(__pyx_tuple__15); + + /* "View.MemoryView":146 + * + * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ - __pyx_tuple__13 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__13); - __Pyx_GIVEREF(__pyx_tuple__13); + __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__16)) __PYX_ERR(1, 146, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__16); + __Pyx_GIVEREF(__pyx_tuple__16); - /* "View.MemoryView":170 + /* "View.MemoryView":174 * self.data = malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ - __pyx_tuple__14 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__14)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__14); - __Pyx_GIVEREF(__pyx_tuple__14); + __pyx_tuple__17 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__17)) __PYX_ERR(1, 174, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__17); + __Pyx_GIVEREF(__pyx_tuple__17); - /* "View.MemoryView":186 + /* "View.MemoryView":190 * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< * info.buf = self.data * info.len = self.len */ - __pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__15); - __Pyx_GIVEREF(__pyx_tuple__15); + __pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__18)) __PYX_ERR(1, 190, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__18); + __Pyx_GIVEREF(__pyx_tuple__18); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__19)) __PYX_ERR(1, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__19); + __Pyx_GIVEREF(__pyx_tuple__19); + + /* "(tree fragment)":4 + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + */ + __pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__20)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__20); + __Pyx_GIVEREF(__pyx_tuple__20); - /* "View.MemoryView":445 + /* "View.MemoryView":486 * result = struct.unpack(self.view.format, bytesitem) * except struct.error: * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< * else: * if len(self.view.format) == 1: */ - __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__16)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__16); - __Pyx_GIVEREF(__pyx_tuple__16); + __pyx_tuple__21 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__21)) __PYX_ERR(1, 486, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__21); + __Pyx_GIVEREF(__pyx_tuple__21); - /* "View.MemoryView":521 - * if self.view.strides == NULL: + /* "View.MemoryView":558 + * if self.view.strides == NULL: * - * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< + * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< * - * return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) + * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) */ - __pyx_tuple__17 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__17)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__17); - __Pyx_GIVEREF(__pyx_tuple__17); + __pyx_tuple__22 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__22)) __PYX_ERR(1, 558, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__22); + __Pyx_GIVEREF(__pyx_tuple__22); + + /* "View.MemoryView":565 + * def suboffsets(self): + * if self.view.suboffsets == NULL: + * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< + * + * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) + */ + __pyx_tuple__23 = PyTuple_New(1); if (unlikely(!__pyx_tuple__23)) __PYX_ERR(1, 565, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__23); + __Pyx_INCREF(__pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_int_neg_1); + PyTuple_SET_ITEM(__pyx_tuple__23, 0, __pyx_int_neg_1); + __Pyx_GIVEREF(__pyx_tuple__23); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + __pyx_tuple__24 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__24)) __PYX_ERR(1, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__24); + __Pyx_GIVEREF(__pyx_tuple__24); + + /* "(tree fragment)":4 + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + */ + __pyx_tuple__25 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__25)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__25); + __Pyx_GIVEREF(__pyx_tuple__25); - /* "View.MemoryView":638 + /* "View.MemoryView":670 * if item is Ellipsis: * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< * seen_ellipsis = True * else: */ - __pyx_slice__18 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__18)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_slice__18); - __Pyx_GIVEREF(__pyx_slice__18); + __pyx_slice__26 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__26)) __PYX_ERR(1, 670, __pyx_L1_error) + __Pyx_GOTREF(__pyx_slice__26); + __Pyx_GIVEREF(__pyx_slice__26); - /* "View.MemoryView":641 + /* "View.MemoryView":673 * seen_ellipsis = True * else: * result.append(slice(None)) # <<<<<<<<<<<<<< * have_slices = True * else: */ - __pyx_slice__19 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__19)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_slice__19); - __Pyx_GIVEREF(__pyx_slice__19); + __pyx_slice__27 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__27)) __PYX_ERR(1, 673, __pyx_L1_error) + __Pyx_GOTREF(__pyx_slice__27); + __Pyx_GIVEREF(__pyx_slice__27); - /* "View.MemoryView":652 + /* "View.MemoryView":684 * nslices = ndim - len(result) * if nslices: * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< * * return have_slices or nslices, tuple(result) */ - __pyx_slice__20 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__20)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_slice__20); - __Pyx_GIVEREF(__pyx_slice__20); + __pyx_slice__28 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__28)) __PYX_ERR(1, 684, __pyx_L1_error) + __Pyx_GOTREF(__pyx_slice__28); + __Pyx_GIVEREF(__pyx_slice__28); - /* "View.MemoryView":660 - * for i in range(ndim): - * if suboffsets[i] >= 0: + /* "View.MemoryView":691 + * for suboffset in suboffsets[:ndim]: + * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< * * */ - __pyx_tuple__21 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__21)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__21); - __Pyx_GIVEREF(__pyx_tuple__21); + __pyx_tuple__29 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__29)) __PYX_ERR(1, 691, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__29); + __Pyx_GIVEREF(__pyx_tuple__29); + + /* "(tree fragment)":2 + * def __reduce_cython__(self): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + */ + __pyx_tuple__30 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__30)) __PYX_ERR(1, 2, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__30); + __Pyx_GIVEREF(__pyx_tuple__30); + + /* "(tree fragment)":4 + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") + * def __setstate_cython__(self, __pyx_state): + * raise TypeError("no default __reduce__ due to non-trivial __cinit__") # <<<<<<<<<<<<<< + */ + __pyx_tuple__31 = PyTuple_Pack(1, __pyx_kp_s_no_default___reduce___due_to_non); if (unlikely(!__pyx_tuple__31)) __PYX_ERR(1, 4, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__31); + __Pyx_GIVEREF(__pyx_tuple__31); /* "utils.pyx":14 * cython.uint * * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): # <<<<<<<<<<<<<< * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): */ - __pyx_tuple__22 = PyTuple_Pack(6, __pyx_n_s_X, __pyx_n_s_Y, __pyx_n_s_out, __pyx_n_s_y, __pyx_n_s_i, __pyx_n_s_j); if (unlikely(!__pyx_tuple__22)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__22); - __Pyx_GIVEREF(__pyx_tuple__22); - __pyx_codeobj__23 = (PyObject*)__Pyx_PyCode_New(3, 0, 6, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__22, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_andy_checkout_pystruct_blu, __pyx_n_s_crammer_singer_joint_feature, 14, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__23)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_tuple__32 = PyTuple_Pack(6, __pyx_n_s_X, __pyx_n_s_Y, __pyx_n_s_out, __pyx_n_s_y, __pyx_n_s_i, __pyx_n_s_j); if (unlikely(!__pyx_tuple__32)) __PYX_ERR(0, 14, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__32); + __Pyx_GIVEREF(__pyx_tuple__32); + __pyx_codeobj__33 = (PyObject*)__Pyx_PyCode_New(3, 0, 6, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__32, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_utils_pyx, __pyx_n_s_crammer_singer_joint_feature, 14, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__33)) __PYX_ERR(0, 14, __pyx_L1_error) /* "utils.pyx":21 * out[y, j] += X[i, j] @@ -17215,65 +20365,75 @@ static int __Pyx_InitCachedConstants(void) { * cdef int i * cdef int n_states = unary_potentials.shape[1] */ - __pyx_tuple__24 = PyTuple_Pack(6, __pyx_n_s_unary_potentials, __pyx_n_s_y, __pyx_n_s_class_weight, __pyx_n_s_i, __pyx_n_s_n_states, __pyx_n_s_s); if (unlikely(!__pyx_tuple__24)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__24); - __Pyx_GIVEREF(__pyx_tuple__24); - __pyx_codeobj__25 = (PyObject*)__Pyx_PyCode_New(3, 0, 6, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__24, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_andy_checkout_pystruct_blu, __pyx_n_s_loss_augment_unaries, 21, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_tuple__34 = PyTuple_Pack(6, __pyx_n_s_unary_potentials, __pyx_n_s_y, __pyx_n_s_class_weight, __pyx_n_s_i, __pyx_n_s_n_states, __pyx_n_s_s); if (unlikely(!__pyx_tuple__34)) __PYX_ERR(0, 21, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__34); + __Pyx_GIVEREF(__pyx_tuple__34); + __pyx_codeobj__35 = (PyObject*)__Pyx_PyCode_New(3, 0, 6, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__34, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_utils_pyx, __pyx_n_s_loss_augment_unaries, 21, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__35)) __PYX_ERR(0, 21, __pyx_L1_error) - /* "View.MemoryView":276 + /* "View.MemoryView":284 * return self.name * * cdef generic = Enum("") # <<<<<<<<<<<<<< * cdef strided = Enum("") # default * cdef indirect = Enum("") */ - __pyx_tuple__26 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__26)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__26); - __Pyx_GIVEREF(__pyx_tuple__26); + __pyx_tuple__36 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__36)) __PYX_ERR(1, 284, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__36); + __Pyx_GIVEREF(__pyx_tuple__36); - /* "View.MemoryView":277 + /* "View.MemoryView":285 * * cdef generic = Enum("") * cdef strided = Enum("") # default # <<<<<<<<<<<<<< * cdef indirect = Enum("") * */ - __pyx_tuple__27 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__27)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__27); - __Pyx_GIVEREF(__pyx_tuple__27); + __pyx_tuple__37 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__37)) __PYX_ERR(1, 285, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__37); + __Pyx_GIVEREF(__pyx_tuple__37); - /* "View.MemoryView":278 + /* "View.MemoryView":286 * cdef generic = Enum("") * cdef strided = Enum("") # default * cdef indirect = Enum("") # <<<<<<<<<<<<<< * * */ - __pyx_tuple__28 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__28)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__28); - __Pyx_GIVEREF(__pyx_tuple__28); + __pyx_tuple__38 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__38)) __PYX_ERR(1, 286, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__38); + __Pyx_GIVEREF(__pyx_tuple__38); - /* "View.MemoryView":281 + /* "View.MemoryView":289 * * * cdef contiguous = Enum("") # <<<<<<<<<<<<<< * cdef indirect_contiguous = Enum("") * */ - __pyx_tuple__29 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__29)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__29); - __Pyx_GIVEREF(__pyx_tuple__29); + __pyx_tuple__39 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__39)) __PYX_ERR(1, 289, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__39); + __Pyx_GIVEREF(__pyx_tuple__39); - /* "View.MemoryView":282 + /* "View.MemoryView":290 * * cdef contiguous = Enum("") * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< * * */ - __pyx_tuple__30 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__30)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __Pyx_GOTREF(__pyx_tuple__30); - __Pyx_GIVEREF(__pyx_tuple__30); + __pyx_tuple__40 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__40)) __PYX_ERR(1, 290, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__40); + __Pyx_GIVEREF(__pyx_tuple__40); + + /* "(tree fragment)":1 + * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< + * if __pyx_checksum != 0xb068931: + * from pickle import PickleError as __pyx_PickleError + */ + __pyx_tuple__41 = PyTuple_Pack(5, __pyx_n_s_pyx_type, __pyx_n_s_pyx_checksum, __pyx_n_s_pyx_state, __pyx_n_s_pyx_PickleError, __pyx_n_s_pyx_result); if (unlikely(!__pyx_tuple__41)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_tuple__41); + __Pyx_GIVEREF(__pyx_tuple__41); + __pyx_codeobj__42 = (PyObject*)__Pyx_PyCode_New(3, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__41, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_stringsource, __pyx_n_s_pyx_unpickle_Enum, 1, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__42)) __PYX_ERR(1, 1, __pyx_L1_error) __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; @@ -17282,10 +20442,12 @@ static int __Pyx_InitCachedConstants(void) { } static int __Pyx_InitGlobals(void) { - if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; - __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); + __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_3 = PyInt_FromLong(3); if (unlikely(!__pyx_int_3)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_184977713 = PyInt_FromLong(184977713L); if (unlikely(!__pyx_int_184977713)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) __PYX_ERR(0, 1, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; @@ -17297,6 +20459,47 @@ PyMODINIT_FUNC initutils(void) #else PyMODINIT_FUNC PyInit_utils(void); /*proto*/ PyMODINIT_FUNC PyInit_utils(void) +#if CYTHON_PEP489_MULTI_PHASE_INIT +{ + return PyModuleDef_Init(&__pyx_moduledef); +} +static int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name) { + PyObject *value = PyObject_GetAttrString(spec, from_name); + int result = 0; + if (likely(value)) { + result = PyDict_SetItemString(moddict, to_name, value); + Py_DECREF(value); + } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Clear(); + } else { + result = -1; + } + return result; +} +static PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { + PyObject *module = NULL, *moddict, *modname; + if (__pyx_m) + return __Pyx_NewRef(__pyx_m); + modname = PyObject_GetAttrString(spec, "name"); + if (unlikely(!modname)) goto bad; + module = PyModule_NewObject(modname); + Py_DECREF(modname); + if (unlikely(!module)) goto bad; + moddict = PyModule_GetDict(module); + if (unlikely(!moddict)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__") < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__") < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__") < 0)) goto bad; + if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__") < 0)) goto bad; + return module; +bad: + Py_XDECREF(module); + return NULL; +} + + +static int __pyx_pymod_exec_utils(PyObject *__pyx_pyinit_module) +#endif #endif { PyObject *__pyx_t_1 = NULL; @@ -17304,10 +20507,11 @@ PyMODINIT_FUNC PyInit_utils(void) PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; - int __pyx_lineno = 0; - const char *__pyx_filename = NULL; - int __pyx_clineno = 0; + static PyThread_type_lock __pyx_t_6[8]; __Pyx_RefNannyDeclarations + #if CYTHON_PEP489_MULTI_PHASE_INIT + if (__pyx_m && __pyx_m == __pyx_pyinit_module) return 0; + #endif #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { @@ -17318,17 +20522,27 @@ PyMODINIT_FUNC PyInit_utils(void) } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_utils(void)", 0); - if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pyx_CyFunction_USED - if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED - if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_Coroutine_USED + if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED - if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_AsyncGen_USED + if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + #ifdef __Pyx_StopAsyncIteration_USED + if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ @@ -17338,39 +20552,45 @@ PyMODINIT_FUNC PyInit_utils(void) #endif #endif /*--- Module creation code ---*/ + #if CYTHON_PEP489_MULTI_PHASE_INIT + __pyx_m = __pyx_pyinit_module; + Py_INCREF(__pyx_m); + #else #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("utils", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif - if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} - __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) + #endif + __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_d); - __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) + __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif - if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); /*--- Initialize various global constants etc. ---*/ - if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) - if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_utils) { - if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; + if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } #if PY_MAJOR_VERSION >= 3 { - PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "utils")) { - if (unlikely(PyDict_SetItemString(modules, "utils", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (unlikely(PyDict_SetItemString(modules, "utils", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) } } #endif /*--- Builtin init code ---*/ - if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ - if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global init code ---*/ generic = Py_None; Py_INCREF(Py_None); strided = Py_None; Py_INCREF(Py_None); @@ -17380,11 +20600,16 @@ PyMODINIT_FUNC PyInit_utils(void) /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ - if (PyType_Ready(&__pyx_type___pyx_array) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_vtabptr_array = &__pyx_vtable_array; + __pyx_vtable_array.get_memview = (PyObject *(*)(struct __pyx_array_obj *))__pyx_array_get_memview; + if (PyType_Ready(&__pyx_type___pyx_array) < 0) __PYX_ERR(1, 103, __pyx_L1_error) __pyx_type___pyx_array.tp_print = 0; + if (__Pyx_SetVtable(__pyx_type___pyx_array.tp_dict, __pyx_vtabptr_array) < 0) __PYX_ERR(1, 103, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_array) < 0) __PYX_ERR(1, 103, __pyx_L1_error) __pyx_array_type = &__pyx_type___pyx_array; - if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 269; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(1, 277, __pyx_L1_error) __pyx_type___pyx_MemviewEnum.tp_print = 0; + if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_MemviewEnum) < 0) __PYX_ERR(1, 277, __pyx_L1_error) __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; @@ -17394,74 +20619,79 @@ PyMODINIT_FUNC PyInit_utils(void) __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; - if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(1, 328, __pyx_L1_error) __pyx_type___pyx_memoryview.tp_print = 0; - if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) __PYX_ERR(1, 328, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryview) < 0) __PYX_ERR(1, 328, __pyx_L1_error) __pyx_memoryview_type = &__pyx_type___pyx_memoryview; __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; - if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(1, 953, __pyx_L1_error) __pyx_type___pyx_memoryviewslice.tp_print = 0; - if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 922; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) __PYX_ERR(1, 953, __pyx_L1_error) + if (__Pyx_setup_reduce((PyObject*)&__pyx_type___pyx_memoryviewslice) < 0) __PYX_ERR(1, 953, __pyx_L1_error) __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; /*--- Type import code ---*/ /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ + #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) + if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) + #endif /* "utils.pyx":14 * cython.uint * * def crammer_singer_joint_feature(double[:,:] X, some_int[:] Y, double[:, :] out): # <<<<<<<<<<<<<< * cdef int y, i - * for i in xrange(X.shape[0]): + * for i in range(X.shape[0]): */ - __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_1 = __Pyx_PyDict_NewPresized(7); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); - __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_0__pyx_mdef_5utils_5crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__23)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_0__pyx_mdef_5utils_5crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_short, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_short, __pyx_t_2) < 0) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_1__pyx_mdef_5utils_7crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__23)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_1__pyx_mdef_5utils_7crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_int, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_int, __pyx_t_2) < 0) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_2__pyx_mdef_5utils_9crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__23)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_2__pyx_mdef_5utils_9crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_long, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_long, __pyx_t_2) < 0) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_3__pyx_mdef_5utils_11crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__23)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_3__pyx_mdef_5utils_11crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_1, __pyx_kp_s_long_long, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, __pyx_kp_s_long_long, __pyx_t_2) < 0) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_4__pyx_mdef_5utils_13crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__23)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_4__pyx_mdef_5utils_13crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_1, __pyx_kp_s_unsigned_char, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, __pyx_kp_s_unsigned_char, __pyx_t_2) < 0) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_5__pyx_mdef_5utils_15crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__23)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_5__pyx_mdef_5utils_15crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_char, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_char, __pyx_t_2) < 0) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_6__pyx_mdef_5utils_17crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__23)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_6__pyx_mdef_5utils_17crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_1, __pyx_kp_s_unsigned_int, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_1, __pyx_kp_s_unsigned_int, __pyx_t_2) < 0) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; - __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_mdef_5utils_1crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__23)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_mdef_5utils_1crammer_singer_joint_feature, 0, __pyx_n_s_crammer_singer_joint_feature, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); ((__pyx_FusedFunctionObject *) __pyx_t_2)->__signatures__ = __pyx_t_1; __Pyx_GIVEREF(__pyx_t_1); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_crammer_singer_joint_feature, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_crammer_singer_joint_feature, __pyx_t_2) < 0) __PYX_ERR(0, 14, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "utils.pyx":21 @@ -17471,49 +20701,49 @@ PyMODINIT_FUNC PyInit_utils(void) * cdef int i * cdef int n_states = unary_potentials.shape[1] */ - __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_3 = __Pyx_PyDict_NewPresized(7); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); - __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_0__pyx_mdef_5utils_21loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__25)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_0__pyx_mdef_5utils_21loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_short, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_short, __pyx_t_4) < 0) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_1__pyx_mdef_5utils_23loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__25)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_1__pyx_mdef_5utils_23loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_int, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_int, __pyx_t_4) < 0) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_2__pyx_mdef_5utils_25loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__25)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_2__pyx_mdef_5utils_25loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_long, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_long, __pyx_t_4) < 0) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_3__pyx_mdef_5utils_27loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__25)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_3__pyx_mdef_5utils_27loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_3, __pyx_kp_s_long_long, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, __pyx_kp_s_long_long, __pyx_t_4) < 0) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_4__pyx_mdef_5utils_29loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__25)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_4__pyx_mdef_5utils_29loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_3, __pyx_kp_s_unsigned_char, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, __pyx_kp_s_unsigned_char, __pyx_t_4) < 0) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_5__pyx_mdef_5utils_31loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__25)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_5__pyx_mdef_5utils_31loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_char, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_char, __pyx_t_4) < 0) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_6__pyx_mdef_5utils_33loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__25)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_6__pyx_mdef_5utils_33loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple); - if (PyDict_SetItem(__pyx_t_3, __pyx_kp_s_unsigned_int, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_t_3, __pyx_kp_s_unsigned_int, __pyx_t_4) < 0) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; - __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_mdef_5utils_3loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__25)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_mdef_5utils_3loss_augment_unaries, 0, __pyx_n_s_loss_augment_unaries, NULL, __pyx_n_s_utils, __pyx_d, ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple); ((__pyx_FusedFunctionObject *) __pyx_t_4)->__signatures__ = __pyx_t_3; __Pyx_GIVEREF(__pyx_t_3); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_loss_augment_unaries, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_loss_augment_unaries, __pyx_t_4) < 0) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; /* "utils.pyx":1 @@ -17521,125 +20751,162 @@ PyMODINIT_FUNC PyInit_utils(void) * # cython: wraparound=False * cimport cython */ - __pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); - if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_5) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; - /* "View.MemoryView":203 + /* "View.MemoryView":207 * info.obj = self * * __pyx_getbuffer = capsule( &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * def __dealloc__(array self): */ - __pyx_t_5 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 207, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); - if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem((PyObject *)__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_5) < 0) __PYX_ERR(1, 207, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; PyType_Modified(__pyx_array_type); - /* "View.MemoryView":276 + /* "View.MemoryView":284 * return self.name * * cdef generic = Enum("") # <<<<<<<<<<<<<< * cdef strided = Enum("") # default * cdef indirect = Enum("") */ - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__26, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__36, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 284, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_XGOTREF(generic); __Pyx_DECREF_SET(generic, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; - /* "View.MemoryView":277 + /* "View.MemoryView":285 * * cdef generic = Enum("") * cdef strided = Enum("") # default # <<<<<<<<<<<<<< * cdef indirect = Enum("") * */ - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__27, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__37, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 285, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_XGOTREF(strided); __Pyx_DECREF_SET(strided, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; - /* "View.MemoryView":278 + /* "View.MemoryView":286 * cdef generic = Enum("") * cdef strided = Enum("") # default * cdef indirect = Enum("") # <<<<<<<<<<<<<< * * */ - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__28, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__38, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 286, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_XGOTREF(indirect); __Pyx_DECREF_SET(indirect, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; - /* "View.MemoryView":281 + /* "View.MemoryView":289 * * * cdef contiguous = Enum("") # <<<<<<<<<<<<<< * cdef indirect_contiguous = Enum("") * */ - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__29, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__39, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 289, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_XGOTREF(contiguous); __Pyx_DECREF_SET(contiguous, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; - /* "View.MemoryView":282 + /* "View.MemoryView":290 * * cdef contiguous = Enum("") * cdef indirect_contiguous = Enum("") # <<<<<<<<<<<<<< * * */ - __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__30, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)__pyx_MemviewEnum_type), __pyx_tuple__40, NULL); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 290, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_XGOTREF(indirect_contiguous); __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = 0; - /* "View.MemoryView":496 + /* "View.MemoryView":314 + * + * DEF THREAD_LOCKS_PREALLOCATED = 8 + * cdef int __pyx_memoryview_thread_locks_used = 0 # <<<<<<<<<<<<<< + * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ + * PyThread_allocate_lock(), + */ + __pyx_memoryview_thread_locks_used = 0; + + /* "View.MemoryView":315 + * DEF THREAD_LOCKS_PREALLOCATED = 8 + * cdef int __pyx_memoryview_thread_locks_used = 0 + * cdef PyThread_type_lock[THREAD_LOCKS_PREALLOCATED] __pyx_memoryview_thread_locks = [ # <<<<<<<<<<<<<< + * PyThread_allocate_lock(), + * PyThread_allocate_lock(), + */ + __pyx_t_6[0] = PyThread_allocate_lock(); + __pyx_t_6[1] = PyThread_allocate_lock(); + __pyx_t_6[2] = PyThread_allocate_lock(); + __pyx_t_6[3] = PyThread_allocate_lock(); + __pyx_t_6[4] = PyThread_allocate_lock(); + __pyx_t_6[5] = PyThread_allocate_lock(); + __pyx_t_6[6] = PyThread_allocate_lock(); + __pyx_t_6[7] = PyThread_allocate_lock(); + memcpy(&(__pyx_memoryview_thread_locks[0]), __pyx_t_6, sizeof(__pyx_memoryview_thread_locks[0]) * (8)); + + /* "View.MemoryView":537 * info.obj = self * * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ - __pyx_t_5 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 537, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); - if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem((PyObject *)__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_5) < 0) __PYX_ERR(1, 537, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; PyType_Modified(__pyx_memoryview_type); - /* "View.MemoryView":953 - * return self.from_object + /* "View.MemoryView":983 + * return self.from_object * * __pyx_getbuffer = capsule( &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ - __pyx_t_5 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 953; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + __pyx_t_5 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), ((char *)"getbuffer(obj, view, flags)")); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 983, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); - if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 953; __pyx_clineno = __LINE__; goto __pyx_L1_error;} + if (PyDict_SetItem((PyObject *)__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_5) < 0) __PYX_ERR(1, 983, __pyx_L1_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; PyType_Modified(__pyx_memoryviewslice_type); - /* "__pyxutil":2 - * - * cdef extern from *: # <<<<<<<<<<<<<< - * void __pyx_PyErr_Clear "PyErr_Clear" () - * __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_short(object) + /* "(tree fragment)":1 + * def __pyx_unpickle_Enum(__pyx_type, long __pyx_checksum, __pyx_state): # <<<<<<<<<<<<<< + * if __pyx_checksum != 0xb068931: + * from pickle import PickleError as __pyx_PickleError + */ + __pyx_t_5 = PyCFunction_NewEx(&__pyx_mdef_15View_dot_MemoryView_1__pyx_unpickle_Enum, NULL, __pyx_n_s_View_MemoryView); if (unlikely(!__pyx_t_5)) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_GOTREF(__pyx_t_5); + if (PyDict_SetItem(__pyx_d, __pyx_n_s_pyx_unpickle_Enum, __pyx_t_5) < 0) __PYX_ERR(1, 1, __pyx_L1_error) + __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; + + /* "(tree fragment)":9 + * __pyx_unpickle_Enum__set_state( __pyx_result, __pyx_state) + * return __pyx_result + * cdef __pyx_unpickle_Enum__set_state(Enum __pyx_result, tuple __pyx_state): # <<<<<<<<<<<<<< + * __pyx_result.name = __pyx_state[0] + * if len(__pyx_state) > 1 and hasattr(__pyx_result, '__dict__'): */ /*--- Wrapped vars code ---*/ @@ -17653,7 +20920,7 @@ PyMODINIT_FUNC PyInit_utils(void) __Pyx_XDECREF(__pyx_t_5); if (__pyx_m) { if (__pyx_d) { - __Pyx_AddTraceback("init utils", __pyx_clineno, __pyx_lineno, __pyx_filename); + __Pyx_AddTraceback("init utils", 0, __pyx_lineno, __pyx_filename); } Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { @@ -17661,14 +20928,17 @@ PyMODINIT_FUNC PyInit_utils(void) } __pyx_L0:; __Pyx_RefNannyFinishContext(); - #if PY_MAJOR_VERSION < 3 - return; - #else + #if CYTHON_PEP489_MULTI_PHASE_INIT + return (__pyx_m != NULL) ? 0 : -1; + #elif PY_MAJOR_VERSION >= 3 return __pyx_m; + #else + return; #endif } -/* Runtime support code */ +/* --- Runtime support code --- */ +/* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; @@ -17685,6 +20955,7 @@ static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { } #endif +/* GetBuiltinName */ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { @@ -17698,6 +20969,7 @@ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { return result; } +/* RaiseArgTupleInvalid */ static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, @@ -17723,6 +20995,7 @@ static void __Pyx_RaiseArgtupleInvalid( (num_expected == 1) ? "" : "s", num_found); } +/* RaiseDoubleKeywords */ static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) @@ -17736,6 +21009,7 @@ static void __Pyx_RaiseDoubleKeywordsError( #endif } +/* ParseKeywords */ static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], @@ -17837,94 +21111,7 @@ static int __Pyx_ParseOptionalKeywords( return -1; } -static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { -#if CYTHON_COMPILING_IN_CPYTHON - PyThreadState *tstate = PyThreadState_GET(); - *type = tstate->exc_type; - *value = tstate->exc_value; - *tb = tstate->exc_traceback; - Py_XINCREF(*type); - Py_XINCREF(*value); - Py_XINCREF(*tb); -#else - PyErr_GetExcInfo(type, value, tb); -#endif -} -static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { -#if CYTHON_COMPILING_IN_CPYTHON - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyThreadState *tstate = PyThreadState_GET(); - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = type; - tstate->exc_value = value; - tstate->exc_traceback = tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_SetExcInfo(type, value, tb); -#endif -} - -static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { - PyObject *local_type, *local_value, *local_tb; -#if CYTHON_COMPILING_IN_CPYTHON - PyObject *tmp_type, *tmp_value, *tmp_tb; - PyThreadState *tstate = PyThreadState_GET(); - local_type = tstate->curexc_type; - local_value = tstate->curexc_value; - local_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; -#else - PyErr_Fetch(&local_type, &local_value, &local_tb); -#endif - PyErr_NormalizeException(&local_type, &local_value, &local_tb); -#if CYTHON_COMPILING_IN_CPYTHON - if (unlikely(tstate->curexc_type)) -#else - if (unlikely(PyErr_Occurred())) -#endif - goto bad; - #if PY_MAJOR_VERSION >= 3 - if (local_tb) { - if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) - goto bad; - } - #endif - Py_XINCREF(local_tb); - Py_XINCREF(local_type); - Py_XINCREF(local_value); - *type = local_type; - *value = local_value; - *tb = local_tb; -#if CYTHON_COMPILING_IN_CPYTHON - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - tstate->exc_type = local_type; - tstate->exc_value = local_value; - tstate->exc_traceback = local_tb; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); -#else - PyErr_SetExcInfo(local_type, local_value, local_tb); -#endif - return 0; -bad: - *type = 0; - *value = 0; - *tb = 0; - Py_XDECREF(local_type); - Py_XDECREF(local_value); - Py_XDECREF(local_tb); - return -1; -} - +/* PyObjectCall */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; @@ -17944,10 +21131,10 @@ static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg } #endif -static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { -#if CYTHON_COMPILING_IN_CPYTHON +/* PyErrFetchRestore */ +#if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; - PyThreadState *tstate = PyThreadState_GET(); tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; @@ -17957,27 +21144,22 @@ static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyOb Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); -#else - PyErr_Restore(type, value, tb); -#endif } -static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { -#if CYTHON_COMPILING_IN_CPYTHON - PyThreadState *tstate = PyThreadState_GET(); +static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; -#else - PyErr_Fetch(type, value, tb); -#endif } +#endif +/* RaiseException */ #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { + __Pyx_PyThreadState_declare Py_XINCREF(type); if (!value || value == Py_None) value = NULL; @@ -18016,6 +21198,7 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, goto raise_error; } } + __Pyx_PyThreadState_assign __Pyx_ErrRestore(type, value, tb); return; raise_error: @@ -18049,10 +21232,13 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject if (value && PyExceptionInstance_Check(value)) { instance_class = (PyObject*) Py_TYPE(value); if (instance_class != type) { - if (PyObject_IsSubclass(instance_class, type)) { - type = instance_class; - } else { + int is_subclass = PyObject_IsSubclass(instance_class, type); + if (!is_subclass) { instance_class = NULL; + } else if (unlikely(is_subclass == -1)) { + goto bad; + } else { + type = instance_class; } } } @@ -18085,11 +21271,7 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject "raise: exception class must be a subclass of BaseException"); goto bad; } -#if PY_VERSION_HEX >= 0x03030000 if (cause) { -#else - if (cause && cause != Py_None) { -#endif PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; @@ -18112,12 +21294,12 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject if (tb) { #if CYTHON_COMPILING_IN_PYPY PyObject *tmp_type, *tmp_value, *tmp_tb; - PyErr_Fetch(tmp_type, tmp_value, tmp_tb); + PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); Py_INCREF(tb); PyErr_Restore(tmp_type, tmp_value, tb); Py_XDECREF(tmp_tb); #else - PyThreadState *tstate = PyThreadState_GET(); + PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); @@ -18132,75 +21314,247 @@ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject } #endif -static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { - int r; - if (!j) return -1; - r = PyObject_SetItem(o, j, v); - Py_DECREF(j); - return r; +/* UnicodeAsUCS4 */ +static CYTHON_INLINE Py_UCS4 __Pyx_PyUnicode_AsPy_UCS4(PyObject* x) { + Py_ssize_t length; + #if CYTHON_PEP393_ENABLED + length = PyUnicode_GET_LENGTH(x); + if (likely(length == 1)) { + return PyUnicode_READ_CHAR(x, 0); + } + #else + length = PyUnicode_GET_SIZE(x); + if (likely(length == 1)) { + return PyUnicode_AS_UNICODE(x)[0]; + } + #if Py_UNICODE_SIZE == 2 + else if (PyUnicode_GET_SIZE(x) == 2) { + Py_UCS4 high_val = PyUnicode_AS_UNICODE(x)[0]; + if (high_val >= 0xD800 && high_val <= 0xDBFF) { + Py_UCS4 low_val = PyUnicode_AS_UNICODE(x)[1]; + if (low_val >= 0xDC00 && low_val <= 0xDFFF) { + return 0x10000 + (((high_val & ((1<<10)-1)) << 10) | (low_val & ((1<<10)-1))); + } + } + } + #endif + #endif + PyErr_Format(PyExc_ValueError, + "only single character unicode strings can be converted to Py_UCS4, " + "got length %" CYTHON_FORMAT_SSIZE_T "d", length); + return (Py_UCS4)-1; } -static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, - int is_list, int wraparound, int boundscheck) { -#if CYTHON_COMPILING_IN_CPYTHON - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); - if ((!boundscheck) || likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { - PyObject* old = PyList_GET_ITEM(o, n); - Py_INCREF(v); - PyList_SET_ITEM(o, n, v); - Py_DECREF(old); - return 1; + +/* object_ord */ +static long __Pyx__PyObject_Ord(PyObject* c) { + Py_ssize_t size; + if (PyBytes_Check(c)) { + size = PyBytes_GET_SIZE(c); + if (likely(size == 1)) { + return (unsigned char) PyBytes_AS_STRING(c)[0]; } - } else { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_ass_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_Clear(); - else - return -1; - } - } - return m->sq_ass_item(o, i, v); +#if PY_MAJOR_VERSION < 3 + } else if (PyUnicode_Check(c)) { + return (long)__Pyx_PyUnicode_AsPy_UCS4(c); +#endif +#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) + } else if (PyByteArray_Check(c)) { + size = PyByteArray_GET_SIZE(c); + if (likely(size == 1)) { + return (unsigned char) PyByteArray_AS_STRING(c)[0]; } - } -#else -#if CYTHON_COMPILING_IN_PYPY - if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) { -#else - if (is_list || PySequence_Check(o)) { #endif - return PySequence_SetItem(o, i, v); + } else { + PyErr_Format(PyExc_TypeError, + "ord() expected string of length 1, but %.200s found", c->ob_type->tp_name); + return (long)(Py_UCS4)-1; } -#endif - return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); + PyErr_Format(PyExc_TypeError, + "ord() expected a character, but string of length %zd found", size); + return (long)(Py_UCS4)-1; } -static CYTHON_INLINE int __Pyx_IterFinish(void) { -#if CYTHON_COMPILING_IN_CPYTHON - PyThreadState *tstate = PyThreadState_GET(); - PyObject* exc_type = tstate->curexc_type; - if (unlikely(exc_type)) { - if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { - PyObject *exc_value, *exc_tb; - exc_value = tstate->curexc_value; - exc_tb = tstate->curexc_traceback; - tstate->curexc_type = 0; - tstate->curexc_value = 0; - tstate->curexc_traceback = 0; - Py_DECREF(exc_type); - Py_XDECREF(exc_value); - Py_XDECREF(exc_tb); - return 0; - } else { - return -1; - } - } - return 0; +/* BytesEquals */ +static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else + if (s1 == s2) { + return (equals == Py_EQ); + } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { + const char *ps1, *ps2; + Py_ssize_t length = PyBytes_GET_SIZE(s1); + if (length != PyBytes_GET_SIZE(s2)) + return (equals == Py_NE); + ps1 = PyBytes_AS_STRING(s1); + ps2 = PyBytes_AS_STRING(s2); + if (ps1[0] != ps2[0]) { + return (equals == Py_NE); + } else if (length == 1) { + return (equals == Py_EQ); + } else { + int result; +#if CYTHON_USE_UNICODE_INTERNALS + Py_hash_t hash1, hash2; + hash1 = ((PyBytesObject*)s1)->ob_shash; + hash2 = ((PyBytesObject*)s2)->ob_shash; + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + return (equals == Py_NE); + } +#endif + result = memcmp(ps1, ps2, (size_t)length); + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { + return (equals == Py_NE); + } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { + return (equals == Py_NE); + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +#endif +} + +/* UnicodeEquals */ +static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { +#if CYTHON_COMPILING_IN_PYPY + return PyObject_RichCompareBool(s1, s2, equals); +#else +#if PY_MAJOR_VERSION < 3 + PyObject* owned_ref = NULL; +#endif + int s1_is_unicode, s2_is_unicode; + if (s1 == s2) { + goto return_eq; + } + s1_is_unicode = PyUnicode_CheckExact(s1); + s2_is_unicode = PyUnicode_CheckExact(s2); +#if PY_MAJOR_VERSION < 3 + if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { + owned_ref = PyUnicode_FromObject(s2); + if (unlikely(!owned_ref)) + return -1; + s2 = owned_ref; + s2_is_unicode = 1; + } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { + owned_ref = PyUnicode_FromObject(s1); + if (unlikely(!owned_ref)) + return -1; + s1 = owned_ref; + s1_is_unicode = 1; + } else if (((!s2_is_unicode) & (!s1_is_unicode))) { + return __Pyx_PyBytes_Equals(s1, s2, equals); + } +#endif + if (s1_is_unicode & s2_is_unicode) { + Py_ssize_t length; + int kind; + void *data1, *data2; + if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) + return -1; + length = __Pyx_PyUnicode_GET_LENGTH(s1); + if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { + goto return_ne; + } +#if CYTHON_USE_UNICODE_INTERNALS + { + Py_hash_t hash1, hash2; + #if CYTHON_PEP393_ENABLED + hash1 = ((PyASCIIObject*)s1)->hash; + hash2 = ((PyASCIIObject*)s2)->hash; + #else + hash1 = ((PyUnicodeObject*)s1)->hash; + hash2 = ((PyUnicodeObject*)s2)->hash; + #endif + if (hash1 != hash2 && hash1 != -1 && hash2 != -1) { + goto return_ne; + } + } +#endif + kind = __Pyx_PyUnicode_KIND(s1); + if (kind != __Pyx_PyUnicode_KIND(s2)) { + goto return_ne; + } + data1 = __Pyx_PyUnicode_DATA(s1); + data2 = __Pyx_PyUnicode_DATA(s2); + if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { + goto return_ne; + } else if (length == 1) { + goto return_eq; + } else { + int result = memcmp(data1, data2, (size_t)(length * kind)); + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ) ? (result == 0) : (result != 0); + } + } else if ((s1 == Py_None) & s2_is_unicode) { + goto return_ne; + } else if ((s2 == Py_None) & s1_is_unicode) { + goto return_ne; + } else { + int result; + PyObject* py_result = PyObject_RichCompare(s1, s2, equals); + if (!py_result) + return -1; + result = __Pyx_PyObject_IsTrue(py_result); + Py_DECREF(py_result); + return result; + } +return_eq: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_EQ); +return_ne: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(owned_ref); + #endif + return (equals == Py_NE); +#endif +} + +/* RaiseTooManyValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { + PyErr_Format(PyExc_ValueError, + "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); +} + +/* RaiseNeedMoreValuesToUnpack */ +static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { + PyErr_Format(PyExc_ValueError, + "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", + index, (index == 1) ? "" : "s"); +} + +/* IterFinish */ +static CYTHON_INLINE int __Pyx_IterFinish(void) { +#if CYTHON_FAST_THREAD_STATE + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject* exc_type = tstate->curexc_type; + if (unlikely(exc_type)) { + if (likely(__Pyx_PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) { + PyObject *exc_value, *exc_tb; + exc_value = tstate->curexc_value; + exc_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; + Py_DECREF(exc_type); + Py_XDECREF(exc_value); + Py_XDECREF(exc_tb); + return 0; + } else { + return -1; + } + } + return 0; #else if (unlikely(PyErr_Occurred())) { if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { @@ -18214,7 +21568,188 @@ static CYTHON_INLINE int __Pyx_IterFinish(void) { #endif } -#if CYTHON_COMPILING_IN_CPYTHON +/* UnpackItemEndCheck */ +static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { + if (unlikely(retval)) { + Py_DECREF(retval); + __Pyx_RaiseTooManyValuesError(expected); + return -1; + } else { + return __Pyx_IterFinish(); + } + return 0; +} + +/* SetItemInt */ +static int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { + int r; + if (!j) return -1; + r = PyObject_SetItem(o, j, v); + Py_DECREF(j); + return r; +} +static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, int is_list, + CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); + if ((!boundscheck) || likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { + PyObject* old = PyList_GET_ITEM(o, n); + Py_INCREF(v); + PyList_SET_ITEM(o, n, v); + Py_DECREF(old); + return 1; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_ass_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return -1; + PyErr_Clear(); + } + } + return m->sq_ass_item(o, i, v); + } + } +#else +#if CYTHON_COMPILING_IN_PYPY + if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) { +#else + if (is_list || PySequence_Check(o)) { +#endif + return PySequence_SetItem(o, i, v); + } +#endif + return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); +} + +/* PyFunctionFastCall */ + #if CYTHON_FAST_PYCALL +#include "frameobject.h" +static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, + PyObject *globals) { + PyFrameObject *f; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + PyObject **fastlocals; + Py_ssize_t i; + PyObject *result; + assert(globals != NULL); + /* XXX Perhaps we should create a specialized + PyFrame_New() that doesn't take locals, but does + take builtins without sanity checking them. + */ + assert(tstate != NULL); + f = PyFrame_New(tstate, co, globals, NULL); + if (f == NULL) { + return NULL; + } + fastlocals = f->f_localsplus; + for (i = 0; i < na; i++) { + Py_INCREF(*args); + fastlocals[i] = *args++; + } + result = PyEval_EvalFrameEx(f,0); + ++tstate->recursion_depth; + Py_DECREF(f); + --tstate->recursion_depth; + return result; +} +#if 1 || PY_VERSION_HEX < 0x030600B1 +static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, int nargs, PyObject *kwargs) { + PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); + PyObject *globals = PyFunction_GET_GLOBALS(func); + PyObject *argdefs = PyFunction_GET_DEFAULTS(func); + PyObject *closure; +#if PY_MAJOR_VERSION >= 3 + PyObject *kwdefs; +#endif + PyObject *kwtuple, **k; + PyObject **d; + Py_ssize_t nd; + Py_ssize_t nk; + PyObject *result; + assert(kwargs == NULL || PyDict_Check(kwargs)); + nk = kwargs ? PyDict_Size(kwargs) : 0; + if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { + return NULL; + } + if ( +#if PY_MAJOR_VERSION >= 3 + co->co_kwonlyargcount == 0 && +#endif + likely(kwargs == NULL || nk == 0) && + co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { + if (argdefs == NULL && co->co_argcount == nargs) { + result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); + goto done; + } + else if (nargs == 0 && argdefs != NULL + && co->co_argcount == Py_SIZE(argdefs)) { + /* function called with no arguments, but all parameters have + a default value: use default values as arguments .*/ + args = &PyTuple_GET_ITEM(argdefs, 0); + result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); + goto done; + } + } + if (kwargs != NULL) { + Py_ssize_t pos, i; + kwtuple = PyTuple_New(2 * nk); + if (kwtuple == NULL) { + result = NULL; + goto done; + } + k = &PyTuple_GET_ITEM(kwtuple, 0); + pos = i = 0; + while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { + Py_INCREF(k[i]); + Py_INCREF(k[i+1]); + i += 2; + } + nk = i / 2; + } + else { + kwtuple = NULL; + k = NULL; + } + closure = PyFunction_GET_CLOSURE(func); +#if PY_MAJOR_VERSION >= 3 + kwdefs = PyFunction_GET_KW_DEFAULTS(func); +#endif + if (argdefs != NULL) { + d = &PyTuple_GET_ITEM(argdefs, 0); + nd = Py_SIZE(argdefs); + } + else { + d = NULL; + nd = 0; + } +#if PY_MAJOR_VERSION >= 3 + result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, + args, nargs, + k, (int)nk, + d, (int)nd, kwdefs, closure); +#else + result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, + args, nargs, + k, (int)nk, + d, (int)nd, closure); +#endif + Py_XDECREF(kwtuple); +done: + Py_LeaveRecursiveCall(); + return result; +} +#endif +#endif + +/* PyObjectCallMethO */ + #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { PyObject *self, *result; PyCFunction cfunc; @@ -18233,10 +21768,16 @@ static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject } #endif -#if CYTHON_COMPILING_IN_CPYTHON +/* PyObjectCallNoArg */ + #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { +#if CYTHON_FAST_PYCALL + if (PyFunction_Check(func)) { + return __Pyx_PyFunction_FastCall(func, NULL, 0); + } +#endif #ifdef __Pyx_CyFunction_USED - if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { + if (likely(PyCFunction_Check(func) || __Pyx_TypeCheck(func, __pyx_CyFunctionType))) { #else if (likely(PyCFunction_Check(func))) { #endif @@ -18248,11 +21789,35 @@ static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { } #endif -#if CYTHON_COMPILING_IN_CPYTHON -static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject *result; - PyObject *args = PyTuple_New(1); - if (unlikely(!args)) return NULL; +/* PyCFunctionFastCall */ + #if CYTHON_FAST_PYCCALL +static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { + PyCFunctionObject *func = (PyCFunctionObject*)func_obj; + PyCFunction meth = PyCFunction_GET_FUNCTION(func); + PyObject *self = PyCFunction_GET_SELF(func); + int flags = PyCFunction_GET_FLAGS(func); + assert(PyCFunction_Check(func)); + assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS))); + assert(nargs >= 0); + assert(nargs == 0 || args != NULL); + /* _PyCFunction_FastCallDict() must not be called with an exception set, + because it may clear it (directly or indirectly) and so the + caller loses its exception */ + assert(!PyErr_Occurred()); + if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { + return (*((__Pyx_PyCFunctionFastWithKeywords)meth)) (self, args, nargs, NULL); + } else { + return (*((__Pyx_PyCFunctionFast)meth)) (self, args, nargs); + } +} +#endif + +/* PyObjectCallOneArg */ + #if CYTHON_COMPILING_IN_CPYTHON +static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { + PyObject *result; + PyObject *args = PyTuple_New(1); + if (unlikely(!args)) return NULL; Py_INCREF(arg); PyTuple_SET_ITEM(args, 0, arg); result = __Pyx_PyObject_Call(func, args, NULL); @@ -18260,29 +21825,39 @@ static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { return result; } static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { -#ifdef __Pyx_CyFunction_USED - if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { -#else - if (likely(PyCFunction_Check(func))) { +#if CYTHON_FAST_PYCALL + if (PyFunction_Check(func)) { + return __Pyx_PyFunction_FastCall(func, &arg, 1); + } #endif + if (likely(PyCFunction_Check(func))) { if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { return __Pyx_PyObject_CallMethO(func, arg); +#if CYTHON_FAST_PYCCALL + } else if (PyCFunction_GET_FLAGS(func) & METH_FASTCALL) { + return __Pyx_PyCFunction_FastCall(func, &arg, 1); +#endif } } return __Pyx__PyObject_CallOneArg(func, arg); } #else static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { - PyObject* args = PyTuple_Pack(1, arg); - return (likely(args)) ? __Pyx_PyObject_Call(func, args, NULL) : NULL; + PyObject *result; + PyObject *args = PyTuple_Pack(1, arg); + if (unlikely(!args)) return NULL; + result = __Pyx_PyObject_Call(func, args, NULL); + Py_DECREF(args); + return result; } #endif -static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { +/* PyObjectCallMethod0 */ + static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { PyObject *method, *result = NULL; method = __Pyx_PyObject_GetAttrStr(obj, method_name); if (unlikely(!method)) goto bad; -#if CYTHON_COMPILING_IN_CPYTHON +#if CYTHON_UNPACK_METHODS if (likely(PyMethod_Check(method))) { PyObject *self = PyMethod_GET_SELF(method); if (likely(self)) { @@ -18299,33 +21874,13 @@ static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name return result; } -static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { - PyErr_Format(PyExc_ValueError, - "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", - index, (index == 1) ? "" : "s"); -} - -static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { - PyErr_Format(PyExc_ValueError, - "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); -} - -static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { - if (unlikely(retval)) { - Py_DECREF(retval); - __Pyx_RaiseTooManyValuesError(expected); - return -1; - } else { - return __Pyx_IterFinish(); - } - return 0; -} - -static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { +/* RaiseNoneIterError */ + static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } -static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { +/* UnpackTupleError */ + static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { if (t == Py_None) { __Pyx_RaiseNoneNotIterableError(); } else if (PyTuple_GET_SIZE(t) < index) { @@ -18335,41 +21890,47 @@ static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { } } -static CYTHON_INLINE int __Pyx_unpack_tuple2(PyObject* tuple, PyObject** pvalue1, PyObject** pvalue2, - int is_tuple, int has_known_size, int decref_tuple) { - Py_ssize_t index; - PyObject *value1 = NULL, *value2 = NULL, *iter = NULL; - if (!is_tuple && unlikely(!PyTuple_Check(tuple))) { - iternextfunc iternext; - iter = PyObject_GetIter(tuple); - if (unlikely(!iter)) goto bad; - if (decref_tuple) { Py_DECREF(tuple); tuple = NULL; } - iternext = Py_TYPE(iter)->tp_iternext; - value1 = iternext(iter); if (unlikely(!value1)) { index = 0; goto unpacking_failed; } - value2 = iternext(iter); if (unlikely(!value2)) { index = 1; goto unpacking_failed; } - if (!has_known_size && unlikely(__Pyx_IternextUnpackEndCheck(iternext(iter), 2))) goto bad; - Py_DECREF(iter); - } else { - if (!has_known_size && unlikely(PyTuple_GET_SIZE(tuple) != 2)) { - __Pyx_UnpackTupleError(tuple, 2); - goto bad; - } +/* UnpackTuple2 */ + static CYTHON_INLINE int __Pyx_unpack_tuple2_exact( + PyObject* tuple, PyObject** pvalue1, PyObject** pvalue2, int decref_tuple) { + PyObject *value1 = NULL, *value2 = NULL; #if CYTHON_COMPILING_IN_PYPY - value1 = PySequence_ITEM(tuple, 0); - if (unlikely(!value1)) goto bad; - value2 = PySequence_ITEM(tuple, 1); - if (unlikely(!value2)) goto bad; + value1 = PySequence_ITEM(tuple, 0); if (unlikely(!value1)) goto bad; + value2 = PySequence_ITEM(tuple, 1); if (unlikely(!value2)) goto bad; #else - value1 = PyTuple_GET_ITEM(tuple, 0); - value2 = PyTuple_GET_ITEM(tuple, 1); - Py_INCREF(value1); - Py_INCREF(value2); + value1 = PyTuple_GET_ITEM(tuple, 0); Py_INCREF(value1); + value2 = PyTuple_GET_ITEM(tuple, 1); Py_INCREF(value2); #endif - if (decref_tuple) { Py_DECREF(tuple); } + if (decref_tuple) { + Py_DECREF(tuple); } *pvalue1 = value1; *pvalue2 = value2; return 0; +#if CYTHON_COMPILING_IN_PYPY +bad: + Py_XDECREF(value1); + Py_XDECREF(value2); + if (decref_tuple) { Py_XDECREF(tuple); } + return -1; +#endif +} +static int __Pyx_unpack_tuple2_generic(PyObject* tuple, PyObject** pvalue1, PyObject** pvalue2, + int has_known_size, int decref_tuple) { + Py_ssize_t index; + PyObject *value1 = NULL, *value2 = NULL, *iter = NULL; + iternextfunc iternext; + iter = PyObject_GetIter(tuple); + if (unlikely(!iter)) goto bad; + if (decref_tuple) { Py_DECREF(tuple); tuple = NULL; } + iternext = Py_TYPE(iter)->tp_iternext; + value1 = iternext(iter); if (unlikely(!value1)) { index = 0; goto unpacking_failed; } + value2 = iternext(iter); if (unlikely(!value2)) { index = 1; goto unpacking_failed; } + if (!has_known_size && unlikely(__Pyx_IternextUnpackEndCheck(iternext(iter), 2))) goto bad; + Py_DECREF(iter); + *pvalue1 = value1; + *pvalue2 = value2; + return 0; unpacking_failed: if (!has_known_size && __Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); @@ -18381,17 +21942,35 @@ static CYTHON_INLINE int __Pyx_unpack_tuple2(PyObject* tuple, PyObject** pvalue1 return -1; } -static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* iterable, int is_dict, PyObject* method_name, +/* dict_iter */ + static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* iterable, int is_dict, PyObject* method_name, Py_ssize_t* p_orig_length, int* p_source_is_dict) { is_dict = is_dict || likely(PyDict_CheckExact(iterable)); *p_source_is_dict = is_dict; -#if !CYTHON_COMPILING_IN_PYPY if (is_dict) { +#if !CYTHON_COMPILING_IN_PYPY *p_orig_length = PyDict_Size(iterable); Py_INCREF(iterable); return iterable; - } +#elif PY_MAJOR_VERSION >= 3 + static PyObject *py_items = NULL, *py_keys = NULL, *py_values = NULL; + PyObject **pp = NULL; + if (method_name) { + const char *name = PyUnicode_AsUTF8(method_name); + if (strcmp(name, "iteritems") == 0) pp = &py_items; + else if (strcmp(name, "iterkeys") == 0) pp = &py_keys; + else if (strcmp(name, "itervalues") == 0) pp = &py_values; + if (pp) { + if (!*pp) { + *pp = PyUnicode_FromString(name + 4); + if (!*pp) + return NULL; + } + method_name = *pp; + } + } #endif + } *p_orig_length = 0; if (method_name) { PyObject* iter; @@ -18408,8 +21987,9 @@ static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* iterable, int is_di } return PyObject_GetIter(iterable); } -static CYTHON_INLINE int __Pyx_dict_iter_next(PyObject* iter_obj, Py_ssize_t orig_length, Py_ssize_t* ppos, - PyObject** pkey, PyObject** pvalue, PyObject** pitem, int source_is_dict) { +static CYTHON_INLINE int __Pyx_dict_iter_next( + PyObject* iter_obj, CYTHON_NCP_UNUSED Py_ssize_t orig_length, CYTHON_NCP_UNUSED Py_ssize_t* ppos, + PyObject** pkey, PyObject** pvalue, PyObject** pitem, int source_is_dict) { PyObject* next_item; #if !CYTHON_COMPILING_IN_PYPY if (source_is_dict) { @@ -18475,1006 +22055,730 @@ static CYTHON_INLINE int __Pyx_dict_iter_next(PyObject* iter_obj, Py_ssize_t ori return 1; } -static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { - unsigned int n = 1; - return *(unsigned char*)(&n) != 0; -} -static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, - __Pyx_BufFmt_StackElem* stack, - __Pyx_TypeInfo* type) { - stack[0].field = &ctx->root; - stack[0].parent_offset = 0; - ctx->root.type = type; - ctx->root.name = "buffer dtype"; - ctx->root.offset = 0; - ctx->head = stack; - ctx->head->field = &ctx->root; - ctx->fmt_offset = 0; - ctx->head->parent_offset = 0; - ctx->new_packmode = '@'; - ctx->enc_packmode = '@'; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->is_complex = 0; - ctx->is_valid_array = 0; - ctx->struct_alignment = 0; - while (type->typegroup == 'S') { - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = 0; - type = type->fields->type; - } +/* GetItemInt */ + static PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { + PyObject *r; + if (!j) return NULL; + r = PyObject_GetItem(o, j); + Py_DECREF(j); + return r; } -static int __Pyx_BufFmt_ParseNumber(const char** ts) { - int count; - const char* t = *ts; - if (*t < '0' || *t > '9') { - return -1; - } else { - count = *t++ - '0'; - while (*t >= '0' && *t < '9') { - count *= 10; - count += *t++ - '0'; - } +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, + CYTHON_NCP_UNUSED int wraparound, + CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyList_GET_SIZE(o); + } + if ((!boundscheck) || likely((0 <= wrapped_i) & (wrapped_i < PyList_GET_SIZE(o)))) { + PyObject *r = PyList_GET_ITEM(o, wrapped_i); + Py_INCREF(r); + return r; } - *ts = t; - return count; -} -static int __Pyx_BufFmt_ExpectNumber(const char **ts) { - int number = __Pyx_BufFmt_ParseNumber(ts); - if (number == -1) - PyErr_Format(PyExc_ValueError,\ - "Does not understand character buffer dtype format string ('%c')", **ts); - return number; -} -static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { - PyErr_Format(PyExc_ValueError, - "Unexpected format string character: '%c'", ch); + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif } -static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { - switch (ch) { - case 'c': return "'char'"; - case 'b': return "'signed char'"; - case 'B': return "'unsigned char'"; - case 'h': return "'short'"; - case 'H': return "'unsigned short'"; - case 'i': return "'int'"; - case 'I': return "'unsigned int'"; - case 'l': return "'long'"; - case 'L': return "'unsigned long'"; - case 'q': return "'long long'"; - case 'Q': return "'unsigned long long'"; - case 'f': return (is_complex ? "'complex float'" : "'float'"); - case 'd': return (is_complex ? "'complex double'" : "'double'"); - case 'g': return (is_complex ? "'complex long double'" : "'long double'"); - case 'T': return "a struct"; - case 'O': return "Python object"; - case 'P': return "a pointer"; - case 's': case 'p': return "a string"; - case 0: return "end"; - default: return "unparseable format string"; - } +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, + CYTHON_NCP_UNUSED int wraparound, + CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + Py_ssize_t wrapped_i = i; + if (wraparound & unlikely(i < 0)) { + wrapped_i += PyTuple_GET_SIZE(o); + } + if ((!boundscheck) || likely((0 <= wrapped_i) & (wrapped_i < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, wrapped_i); + Py_INCREF(r); + return r; + } + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +#else + return PySequence_GetItem(o, i); +#endif } -static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return 2; - case 'i': case 'I': case 'l': case 'L': return 4; - case 'q': case 'Q': return 8; - case 'f': return (is_complex ? 8 : 4); - case 'd': return (is_complex ? 16 : 8); - case 'g': { - PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); - return 0; +static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, + CYTHON_NCP_UNUSED int wraparound, + CYTHON_NCP_UNUSED int boundscheck) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS && CYTHON_USE_TYPE_SLOTS + if (is_list || PyList_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); + if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { + PyObject *r = PyList_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } } - case 'O': case 'P': return sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; + else if (PyTuple_CheckExact(o)) { + Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); + if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { + PyObject *r = PyTuple_GET_ITEM(o, n); + Py_INCREF(r); + return r; + } + } else { + PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; + if (likely(m && m->sq_item)) { + if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { + Py_ssize_t l = m->sq_length(o); + if (likely(l >= 0)) { + i += l; + } else { + if (!PyErr_ExceptionMatches(PyExc_OverflowError)) + return NULL; + PyErr_Clear(); + } + } + return m->sq_item(o, i); + } } -} -static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { - switch (ch) { - case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(short); - case 'i': case 'I': return sizeof(int); - case 'l': case 'L': return sizeof(long); - #ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(PY_LONG_LONG); - #endif - case 'f': return sizeof(float) * (is_complex ? 2 : 1); - case 'd': return sizeof(double) * (is_complex ? 2 : 1); - case 'g': return sizeof(long double) * (is_complex ? 2 : 1); - case 'O': case 'P': return sizeof(void*); - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; +#else + if (is_list || PySequence_Check(o)) { + return PySequence_GetItem(o, i); } - } -} -typedef struct { char c; short x; } __Pyx_st_short; -typedef struct { char c; int x; } __Pyx_st_int; -typedef struct { char c; long x; } __Pyx_st_long; -typedef struct { char c; float x; } __Pyx_st_float; -typedef struct { char c; double x; } __Pyx_st_double; -typedef struct { char c; long double x; } __Pyx_st_longdouble; -typedef struct { char c; void *x; } __Pyx_st_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif -static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); -#endif - case 'f': return sizeof(__Pyx_st_float) - sizeof(float); - case 'd': return sizeof(__Pyx_st_double) - sizeof(double); - case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; + return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); +} + +/* MemviewSliceInit */ + static int +__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, + int ndim, + __Pyx_memviewslice *memviewslice, + int memview_is_new_reference) +{ + __Pyx_RefNannyDeclarations + int i, retval=-1; + Py_buffer *buf = &memview->view; + __Pyx_RefNannySetupContext("init_memviewslice", 0); + if (!buf) { + PyErr_SetString(PyExc_ValueError, + "buf is NULL."); + goto fail; + } else if (memviewslice->memview || memviewslice->data) { + PyErr_SetString(PyExc_ValueError, + "memviewslice is already initialized!"); + goto fail; + } + if (buf->strides) { + for (i = 0; i < ndim; i++) { + memviewslice->strides[i] = buf->strides[i]; + } + } else { + Py_ssize_t stride = buf->itemsize; + for (i = ndim - 1; i >= 0; i--) { + memviewslice->strides[i] = stride; + stride *= buf->shape[i]; + } + } + for (i = 0; i < ndim; i++) { + memviewslice->shape[i] = buf->shape[i]; + if (buf->suboffsets) { + memviewslice->suboffsets[i] = buf->suboffsets[i]; + } else { + memviewslice->suboffsets[i] = -1; + } + } + memviewslice->memview = memview; + memviewslice->data = (char *)buf->buf; + if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { + Py_INCREF(memview); } + retval = 0; + goto no_fail; +fail: + memviewslice->memview = 0; + memviewslice->data = 0; + retval = -1; +no_fail: + __Pyx_RefNannyFinishContext(); + return retval; } -/* These are for computing the padding at the end of the struct to align - on the first member of the struct. This will probably the same as above, - but we don't have any guarantees. - */ -typedef struct { short x; char c; } __Pyx_pad_short; -typedef struct { int x; char c; } __Pyx_pad_int; -typedef struct { long x; char c; } __Pyx_pad_long; -typedef struct { float x; char c; } __Pyx_pad_float; -typedef struct { double x; char c; } __Pyx_pad_double; -typedef struct { long double x; char c; } __Pyx_pad_longdouble; -typedef struct { void *x; char c; } __Pyx_pad_void_p; -#ifdef HAVE_LONG_LONG -typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#ifndef Py_NO_RETURN +#define Py_NO_RETURN #endif -static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { - switch (ch) { - case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; - case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); - case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); - case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); -#ifdef HAVE_LONG_LONG - case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +static void __pyx_fatalerror(const char *fmt, ...) Py_NO_RETURN { + va_list vargs; + char msg[200]; +#ifdef HAVE_STDARG_PROTOTYPES + va_start(vargs, fmt); +#else + va_start(vargs); #endif - case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); - case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); - case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); - case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); - default: - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } + vsnprintf(msg, 200, fmt, vargs); + va_end(vargs); + Py_FatalError(msg); } -static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { - switch (ch) { - case 'c': - return 'H'; - case 'b': case 'h': case 'i': - case 'l': case 'q': case 's': case 'p': - return 'I'; - case 'B': case 'H': case 'I': case 'L': case 'Q': - return 'U'; - case 'f': case 'd': case 'g': - return (is_complex ? 'C' : 'R'); - case 'O': - return 'O'; - case 'P': - return 'P'; - default: { - __Pyx_BufFmt_RaiseUnexpectedChar(ch); - return 0; - } - } +static CYTHON_INLINE int +__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)++; + PyThread_release_lock(lock); + return result; } -static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { - if (ctx->head == NULL || ctx->head->field == &ctx->root) { - const char* expected; - const char* quote; - if (ctx->head == NULL) { - expected = "end"; - quote = ""; - } else { - expected = ctx->head->field->type->name; - quote = "'"; - } - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected %s%s%s but got %s", - quote, expected, quote, - __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); - } else { - __Pyx_StructField* field = ctx->head->field; - __Pyx_StructField* parent = (ctx->head - 1)->field; - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", - field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), - parent->type->name, field->name); - } +static CYTHON_INLINE int +__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, + PyThread_type_lock lock) +{ + int result; + PyThread_acquire_lock(lock, 1); + result = (*acquisition_count)--; + PyThread_release_lock(lock); + return result; } -static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { - char group; - size_t size, offset, arraysize = 1; - if (ctx->enc_type == 0) return 0; - if (ctx->head->field->type->arraysize[0]) { - int i, ndim = 0; - if (ctx->enc_type == 's' || ctx->enc_type == 'p') { - ctx->is_valid_array = ctx->head->field->type->ndim == 1; - ndim = 1; - if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { - PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %zu", - ctx->head->field->type->arraysize[0], ctx->enc_count); - return -1; +static CYTHON_INLINE void +__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) +{ + int first_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview || (PyObject *) memview == Py_None) + return; + if (__pyx_get_slice_count(memview) < 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + first_time = __pyx_add_acquisition_count(memview) == 0; + if (first_time) { + if (have_gil) { + Py_INCREF((PyObject *) memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_INCREF((PyObject *) memview); + PyGILState_Release(_gilstate); } } - if (!ctx->is_valid_array) { - PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", - ctx->head->field->type->ndim, ndim); - return -1; - } - for (i = 0; i < ctx->head->field->type->ndim; i++) { - arraysize *= ctx->head->field->type->arraysize[i]; +} +static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, + int have_gil, int lineno) { + int last_time; + struct __pyx_memoryview_obj *memview = memslice->memview; + if (!memview ) { + return; + } else if ((PyObject *) memview == Py_None) { + memslice->memview = NULL; + return; } - ctx->is_valid_array = 0; - ctx->enc_count = 1; - } - group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); - do { - __Pyx_StructField* field = ctx->head->field; - __Pyx_TypeInfo* type = field->type; - if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { - size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + if (__pyx_get_slice_count(memview) <= 0) + __pyx_fatalerror("Acquisition count is %d (line %d)", + __pyx_get_slice_count(memview), lineno); + last_time = __pyx_sub_acquisition_count(memview) == 1; + memslice->data = NULL; + if (last_time) { + if (have_gil) { + Py_CLEAR(memslice->memview); + } else { + PyGILState_STATE _gilstate = PyGILState_Ensure(); + Py_CLEAR(memslice->memview); + PyGILState_Release(_gilstate); + } } else { - size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); + memslice->memview = NULL; } - if (ctx->enc_packmode == '@') { - size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); - size_t align_mod_offset; - if (align_at == 0) return -1; - align_mod_offset = ctx->fmt_offset % align_at; - if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; - if (ctx->struct_alignment == 0) - ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, - ctx->is_complex); +} + +/* ArgTypeTest */ + static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) +{ + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; } - if (type->size != size || type->typegroup != group) { - if (type->typegroup == 'C' && type->fields != NULL) { - size_t parent_offset = ctx->head->parent_offset + field->offset; - ++ctx->head; - ctx->head->field = type->fields; - ctx->head->parent_offset = parent_offset; - continue; - } - if ((type->typegroup == 'H' || group == 'H') && type->size == size) { - } else { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } + else if (exact) { + #if PY_MAJOR_VERSION == 2 + if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; + #endif } - offset = ctx->head->parent_offset + field->offset; - if (ctx->fmt_offset != offset) { - PyErr_Format(PyExc_ValueError, - "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", - (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); - return -1; - } - ctx->fmt_offset += size; - if (arraysize) - ctx->fmt_offset += (arraysize - 1) * size; - --ctx->enc_count; - while (1) { - if (field == &ctx->root) { - ctx->head = NULL; - if (ctx->enc_count != 0) { - __Pyx_BufFmt_RaiseExpected(ctx); - return -1; - } - break; - } - ctx->head->field = ++field; - if (field->type == NULL) { - --ctx->head; - field = ctx->head->field; - continue; - } else if (field->type->typegroup == 'S') { - size_t parent_offset = ctx->head->parent_offset + field->offset; - if (field->type->fields->type == NULL) continue; - field = field->type->fields; - ++ctx->head; - ctx->head->field = field; - ctx->head->parent_offset = parent_offset; - break; - } else { - break; - } - } - } while (ctx->enc_count); - ctx->enc_type = 0; - ctx->is_complex = 0; - return 0; -} -static CYTHON_INLINE PyObject * -__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) -{ - const char *ts = *tsp; - int i = 0, number; - int ndim = ctx->head->field->type->ndim; -; - ++ts; - if (ctx->new_count != 1) { - PyErr_SetString(PyExc_ValueError, - "Cannot handle repeated arrays in format string"); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - while (*ts && *ts != ')') { - switch (*ts) { - case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; - default: break; - } - number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) - return PyErr_Format(PyExc_ValueError, - "Expected a dimension of size %zu, got %d", - ctx->head->field->type->arraysize[i], number); - if (*ts != ',' && *ts != ')') - return PyErr_Format(PyExc_ValueError, - "Expected a comma in format string, got '%c'", *ts); - if (*ts == ',') ts++; - i++; - } - if (i != ndim) - return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", - ctx->head->field->type->ndim, i); - if (!*ts) { - PyErr_SetString(PyExc_ValueError, - "Unexpected end of format string, expected ')'"); - return NULL; - } - ctx->is_valid_array = 1; - ctx->new_count = 1; - *tsp = ++ts; - return Py_None; -} -static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { - int got_Z = 0; - while (1) { - switch(*ts) { - case 0: - if (ctx->enc_type != 0 && ctx->head == NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - if (ctx->head != NULL) { - __Pyx_BufFmt_RaiseExpected(ctx); - return NULL; - } - return ts; - case ' ': - case '\r': - case '\n': - ++ts; - break; - case '<': - if (!__Pyx_IsLittleEndian()) { - PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '>': - case '!': - if (__Pyx_IsLittleEndian()) { - PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); - return NULL; - } - ctx->new_packmode = '='; - ++ts; - break; - case '=': - case '@': - case '^': - ctx->new_packmode = *ts++; - break; - case 'T': - { - const char* ts_after_sub; - size_t i, struct_count = ctx->new_count; - size_t struct_alignment = ctx->struct_alignment; - ctx->new_count = 1; - ++ts; - if (*ts != '{') { - PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); - return NULL; - } - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; - ctx->enc_count = 0; - ctx->struct_alignment = 0; - ++ts; - ts_after_sub = ts; - for (i = 0; i != struct_count; ++i) { - ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); - if (!ts_after_sub) return NULL; - } - ts = ts_after_sub; - if (struct_alignment) ctx->struct_alignment = struct_alignment; - } - break; - case '}': - { - size_t alignment = ctx->struct_alignment; - ++ts; - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_type = 0; - if (alignment && ctx->fmt_offset % alignment) { - ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); - } - } - return ts; - case 'x': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->fmt_offset += ctx->new_count; - ctx->new_count = 1; - ctx->enc_count = 0; - ctx->enc_type = 0; - ctx->enc_packmode = ctx->new_packmode; - ++ts; - break; - case 'Z': - got_Z = 1; - ++ts; - if (*ts != 'f' && *ts != 'd' && *ts != 'g') { - __Pyx_BufFmt_RaiseUnexpectedChar('Z'); - return NULL; - } - case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': - case 'l': case 'L': case 'q': case 'Q': - case 'f': case 'd': case 'g': - case 'O': case 'p': - if (ctx->enc_type == *ts && got_Z == ctx->is_complex && - ctx->enc_packmode == ctx->new_packmode) { - ctx->enc_count += ctx->new_count; - ctx->new_count = 1; - got_Z = 0; - ++ts; - break; - } - case 's': - if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; - ctx->enc_count = ctx->new_count; - ctx->enc_packmode = ctx->new_packmode; - ctx->enc_type = *ts; - ctx->is_complex = got_Z; - ++ts; - ctx->new_count = 1; - got_Z = 0; - break; - case ':': - ++ts; - while(*ts != ':') ++ts; - ++ts; - break; - case '(': - if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; - break; - default: - { - int number = __Pyx_BufFmt_ExpectNumber(&ts); - if (number == -1) return NULL; - ctx->new_count = (size_t)number; - } - } - } -} -static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { - buf->buf = NULL; - buf->obj = NULL; - buf->strides = __Pyx_zeros; - buf->shape = __Pyx_zeros; - buf->suboffsets = __Pyx_minusones; -} -static CYTHON_INLINE int __Pyx_GetBufferAndValidate( - Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, - int nd, int cast, __Pyx_BufFmt_StackElem* stack) -{ - if (obj == Py_None || obj == NULL) { - __Pyx_ZeroBuffer(buf); - return 0; - } - buf->buf = NULL; - if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; - if (buf->ndim != nd) { - PyErr_Format(PyExc_ValueError, - "Buffer has wrong number of dimensions (expected %d, got %d)", - nd, buf->ndim); - goto fail; - } - if (!cast) { - __Pyx_BufFmt_Context ctx; - __Pyx_BufFmt_Init(&ctx, stack, dtype); - if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; - } - if ((unsigned)buf->itemsize != dtype->size) { - PyErr_Format(PyExc_ValueError, - "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", - buf->itemsize, (buf->itemsize > 1) ? "s" : "", - dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); - goto fail; - } - if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; - return 0; -fail:; - __Pyx_ZeroBuffer(buf); - return -1; -} -static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { - if (info->buf == NULL) return; - if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; - __Pyx_ReleaseBuffer(info); -} - -static int -__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, - int ndim, - __Pyx_memviewslice *memviewslice, - int memview_is_new_reference) -{ - __Pyx_RefNannyDeclarations - int i, retval=-1; - Py_buffer *buf = &memview->view; - __Pyx_RefNannySetupContext("init_memviewslice", 0); - if (!buf) { - PyErr_SetString(PyExc_ValueError, - "buf is NULL."); - goto fail; - } else if (memviewslice->memview || memviewslice->data) { - PyErr_SetString(PyExc_ValueError, - "memviewslice is already initialized!"); - goto fail; - } - if (buf->strides) { - for (i = 0; i < ndim; i++) { - memviewslice->strides[i] = buf->strides[i]; - } - } else { - Py_ssize_t stride = buf->itemsize; - for (i = ndim - 1; i >= 0; i--) { - memviewslice->strides[i] = stride; - stride *= buf->shape[i]; - } - } - for (i = 0; i < ndim; i++) { - memviewslice->shape[i] = buf->shape[i]; - if (buf->suboffsets) { - memviewslice->suboffsets[i] = buf->suboffsets[i]; - } else { - memviewslice->suboffsets[i] = -1; - } - } - memviewslice->memview = memview; - memviewslice->data = (char *)buf->buf; - if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { - Py_INCREF(memview); - } - retval = 0; - goto no_fail; -fail: - memviewslice->memview = 0; - memviewslice->data = 0; - retval = -1; -no_fail: - __Pyx_RefNannyFinishContext(); - return retval; -} -static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) { - va_list vargs; - char msg[200]; - va_start(vargs, fmt); -#ifdef HAVE_STDARG_PROTOTYPES - va_start(vargs, fmt); -#else - va_start(vargs); -#endif - vsnprintf(msg, 200, fmt, vargs); - Py_FatalError(msg); - va_end(vargs); -} -static CYTHON_INLINE int -__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, - PyThread_type_lock lock) -{ - int result; - PyThread_acquire_lock(lock, 1); - result = (*acquisition_count)++; - PyThread_release_lock(lock); - return result; -} -static CYTHON_INLINE int -__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, - PyThread_type_lock lock) -{ - int result; - PyThread_acquire_lock(lock, 1); - result = (*acquisition_count)--; - PyThread_release_lock(lock); - return result; -} -static CYTHON_INLINE void -__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) -{ - int first_time; - struct __pyx_memoryview_obj *memview = memslice->memview; - if (!memview || (PyObject *) memview == Py_None) - return; - if (__pyx_get_slice_count(memview) < 0) - __pyx_fatalerror("Acquisition count is %d (line %d)", - __pyx_get_slice_count(memview), lineno); - first_time = __pyx_add_acquisition_count(memview) == 0; - if (first_time) { - if (have_gil) { - Py_INCREF((PyObject *) memview); - } else { - PyGILState_STATE _gilstate = PyGILState_Ensure(); - Py_INCREF((PyObject *) memview); - PyGILState_Release(_gilstate); - } - } -} -static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, - int have_gil, int lineno) { - int last_time; - struct __pyx_memoryview_obj *memview = memslice->memview; - if (!memview ) { - return; - } else if ((PyObject *) memview == Py_None) { - memslice->memview = NULL; - return; - } - if (__pyx_get_slice_count(memview) <= 0) - __pyx_fatalerror("Acquisition count is %d (line %d)", - __pyx_get_slice_count(memview), lineno); - last_time = __pyx_sub_acquisition_count(memview) == 1; - memslice->data = NULL; - if (last_time) { - if (have_gil) { - Py_CLEAR(memslice->memview); - } else { - PyGILState_STATE _gilstate = PyGILState_Ensure(); - Py_CLEAR(memslice->memview); - PyGILState_Release(_gilstate); - } - } else { - memslice->memview = NULL; + else { + if (likely(__Pyx_TypeCheck(obj, type))) return 1; } -} - -static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); -} -static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, - const char *name, int exact) -{ - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - if (none_allowed && obj == Py_None) return 1; - else if (exact) { - if (likely(Py_TYPE(obj) == type)) return 1; - #if PY_MAJOR_VERSION == 2 - else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; - #endif - } - else { - if (likely(PyObject_TypeCheck(obj, type))) return 1; - } - __Pyx_RaiseArgumentTypeInvalid(name, obj, type); return 0; } -static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); +/* None */ + static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t a, Py_ssize_t b) { + Py_ssize_t q = a / b; + Py_ssize_t r = a - q*b; + q -= ((r != 0) & ((r ^ b) < 0)); + return q; +} + +/* GetAttr */ + static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { +#if CYTHON_USE_TYPE_SLOTS +#if PY_MAJOR_VERSION >= 3 + if (likely(PyUnicode_Check(n))) #else - if (s1 == s2) { - return (equals == Py_EQ); - } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { - const char *ps1, *ps2; - Py_ssize_t length = PyBytes_GET_SIZE(s1); - if (length != PyBytes_GET_SIZE(s2)) - return (equals == Py_NE); - ps1 = PyBytes_AS_STRING(s1); - ps2 = PyBytes_AS_STRING(s2); - if (ps1[0] != ps2[0]) { - return (equals == Py_NE); - } else if (length == 1) { - return (equals == Py_EQ); - } else { - int result = memcmp(ps1, ps2, (size_t)length); - return (equals == Py_EQ) ? (result == 0) : (result != 0); + if (likely(PyString_Check(n))) +#endif + return __Pyx_PyObject_GetAttrStr(o, n); +#endif + return PyObject_GetAttr(o, n); +} + +/* decode_c_string */ + static CYTHON_INLINE PyObject* __Pyx_decode_c_string( + const char* cstring, Py_ssize_t start, Py_ssize_t stop, + const char* encoding, const char* errors, + PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { + Py_ssize_t length; + if (unlikely((start < 0) | (stop < 0))) { + size_t slen = strlen(cstring); + if (unlikely(slen > (size_t) PY_SSIZE_T_MAX)) { + PyErr_SetString(PyExc_OverflowError, + "c-string too long to convert to Python"); + return NULL; } - } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { - return (equals == Py_NE); - } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { - return (equals == Py_NE); + length = (Py_ssize_t) slen; + if (start < 0) { + start += length; + if (start < 0) + start = 0; + } + if (stop < 0) + stop += length; + } + length = stop - start; + if (unlikely(length <= 0)) + return PyUnicode_FromUnicode(NULL, 0); + cstring += start; + if (decode_func) { + return decode_func(cstring, length, errors); } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; + return PyUnicode_Decode(cstring, length, encoding, errors); } -#endif } -static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { -#if CYTHON_COMPILING_IN_PYPY - return PyObject_RichCompareBool(s1, s2, equals); -#else -#if PY_MAJOR_VERSION < 3 - PyObject* owned_ref = NULL; -#endif - int s1_is_unicode, s2_is_unicode; - if (s1 == s2) { - goto return_eq; +/* PyErrExceptionMatches */ + #if CYTHON_FAST_THREAD_STATE +static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(tuple); +#if PY_MAJOR_VERSION >= 3 + for (i=0; icurexc_type; + if (exc_type == err) return 1; + if (unlikely(!exc_type)) return 0; + if (unlikely(PyTuple_Check(err))) + return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); + return __Pyx_PyErr_GivenExceptionMatches(exc_type, err); +} #endif - if (s1_is_unicode & s2_is_unicode) { - Py_ssize_t length; - int kind; - void *data1, *data2; - if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) - return -1; - length = __Pyx_PyUnicode_GET_LENGTH(s1); - if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { - goto return_ne; - } - kind = __Pyx_PyUnicode_KIND(s1); - if (kind != __Pyx_PyUnicode_KIND(s2)) { - goto return_ne; - } - data1 = __Pyx_PyUnicode_DATA(s1); - data2 = __Pyx_PyUnicode_DATA(s2); - if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { - goto return_ne; - } else if (length == 1) { - goto return_eq; - } else { - int result = memcmp(data1, data2, (size_t)(length * kind)); - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ) ? (result == 0) : (result != 0); - } - } else if ((s1 == Py_None) & s2_is_unicode) { - goto return_ne; - } else if ((s2 == Py_None) & s1_is_unicode) { - goto return_ne; + +/* GetAttr3 */ + static PyObject *__Pyx_GetAttr3Default(PyObject *d) { + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + if (unlikely(!__Pyx_PyErr_ExceptionMatches(PyExc_AttributeError))) + return NULL; + __Pyx_PyErr_Clear(); + Py_INCREF(d); + return d; +} +static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) { + PyObject *r = __Pyx_GetAttr(o, n); + return (likely(r)) ? r : __Pyx_GetAttr3Default(d); +} + +/* GetModuleGlobalName */ + static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { + PyObject *result; +#if !CYTHON_AVOID_BORROWED_REFS + result = PyDict_GetItem(__pyx_d, name); + if (likely(result)) { + Py_INCREF(result); } else { - int result; - PyObject* py_result = PyObject_RichCompare(s1, s2, equals); - if (!py_result) - return -1; - result = __Pyx_PyObject_IsTrue(py_result); - Py_DECREF(py_result); - return result; - } -return_eq: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_EQ); -return_ne: - #if PY_MAJOR_VERSION < 3 - Py_XDECREF(owned_ref); - #endif - return (equals == Py_NE); +#else + result = PyObject_GetItem(__pyx_d, name); + if (!result) { + PyErr_Clear(); #endif + result = __Pyx_GetBuiltinName(name); + } + return result; } -static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t a, Py_ssize_t b) { - Py_ssize_t q = a / b; - Py_ssize_t r = a - q*b; - q -= ((r != 0) & ((r ^ b) < 0)); - return q; +/* ExtTypeTest */ + static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { + if (unlikely(!type)) { + PyErr_SetString(PyExc_SystemError, "Missing type object"); + return 0; + } + if (likely(__Pyx_TypeCheck(obj, type))) + return 1; + PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", + Py_TYPE(obj)->tp_name, type->tp_name); + return 0; } -static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { -#if CYTHON_COMPILING_IN_CPYTHON -#if PY_MAJOR_VERSION >= 3 - if (likely(PyUnicode_Check(n))) +/* SaveResetException */ + #if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { + #if PY_VERSION_HEX >= 0x030700A2 + *type = tstate->exc_state.exc_type; + *value = tstate->exc_state.exc_value; + *tb = tstate->exc_state.exc_traceback; + #else + *type = tstate->exc_type; + *value = tstate->exc_value; + *tb = tstate->exc_traceback; + #endif + Py_XINCREF(*type); + Py_XINCREF(*value); + Py_XINCREF(*tb); +} +static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; + #if PY_VERSION_HEX >= 0x030700A2 + tmp_type = tstate->exc_state.exc_type; + tmp_value = tstate->exc_state.exc_value; + tmp_tb = tstate->exc_state.exc_traceback; + tstate->exc_state.exc_type = type; + tstate->exc_state.exc_value = value; + tstate->exc_state.exc_traceback = tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = type; + tstate->exc_value = value; + tstate->exc_traceback = tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); +} +#endif + +/* GetException */ + #if CYTHON_FAST_THREAD_STATE +static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { +#else +static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { +#endif + PyObject *local_type, *local_value, *local_tb; +#if CYTHON_FAST_THREAD_STATE + PyObject *tmp_type, *tmp_value, *tmp_tb; + local_type = tstate->curexc_type; + local_value = tstate->curexc_value; + local_tb = tstate->curexc_traceback; + tstate->curexc_type = 0; + tstate->curexc_value = 0; + tstate->curexc_traceback = 0; +#else + PyErr_Fetch(&local_type, &local_value, &local_tb); +#endif + PyErr_NormalizeException(&local_type, &local_value, &local_tb); +#if CYTHON_FAST_THREAD_STATE + if (unlikely(tstate->curexc_type)) +#else + if (unlikely(PyErr_Occurred())) +#endif + goto bad; + #if PY_MAJOR_VERSION >= 3 + if (local_tb) { + if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) + goto bad; + } + #endif + Py_XINCREF(local_tb); + Py_XINCREF(local_type); + Py_XINCREF(local_value); + *type = local_type; + *value = local_value; + *tb = local_tb; +#if CYTHON_FAST_THREAD_STATE + #if PY_VERSION_HEX >= 0x030700A2 + tmp_type = tstate->exc_state.exc_type; + tmp_value = tstate->exc_state.exc_value; + tmp_tb = tstate->exc_state.exc_traceback; + tstate->exc_state.exc_type = local_type; + tstate->exc_state.exc_value = local_value; + tstate->exc_state.exc_traceback = local_tb; + #else + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + tstate->exc_type = local_type; + tstate->exc_value = local_value; + tstate->exc_traceback = local_tb; + #endif + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); #else - if (likely(PyString_Check(n))) -#endif - return __Pyx_PyObject_GetAttrStr(o, n); + PyErr_SetExcInfo(local_type, local_value, local_tb); #endif - return PyObject_GetAttr(o, n); -} - -static CYTHON_INLINE PyObject* __Pyx_decode_c_string( - const char* cstring, Py_ssize_t start, Py_ssize_t stop, - const char* encoding, const char* errors, - PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { - Py_ssize_t length; - if (unlikely((start < 0) | (stop < 0))) { - length = strlen(cstring); - if (start < 0) { - start += length; - if (start < 0) - start = 0; - } - if (stop < 0) - stop += length; - } - length = stop - start; - if (unlikely(length <= 0)) - return PyUnicode_FromUnicode(NULL, 0); - cstring += start; - if (decode_func) { - return decode_func(cstring, length, errors); - } else { - return PyUnicode_Decode(cstring, length, encoding, errors); - } -} - -static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { - if (unlikely(!type)) { - PyErr_SetString(PyExc_SystemError, "Missing type object"); - return 0; - } - if (likely(PyObject_TypeCheck(obj, type))) - return 1; - PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", - Py_TYPE(obj)->tp_name, type->tp_name); return 0; +bad: + *type = 0; + *value = 0; + *tb = 0; + Py_XDECREF(local_type); + Py_XDECREF(local_value); + Py_XDECREF(local_tb); + return -1; } -static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { +/* SwapException */ + #if CYTHON_FAST_THREAD_STATE +static CYTHON_INLINE void __Pyx__ExceptionSwap(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; -#if CYTHON_COMPILING_IN_CPYTHON - PyThreadState *tstate = PyThreadState_GET(); + #if PY_VERSION_HEX >= 0x030700A2 + tmp_type = tstate->exc_state.exc_type; + tmp_value = tstate->exc_state.exc_value; + tmp_tb = tstate->exc_state.exc_traceback; + tstate->exc_state.exc_type = *type; + tstate->exc_state.exc_value = *value; + tstate->exc_state.exc_traceback = *tb; + #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = *type; tstate->exc_value = *value; tstate->exc_traceback = *tb; + #endif + *type = tmp_type; + *value = tmp_value; + *tb = tmp_tb; +} #else +static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { + PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); PyErr_SetExcInfo(*type, *value, *tb); -#endif *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } +#endif -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { - PyObject *r; - if (!j) return NULL; - r = PyObject_GetItem(o, j); - Py_DECREF(j); - return r; -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck) { -#if CYTHON_COMPILING_IN_CPYTHON - if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); - if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { - PyObject *r = PyList_GET_ITEM(o, i); - Py_INCREF(r); - return r; +/* Import */ + static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { + PyObject *empty_list = 0; + PyObject *module = 0; + PyObject *global_dict = 0; + PyObject *empty_dict = 0; + PyObject *list; + #if PY_MAJOR_VERSION < 3 + PyObject *py_import; + py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); + if (!py_import) + goto bad; + #endif + if (from_list) + list = from_list; + else { + empty_list = PyList_New(0); + if (!empty_list) + goto bad; + list = empty_list; } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif -} -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, - int wraparound, int boundscheck) { -#if CYTHON_COMPILING_IN_CPYTHON - if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); - if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, i); - Py_INCREF(r); - return r; + global_dict = PyModule_GetDict(__pyx_m); + if (!global_dict) + goto bad; + empty_dict = PyDict_New(); + if (!empty_dict) + goto bad; + { + #if PY_MAJOR_VERSION >= 3 + if (level == -1) { + if (strchr(__Pyx_MODULE_NAME, '.')) { + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, 1); + if (!module) { + if (!PyErr_ExceptionMatches(PyExc_ImportError)) + goto bad; + PyErr_Clear(); + } + } + level = 0; + } + #endif + if (!module) { + #if PY_MAJOR_VERSION < 3 + PyObject *py_level = PyInt_FromLong(level); + if (!py_level) + goto bad; + module = PyObject_CallFunctionObjArgs(py_import, + name, global_dict, empty_dict, list, py_level, NULL); + Py_DECREF(py_level); + #else + module = PyImport_ImportModuleLevelObject( + name, global_dict, empty_dict, list, level); + #endif + } } - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); -#else - return PySequence_GetItem(o, i); -#endif +bad: + #if PY_MAJOR_VERSION < 3 + Py_XDECREF(py_import); + #endif + Py_XDECREF(empty_list); + Py_XDECREF(empty_dict); + return module; } -static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, - int is_list, int wraparound, int boundscheck) { -#if CYTHON_COMPILING_IN_CPYTHON - if (is_list || PyList_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); - if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { - PyObject *r = PyList_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } + +/* PyIntBinop */ + #if !CYTHON_COMPILING_IN_PYPY +static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED int inplace) { + #if PY_MAJOR_VERSION < 3 + if (likely(PyInt_CheckExact(op1))) { + const long b = intval; + long x; + long a = PyInt_AS_LONG(op1); + x = (long)((unsigned long)a + b); + if (likely((x^a) >= 0 || (x^b) >= 0)) + return PyInt_FromLong(x); + return PyLong_Type.tp_as_number->nb_add(op1, op2); } - else if (PyTuple_CheckExact(o)) { - Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); - if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { - PyObject *r = PyTuple_GET_ITEM(o, n); - Py_INCREF(r); - return r; - } - } else { - PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; - if (likely(m && m->sq_item)) { - if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { - Py_ssize_t l = m->sq_length(o); - if (likely(l >= 0)) { - i += l; - } else { - if (PyErr_ExceptionMatches(PyExc_OverflowError)) - PyErr_Clear(); - else - return NULL; - } + #endif + #if CYTHON_USE_PYLONG_INTERNALS + if (likely(PyLong_CheckExact(op1))) { + const long b = intval; + long a, x; +#ifdef HAVE_LONG_LONG + const PY_LONG_LONG llb = intval; + PY_LONG_LONG lla, llx; +#endif + const digit* digits = ((PyLongObject*)op1)->ob_digit; + const Py_ssize_t size = Py_SIZE(op1); + if (likely(__Pyx_sst_abs(size) <= 1)) { + a = likely(size) ? digits[0] : 0; + if (size == -1) a = -a; + } else { + switch (size) { + case -2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; +#ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; +#endif + } + case 2: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; +#ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; +#endif + } + case -3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; +#ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; +#endif + } + case 3: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; +#ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; +#endif + } + case -4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; +#ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; +#endif + } + case 4: + if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); + break; +#ifdef HAVE_LONG_LONG + } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { + lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); + goto long_long; +#endif + } + default: return PyLong_Type.tp_as_number->nb_add(op1, op2); } - return m->sq_item(o, i); } + x = a + b; + return PyLong_FromLong(x); +#ifdef HAVE_LONG_LONG + long_long: + llx = lla + llb; + return PyLong_FromLongLong(llx); +#endif + + } -#else - if (is_list || PySequence_Check(o)) { - return PySequence_GetItem(o, i); + #endif + if (PyFloat_CheckExact(op1)) { + const long b = intval; + double a = PyFloat_AS_DOUBLE(op1); + double result; + PyFPE_START_PROTECT("add", return NULL) + result = ((double)a) + (double)b; + PyFPE_END_PROTECT(result) + return PyFloat_FromDouble(result); } -#endif - return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); + return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); } +#endif -static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { +/* None */ + static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); } -static CYTHON_INLINE long __Pyx_div_long(long a, long b) { +/* None */ + static CYTHON_INLINE long __Pyx_div_long(long a, long b) { long q = a / b; long r = a - q*b; q -= ((r != 0) & ((r ^ b) < 0)); return q; } -static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, +/* WriteUnraisableException */ + static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, - int full_traceback) { + int full_traceback, CYTHON_UNUSED int nogil) { PyObject *old_exc, *old_val, *old_tb; PyObject *ctx; + __Pyx_PyThreadState_declare +#ifdef WITH_THREAD + PyGILState_STATE state; + if (nogil) + state = PyGILState_Ensure(); +#ifdef _MSC_VER + else state = (PyGILState_STATE)-1; +#endif +#endif + __Pyx_PyThreadState_assign __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); if (full_traceback) { Py_XINCREF(old_exc); @@ -19495,26 +22799,140 @@ static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, PyErr_WriteUnraisable(ctx); Py_DECREF(ctx); } +#ifdef WITH_THREAD + if (nogil) + PyGILState_Release(state); +#endif +} + +/* ImportFrom */ + static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { + PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); + if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { + PyErr_Format(PyExc_ImportError, + #if PY_MAJOR_VERSION < 3 + "cannot import name %.230s", PyString_AS_STRING(name)); + #else + "cannot import name %S", name); + #endif + } + return value; +} + +/* HasAttr */ + static CYTHON_INLINE int __Pyx_HasAttr(PyObject *o, PyObject *n) { + PyObject *r; + if (unlikely(!__Pyx_PyBaseString_Check(n))) { + PyErr_SetString(PyExc_TypeError, + "hasattr(): attribute name must be string"); + return -1; + } + r = __Pyx_GetAttr(o, n); + if (unlikely(!r)) { + PyErr_Clear(); + return 0; + } else { + Py_DECREF(r); + return 1; + } } -static int __Pyx_SetVtable(PyObject *dict, void *vtable) { +/* SetVTable */ + static int __Pyx_SetVtable(PyObject *dict, void *vtable) { #if PY_VERSION_HEX >= 0x02070000 PyObject *ob = PyCapsule_New(vtable, 0, 0); #else PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); #endif - if (!ob) - goto bad; - if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) - goto bad; - Py_DECREF(ob); - return 0; -bad: - Py_XDECREF(ob); - return -1; + if (!ob) + goto bad; + if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) + goto bad; + Py_DECREF(ob); + return 0; +bad: + Py_XDECREF(ob); + return -1; +} + +/* SetupReduce */ + static int __Pyx_setup_reduce_is_named(PyObject* meth, PyObject* name) { + int ret; + PyObject *name_attr; + name_attr = __Pyx_PyObject_GetAttrStr(meth, __pyx_n_s_name_2); + if (likely(name_attr)) { + ret = PyObject_RichCompareBool(name_attr, name, Py_EQ); + } else { + ret = -1; + } + if (unlikely(ret < 0)) { + PyErr_Clear(); + ret = 0; + } + Py_XDECREF(name_attr); + return ret; +} +static int __Pyx_setup_reduce(PyObject* type_obj) { + int ret = 0; + PyObject *object_reduce = NULL; + PyObject *object_reduce_ex = NULL; + PyObject *reduce = NULL; + PyObject *reduce_ex = NULL; + PyObject *reduce_cython = NULL; + PyObject *setstate = NULL; + PyObject *setstate_cython = NULL; +#if CYTHON_USE_PYTYPE_LOOKUP + if (_PyType_Lookup((PyTypeObject*)type_obj, __pyx_n_s_getstate)) goto GOOD; +#else + if (PyObject_HasAttr(type_obj, __pyx_n_s_getstate)) goto GOOD; +#endif +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce_ex = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto BAD; +#else + object_reduce_ex = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce_ex); if (!object_reduce_ex) goto BAD; +#endif + reduce_ex = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_ex); if (unlikely(!reduce_ex)) goto BAD; + if (reduce_ex == object_reduce_ex) { +#if CYTHON_USE_PYTYPE_LOOKUP + object_reduce = _PyType_Lookup(&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto BAD; +#else + object_reduce = __Pyx_PyObject_GetAttrStr((PyObject*)&PyBaseObject_Type, __pyx_n_s_reduce); if (!object_reduce) goto BAD; +#endif + reduce = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce); if (unlikely(!reduce)) goto BAD; + if (reduce == object_reduce || __Pyx_setup_reduce_is_named(reduce, __pyx_n_s_reduce_cython)) { + reduce_cython = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_reduce_cython); if (unlikely(!reduce_cython)) goto BAD; + ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce, reduce_cython); if (unlikely(ret < 0)) goto BAD; + ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_reduce_cython); if (unlikely(ret < 0)) goto BAD; + setstate = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_setstate); + if (!setstate) PyErr_Clear(); + if (!setstate || __Pyx_setup_reduce_is_named(setstate, __pyx_n_s_setstate_cython)) { + setstate_cython = __Pyx_PyObject_GetAttrStr(type_obj, __pyx_n_s_setstate_cython); if (unlikely(!setstate_cython)) goto BAD; + ret = PyDict_SetItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate, setstate_cython); if (unlikely(ret < 0)) goto BAD; + ret = PyDict_DelItem(((PyTypeObject*)type_obj)->tp_dict, __pyx_n_s_setstate_cython); if (unlikely(ret < 0)) goto BAD; + } + PyType_Modified((PyTypeObject*)type_obj); + } + } + goto GOOD; +BAD: + if (!PyErr_Occurred()) + PyErr_Format(PyExc_RuntimeError, "Unable to initialize pickling for %s", ((PyTypeObject*)type_obj)->tp_name); + ret = -1; +GOOD: +#if !CYTHON_USE_PYTYPE_LOOKUP + Py_XDECREF(object_reduce); + Py_XDECREF(object_reduce_ex); +#endif + Py_XDECREF(reduce); + Py_XDECREF(reduce_ex); + Py_XDECREF(reduce_cython); + Py_XDECREF(setstate); + Py_XDECREF(setstate_cython); + return ret; } -static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { +/* FetchCommonType */ + static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { PyObject* fake_module; PyTypeObject* cached_type = NULL; fake_module = PyImport_AddModule((char*) "_cython_" CYTHON_ABI); @@ -19552,7 +22970,8 @@ static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { goto done; } -static PyObject * +/* CythonFunction */ + static PyObject * __Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *closure) { if (unlikely(op->func_doc == NULL)) { @@ -19705,15 +23124,25 @@ __Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op) } static int __Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { + int result = 0; PyObject *res = op->defaults_getter((PyObject *) op); if (unlikely(!res)) return -1; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS op->defaults_tuple = PyTuple_GET_ITEM(res, 0); Py_INCREF(op->defaults_tuple); op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); Py_INCREF(op->defaults_kwdict); + #else + op->defaults_tuple = PySequence_ITEM(res, 0); + if (unlikely(!op->defaults_tuple)) result = -1; + else { + op->defaults_kwdict = PySequence_ITEM(res, 1); + if (unlikely(!op->defaults_kwdict)) result = -1; + } + #endif Py_DECREF(res); - return 0; + return result; } static int __Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value) { @@ -19823,11 +23252,8 @@ static PyGetSetDef __pyx_CyFunction_getsets[] = { {(char *) "__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, {0, 0, 0, 0, 0} }; -#ifndef PY_WRITE_RESTRICTED -#define PY_WRITE_RESTRICTED WRITE_RESTRICTED -#endif static PyMemberDef __pyx_CyFunction_members[] = { - {(char *) "__module__", T_OBJECT, offsetof(__pyx_CyFunctionObject, func.m_module), PY_WRITE_RESTRICTED, 0}, + {(char *) "__module__", T_OBJECT, offsetof(PyCFunctionObject, m_module), PY_WRITE_RESTRICTED, 0}, {0, 0, 0, 0, 0} }; static PyObject * @@ -19900,123 +23326,515 @@ __Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) int i; for (i = 0; i < m->defaults_pyobjects; i++) Py_XDECREF(pydefaults[i]); - PyMem_Free(m->defaults); + PyObject_Free(m->defaults); m->defaults = NULL; } - return 0; + return 0; +} +static void __Pyx__CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + if (__Pyx_CyFunction_weakreflist(m) != NULL) + PyObject_ClearWeakRefs((PyObject *) m); + __Pyx_CyFunction_clear(m); + PyObject_GC_Del(m); +} +static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) +{ + PyObject_GC_UnTrack(m); + __Pyx__CyFunction_dealloc(m); +} +static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +{ + Py_VISIT(m->func_closure); + Py_VISIT(m->func.m_module); + Py_VISIT(m->func_dict); + Py_VISIT(m->func_name); + Py_VISIT(m->func_qualname); + Py_VISIT(m->func_doc); + Py_VISIT(m->func_globals); + Py_VISIT(m->func_code); + Py_VISIT(m->func_classobj); + Py_VISIT(m->defaults_tuple); + Py_VISIT(m->defaults_kwdict); + if (m->defaults) { + PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); + int i; + for (i = 0; i < m->defaults_pyobjects; i++) + Py_VISIT(pydefaults[i]); + } + return 0; +} +static PyObject *__Pyx_CyFunction_descr_get(PyObject *func, PyObject *obj, PyObject *type) +{ + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + if (m->flags & __Pyx_CYFUNCTION_STATICMETHOD) { + Py_INCREF(func); + return func; + } + if (m->flags & __Pyx_CYFUNCTION_CLASSMETHOD) { + if (type == NULL) + type = (PyObject *)(Py_TYPE(obj)); + return __Pyx_PyMethod_New(func, type, (PyObject *)(Py_TYPE(type))); + } + if (obj == Py_None) + obj = NULL; + return __Pyx_PyMethod_New(func, obj, type); +} +static PyObject* +__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +{ +#if PY_MAJOR_VERSION >= 3 + return PyUnicode_FromFormat("", + op->func_qualname, (void *)op); +#else + return PyString_FromFormat("", + PyString_AsString(op->func_qualname), (void *)op); +#endif +} +static PyObject * __Pyx_CyFunction_CallMethod(PyObject *func, PyObject *self, PyObject *arg, PyObject *kw) { + PyCFunctionObject* f = (PyCFunctionObject*)func; + PyCFunction meth = f->m_ml->ml_meth; + Py_ssize_t size; + switch (f->m_ml->ml_flags & (METH_VARARGS | METH_KEYWORDS | METH_NOARGS | METH_O)) { + case METH_VARARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) + return (*meth)(self, arg); + break; + case METH_VARARGS | METH_KEYWORDS: + return (*(PyCFunctionWithKeywords)meth)(self, arg, kw); + case METH_NOARGS: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { + size = PyTuple_GET_SIZE(arg); + if (likely(size == 0)) + return (*meth)(self, NULL); + PyErr_Format(PyExc_TypeError, + "%.200s() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", + f->m_ml->ml_name, size); + return NULL; + } + break; + case METH_O: + if (likely(kw == NULL || PyDict_Size(kw) == 0)) { + size = PyTuple_GET_SIZE(arg); + if (likely(size == 1)) { + PyObject *result, *arg0; + #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + arg0 = PyTuple_GET_ITEM(arg, 0); + #else + arg0 = PySequence_ITEM(arg, 0); if (unlikely(!arg0)) return NULL; + #endif + result = (*meth)(self, arg0); + #if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(arg0); + #endif + return result; + } + PyErr_Format(PyExc_TypeError, + "%.200s() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", + f->m_ml->ml_name, size); + return NULL; + } + break; + default: + PyErr_SetString(PyExc_SystemError, "Bad call flags in " + "__Pyx_CyFunction_Call. METH_OLDARGS is no " + "longer supported!"); + return NULL; + } + PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", + f->m_ml->ml_name); + return NULL; +} +static CYTHON_INLINE PyObject *__Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { + return __Pyx_CyFunction_CallMethod(func, ((PyCFunctionObject*)func)->m_self, arg, kw); +} +static PyObject *__Pyx_CyFunction_CallAsMethod(PyObject *func, PyObject *args, PyObject *kw) { + PyObject *result; + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; + if ((cyfunc->flags & __Pyx_CYFUNCTION_CCLASS) && !(cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD)) { + Py_ssize_t argc; + PyObject *new_args; + PyObject *self; + argc = PyTuple_GET_SIZE(args); + new_args = PyTuple_GetSlice(args, 1, argc); + if (unlikely(!new_args)) + return NULL; + self = PyTuple_GetItem(args, 0); + if (unlikely(!self)) { + Py_DECREF(new_args); + return NULL; + } + result = __Pyx_CyFunction_CallMethod(func, self, new_args, kw); + Py_DECREF(new_args); + } else { + result = __Pyx_CyFunction_Call(func, args, kw); + } + return result; +} +static PyTypeObject __pyx_CyFunctionType_type = { + PyVarObject_HEAD_INIT(0, 0) + "cython_function_or_method", + sizeof(__pyx_CyFunctionObject), + 0, + (destructor) __Pyx_CyFunction_dealloc, + 0, + 0, + 0, +#if PY_MAJOR_VERSION < 3 + 0, +#else + 0, +#endif + (reprfunc) __Pyx_CyFunction_repr, + 0, + 0, + 0, + 0, + __Pyx_CyFunction_CallAsMethod, + 0, + 0, + 0, + 0, + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, + 0, + (traverseproc) __Pyx_CyFunction_traverse, + (inquiry) __Pyx_CyFunction_clear, + 0, +#if PY_VERSION_HEX < 0x030500A0 + offsetof(__pyx_CyFunctionObject, func_weakreflist), +#else + offsetof(PyCFunctionObject, m_weakreflist), +#endif + 0, + 0, + __pyx_CyFunction_methods, + __pyx_CyFunction_members, + __pyx_CyFunction_getsets, + 0, + 0, + __Pyx_CyFunction_descr_get, + 0, + offsetof(__pyx_CyFunctionObject, func_dict), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, +#if PY_VERSION_HEX >= 0x030400a1 + 0, +#endif +}; +static int __pyx_CyFunction_init(void) { + __pyx_CyFunctionType = __Pyx_FetchCommonType(&__pyx_CyFunctionType_type); + if (unlikely(__pyx_CyFunctionType == NULL)) { + return -1; + } + return 0; +} +static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *func, size_t size, int pyobjects) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults = PyObject_Malloc(size); + if (unlikely(!m->defaults)) + return PyErr_NoMemory(); + memset(m->defaults, 0, size); + m->defaults_pyobjects = pyobjects; + return m->defaults; +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_tuple = tuple; + Py_INCREF(tuple); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->defaults_kwdict = dict; + Py_INCREF(dict); +} +static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { + __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; + m->func_annotations = dict; + Py_INCREF(dict); +} + +/* FusedFunction */ + static PyObject * +__pyx_FusedFunction_New(PyTypeObject *type, PyMethodDef *ml, int flags, + PyObject *qualname, PyObject *self, + PyObject *module, PyObject *globals, + PyObject *code) +{ + __pyx_FusedFunctionObject *fusedfunc = + (__pyx_FusedFunctionObject *) __Pyx_CyFunction_New(type, ml, flags, qualname, + self, module, globals, code); + if (!fusedfunc) + return NULL; + fusedfunc->__signatures__ = NULL; + fusedfunc->type = NULL; + fusedfunc->self = NULL; + return (PyObject *) fusedfunc; +} +static void +__pyx_FusedFunction_dealloc(__pyx_FusedFunctionObject *self) +{ + PyObject_GC_UnTrack(self); + Py_CLEAR(self->self); + Py_CLEAR(self->type); + Py_CLEAR(self->__signatures__); + __Pyx__CyFunction_dealloc((__pyx_CyFunctionObject *) self); +} +static int +__pyx_FusedFunction_traverse(__pyx_FusedFunctionObject *self, + visitproc visit, + void *arg) +{ + Py_VISIT(self->self); + Py_VISIT(self->type); + Py_VISIT(self->__signatures__); + return __Pyx_CyFunction_traverse((__pyx_CyFunctionObject *) self, visit, arg); +} +static int +__pyx_FusedFunction_clear(__pyx_FusedFunctionObject *self) +{ + Py_CLEAR(self->self); + Py_CLEAR(self->type); + Py_CLEAR(self->__signatures__); + return __Pyx_CyFunction_clear((__pyx_CyFunctionObject *) self); +} +static PyObject * +__pyx_FusedFunction_descr_get(PyObject *self, PyObject *obj, PyObject *type) +{ + __pyx_FusedFunctionObject *func, *meth; + func = (__pyx_FusedFunctionObject *) self; + if (func->self || func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD) { + Py_INCREF(self); + return self; + } + if (obj == Py_None) + obj = NULL; + meth = (__pyx_FusedFunctionObject *) __pyx_FusedFunction_NewEx( + ((PyCFunctionObject *) func)->m_ml, + ((__pyx_CyFunctionObject *) func)->flags, + ((__pyx_CyFunctionObject *) func)->func_qualname, + ((__pyx_CyFunctionObject *) func)->func_closure, + ((PyCFunctionObject *) func)->m_module, + ((__pyx_CyFunctionObject *) func)->func_globals, + ((__pyx_CyFunctionObject *) func)->func_code); + if (!meth) + return NULL; + Py_XINCREF(func->func.func_classobj); + meth->func.func_classobj = func->func.func_classobj; + Py_XINCREF(func->__signatures__); + meth->__signatures__ = func->__signatures__; + Py_XINCREF(type); + meth->type = type; + Py_XINCREF(func->func.defaults_tuple); + meth->func.defaults_tuple = func->func.defaults_tuple; + if (func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD) + obj = type; + Py_XINCREF(obj); + meth->self = obj; + return (PyObject *) meth; } -static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) +static PyObject * +_obj_to_str(PyObject *obj) { - PyObject_GC_UnTrack(m); - if (__Pyx_CyFunction_weakreflist(m) != NULL) - PyObject_ClearWeakRefs((PyObject *) m); - __Pyx_CyFunction_clear(m); - PyObject_GC_Del(m); + if (PyType_Check(obj)) + return PyObject_GetAttr(obj, __pyx_n_s_name_2); + else + return PyObject_Str(obj); } -static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) +static PyObject * +__pyx_FusedFunction_getitem(__pyx_FusedFunctionObject *self, PyObject *idx) { - Py_VISIT(m->func_closure); - Py_VISIT(m->func.m_module); - Py_VISIT(m->func_dict); - Py_VISIT(m->func_name); - Py_VISIT(m->func_qualname); - Py_VISIT(m->func_doc); - Py_VISIT(m->func_globals); - Py_VISIT(m->func_code); - Py_VISIT(m->func_classobj); - Py_VISIT(m->defaults_tuple); - Py_VISIT(m->defaults_kwdict); - if (m->defaults) { - PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); + PyObject *signature = NULL; + PyObject *unbound_result_func; + PyObject *result_func = NULL; + if (self->__signatures__ == NULL) { + PyErr_SetString(PyExc_TypeError, "Function is not fused"); + return NULL; + } + if (PyTuple_Check(idx)) { + PyObject *list = PyList_New(0); + Py_ssize_t n = PyTuple_GET_SIZE(idx); + PyObject *string = NULL; + PyObject *sep = NULL; int i; - for (i = 0; i < m->defaults_pyobjects; i++) - Py_VISIT(pydefaults[i]); + if (!list) + return NULL; + for (i = 0; i < n; i++) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + PyObject *item = PyTuple_GET_ITEM(idx, i); +#else + PyObject *item = PySequence_ITEM(idx, i); +#endif + string = _obj_to_str(item); +#if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_DECREF(item); +#endif + if (!string || PyList_Append(list, string) < 0) + goto __pyx_err; + Py_DECREF(string); + } + sep = PyUnicode_FromString("|"); + if (sep) + signature = PyUnicode_Join(sep, list); +__pyx_err: +; + Py_DECREF(list); + Py_XDECREF(sep); + } else { + signature = _obj_to_str(idx); } - return 0; + if (!signature) + return NULL; + unbound_result_func = PyObject_GetItem(self->__signatures__, signature); + if (unbound_result_func) { + if (self->self || self->type) { + __pyx_FusedFunctionObject *unbound = (__pyx_FusedFunctionObject *) unbound_result_func; + Py_CLEAR(unbound->func.func_classobj); + Py_XINCREF(self->func.func_classobj); + unbound->func.func_classobj = self->func.func_classobj; + result_func = __pyx_FusedFunction_descr_get(unbound_result_func, + self->self, self->type); + } else { + result_func = unbound_result_func; + Py_INCREF(result_func); + } + } + Py_DECREF(signature); + Py_XDECREF(unbound_result_func); + return result_func; } -static PyObject *__Pyx_CyFunction_descr_get(PyObject *func, PyObject *obj, PyObject *type) +static PyObject * +__pyx_FusedFunction_callfunction(PyObject *func, PyObject *args, PyObject *kw) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - if (m->flags & __Pyx_CYFUNCTION_STATICMETHOD) { - Py_INCREF(func); - return func; - } - if (m->flags & __Pyx_CYFUNCTION_CLASSMETHOD) { - if (type == NULL) - type = (PyObject *)(Py_TYPE(obj)); - return __Pyx_PyMethod_New(func, type, (PyObject *)(Py_TYPE(type))); + __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; + int static_specialized = (cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD && + !((__pyx_FusedFunctionObject *) func)->__signatures__); + if (cyfunc->flags & __Pyx_CYFUNCTION_CCLASS && !static_specialized) { + return __Pyx_CyFunction_CallAsMethod(func, args, kw); + } else { + return __Pyx_CyFunction_Call(func, args, kw); } - if (obj == Py_None) - obj = NULL; - return __Pyx_PyMethod_New(func, obj, type); } -static PyObject* -__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) +static PyObject * +__pyx_FusedFunction_call(PyObject *func, PyObject *args, PyObject *kw) { -#if PY_MAJOR_VERSION >= 3 - return PyUnicode_FromFormat("", - op->func_qualname, (void *)op); + __pyx_FusedFunctionObject *binding_func = (__pyx_FusedFunctionObject *) func; + Py_ssize_t argc = PyTuple_GET_SIZE(args); + PyObject *new_args = NULL; + __pyx_FusedFunctionObject *new_func = NULL; + PyObject *result = NULL; + PyObject *self = NULL; + int is_staticmethod = binding_func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD; + int is_classmethod = binding_func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD; + if (binding_func->self) { + Py_ssize_t i; + new_args = PyTuple_New(argc + 1); + if (!new_args) + return NULL; + self = binding_func->self; +#if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_INCREF(self); +#endif + Py_INCREF(self); + PyTuple_SET_ITEM(new_args, 0, self); + for (i = 0; i < argc; i++) { +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + PyObject *item = PyTuple_GET_ITEM(args, i); + Py_INCREF(item); #else - return PyString_FromFormat("", - PyString_AsString(op->func_qualname), (void *)op); + PyObject *item = PySequence_ITEM(args, i); if (unlikely(!item)) goto bad; #endif -} -#if CYTHON_COMPILING_IN_PYPY -static PyObject * __Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { - PyCFunctionObject* f = (PyCFunctionObject*)func; - PyCFunction meth = PyCFunction_GET_FUNCTION(func); - PyObject *self = PyCFunction_GET_SELF(func); - Py_ssize_t size; - switch (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) { - case METH_VARARGS: - if (likely(kw == NULL) || PyDict_Size(kw) == 0) - return (*meth)(self, arg); - break; - case METH_VARARGS | METH_KEYWORDS: - return (*(PyCFunctionWithKeywords)meth)(self, arg, kw); - case METH_NOARGS: - if (likely(kw == NULL) || PyDict_Size(kw) == 0) { - size = PyTuple_GET_SIZE(arg); - if (size == 0) - return (*meth)(self, NULL); - PyErr_Format(PyExc_TypeError, - "%.200s() takes no arguments (%zd given)", - f->m_ml->ml_name, size); + PyTuple_SET_ITEM(new_args, i + 1, item); + } + args = new_args; + } else if (binding_func->type) { + if (argc < 1) { + PyErr_SetString(PyExc_TypeError, "Need at least one argument, 0 given."); return NULL; } - break; - case METH_O: - if (likely(kw == NULL) || PyDict_Size(kw) == 0) { - size = PyTuple_GET_SIZE(arg); - if (size == 1) - return (*meth)(self, PyTuple_GET_ITEM(arg, 0)); +#if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS + self = PyTuple_GET_ITEM(args, 0); +#else + self = PySequence_ITEM(args, 0); if (unlikely(!self)) return NULL; +#endif + } + if (self && !is_classmethod && !is_staticmethod) { + int is_instance = PyObject_IsInstance(self, binding_func->type); + if (unlikely(!is_instance)) { PyErr_Format(PyExc_TypeError, - "%.200s() takes exactly one argument (%zd given)", - f->m_ml->ml_name, size); - return NULL; + "First argument should be of type %.200s, got %.200s.", + ((PyTypeObject *) binding_func->type)->tp_name, + self->ob_type->tp_name); + goto bad; + } else if (unlikely(is_instance == -1)) { + goto bad; } - break; - default: - PyErr_SetString(PyExc_SystemError, "Bad call flags in " - "__Pyx_CyFunction_Call. METH_OLDARGS is no " - "longer supported!"); - return NULL; } - PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", - f->m_ml->ml_name); - return NULL; -} -#else -static PyObject * __Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { - return PyCFunction_Call(func, arg, kw); -} +#if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_XDECREF(self); + self = NULL; #endif -static PyTypeObject __pyx_CyFunctionType_type = { + if (binding_func->__signatures__) { + PyObject *tup; + if (is_staticmethod && binding_func->func.flags & __Pyx_CYFUNCTION_CCLASS) { + tup = PyTuple_Pack(3, args, + kw == NULL ? Py_None : kw, + binding_func->func.defaults_tuple); + if (unlikely(!tup)) goto bad; + new_func = (__pyx_FusedFunctionObject *) __Pyx_CyFunction_CallMethod( + func, binding_func->__signatures__, tup, NULL); + } else { + tup = PyTuple_Pack(4, binding_func->__signatures__, args, + kw == NULL ? Py_None : kw, + binding_func->func.defaults_tuple); + if (unlikely(!tup)) goto bad; + new_func = (__pyx_FusedFunctionObject *) __pyx_FusedFunction_callfunction(func, tup, NULL); + } + Py_DECREF(tup); + if (unlikely(!new_func)) + goto bad; + Py_XINCREF(binding_func->func.func_classobj); + Py_CLEAR(new_func->func.func_classobj); + new_func->func.func_classobj = binding_func->func.func_classobj; + func = (PyObject *) new_func; + } + result = __pyx_FusedFunction_callfunction(func, args, kw); +bad: +#if !(CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS) + Py_XDECREF(self); +#endif + Py_XDECREF(new_args); + Py_XDECREF((PyObject *) new_func); + return result; +} +static PyMemberDef __pyx_FusedFunction_members[] = { + {(char *) "__signatures__", + T_OBJECT, + offsetof(__pyx_FusedFunctionObject, __signatures__), + READONLY, + 0}, + {0, 0, 0, 0, 0}, +}; +static PyMappingMethods __pyx_FusedFunction_mapping_methods = { + 0, + (binaryfunc) __pyx_FusedFunction_getitem, + 0, +}; +static PyTypeObject __pyx_FusedFunctionType_type = { PyVarObject_HEAD_INIT(0, 0) - "cython_function_or_method", - sizeof(__pyx_CyFunctionObject), + "fused_cython_function", + sizeof(__pyx_FusedFunctionObject), 0, - (destructor) __Pyx_CyFunction_dealloc, + (destructor) __pyx_FusedFunction_dealloc, 0, 0, 0, @@ -20025,36 +23843,32 @@ static PyTypeObject __pyx_CyFunctionType_type = { #else 0, #endif - (reprfunc) __Pyx_CyFunction_repr, 0, 0, 0, + &__pyx_FusedFunction_mapping_methods, + 0, + (ternaryfunc) __pyx_FusedFunction_call, 0, - __Pyx_CyFunction_Call, 0, 0, 0, + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, 0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, + (traverseproc) __pyx_FusedFunction_traverse, + (inquiry) __pyx_FusedFunction_clear, 0, - (traverseproc) __Pyx_CyFunction_traverse, - (inquiry) __Pyx_CyFunction_clear, 0, -#if PY_VERSION_HEX < 0x030500A0 - offsetof(__pyx_CyFunctionObject, func_weakreflist), -#else - offsetof(PyCFunctionObject, m_weakreflist), -#endif 0, 0, - __pyx_CyFunction_methods, - __pyx_CyFunction_members, + 0, + __pyx_FusedFunction_members, __pyx_CyFunction_getsets, + &__pyx_CyFunctionType_type, 0, + __pyx_FusedFunction_descr_get, 0, - __Pyx_CyFunction_descr_get, 0, - offsetof(__pyx_CyFunctionObject, func_dict), 0, 0, 0, @@ -20071,504 +23885,822 @@ static PyTypeObject __pyx_CyFunctionType_type = { 0, #endif }; -static int __Pyx_CyFunction_init(void) { -#if !CYTHON_COMPILING_IN_PYPY - __pyx_CyFunctionType_type.tp_call = PyCFunction_Call; -#endif - __pyx_CyFunctionType = __Pyx_FetchCommonType(&__pyx_CyFunctionType_type); - if (__pyx_CyFunctionType == NULL) { +static int __pyx_FusedFunction_init(void) { + __pyx_FusedFunctionType = __Pyx_FetchCommonType(&__pyx_FusedFunctionType_type); + if (__pyx_FusedFunctionType == NULL) { return -1; } return 0; } -static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *func, size_t size, int pyobjects) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->defaults = PyMem_Malloc(size); - if (!m->defaults) - return PyErr_NoMemory(); - memset(m->defaults, 0, size); - m->defaults_pyobjects = pyobjects; - return m->defaults; + +/* CLineInTraceback */ + #ifndef CYTHON_CLINE_IN_TRACEBACK +static int __Pyx_CLineForTraceback(CYTHON_UNUSED PyThreadState *tstate, int c_line) { + PyObject *use_cline; + PyObject *ptype, *pvalue, *ptraceback; +#if CYTHON_COMPILING_IN_CPYTHON + PyObject **cython_runtime_dict; +#endif + __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); +#if CYTHON_COMPILING_IN_CPYTHON + cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); + if (likely(cython_runtime_dict)) { + use_cline = PyDict_GetItem(*cython_runtime_dict, __pyx_n_s_cline_in_traceback); + } else +#endif + { + PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); + if (use_cline_obj) { + use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; + Py_DECREF(use_cline_obj); + } else { + PyErr_Clear(); + use_cline = NULL; + } + } + if (!use_cline) { + c_line = 0; + PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); + } + else if (PyObject_Not(use_cline) != 0) { + c_line = 0; + } + __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); + return c_line; } -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->defaults_tuple = tuple; - Py_INCREF(tuple); +#endif + +/* CodeObjectCache */ + static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { + int start = 0, mid = 0, end = count - 1; + if (end >= 0 && code_line > entries[end].code_line) { + return count; + } + while (start < end) { + mid = start + (end - start) / 2; + if (code_line < entries[mid].code_line) { + end = mid; + } else if (code_line > entries[mid].code_line) { + start = mid + 1; + } else { + return mid; + } + } + if (code_line <= entries[mid].code_line) { + return mid; + } else { + return mid + 1; + } } -static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->defaults_kwdict = dict; - Py_INCREF(dict); +static PyCodeObject *__pyx_find_code_object(int code_line) { + PyCodeObject* code_object; + int pos; + if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { + return NULL; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + return NULL; + } + code_object = __pyx_code_cache.entries[pos].code_object; + Py_INCREF(code_object); + return code_object; } -static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { - __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; - m->func_annotations = dict; - Py_INCREF(dict); +static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { + int pos, i; + __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; + if (unlikely(!code_line)) { + return; + } + if (unlikely(!entries)) { + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); + if (likely(entries)) { + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = 64; + __pyx_code_cache.count = 1; + entries[0].code_line = code_line; + entries[0].code_object = code_object; + Py_INCREF(code_object); + } + return; + } + pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); + if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { + PyCodeObject* tmp = entries[pos].code_object; + entries[pos].code_object = code_object; + Py_DECREF(tmp); + return; + } + if (__pyx_code_cache.count == __pyx_code_cache.max_count) { + int new_max = __pyx_code_cache.max_count + 64; + entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( + __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); + if (unlikely(!entries)) { + return; + } + __pyx_code_cache.entries = entries; + __pyx_code_cache.max_count = new_max; + } + for (i=__pyx_code_cache.count; i>pos; i--) { + entries[i] = entries[i-1]; + } + entries[pos].code_line = code_line; + entries[pos].code_object = code_object; + __pyx_code_cache.count++; + Py_INCREF(code_object); } -static PyObject * -__pyx_FusedFunction_New(PyTypeObject *type, PyMethodDef *ml, int flags, - PyObject *qualname, PyObject *self, - PyObject *module, PyObject *globals, - PyObject *code) +/* AddTraceback */ + #include "compile.h" +#include "frameobject.h" +#include "traceback.h" +static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( + const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyObject *py_srcfile = 0; + PyObject *py_funcname = 0; + #if PY_MAJOR_VERSION < 3 + py_srcfile = PyString_FromString(filename); + #else + py_srcfile = PyUnicode_FromString(filename); + #endif + if (!py_srcfile) goto bad; + if (c_line) { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #else + py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); + #endif + } + else { + #if PY_MAJOR_VERSION < 3 + py_funcname = PyString_FromString(funcname); + #else + py_funcname = PyUnicode_FromString(funcname); + #endif + } + if (!py_funcname) goto bad; + py_code = __Pyx_PyCode_New( + 0, + 0, + 0, + 0, + 0, + __pyx_empty_bytes, /*PyObject *code,*/ + __pyx_empty_tuple, /*PyObject *consts,*/ + __pyx_empty_tuple, /*PyObject *names,*/ + __pyx_empty_tuple, /*PyObject *varnames,*/ + __pyx_empty_tuple, /*PyObject *freevars,*/ + __pyx_empty_tuple, /*PyObject *cellvars,*/ + py_srcfile, /*PyObject *filename,*/ + py_funcname, /*PyObject *name,*/ + py_line, + __pyx_empty_bytes /*PyObject *lnotab*/ + ); + Py_DECREF(py_srcfile); + Py_DECREF(py_funcname); + return py_code; +bad: + Py_XDECREF(py_srcfile); + Py_XDECREF(py_funcname); + return NULL; +} +static void __Pyx_AddTraceback(const char *funcname, int c_line, + int py_line, const char *filename) { + PyCodeObject *py_code = 0; + PyFrameObject *py_frame = 0; + PyThreadState *tstate = __Pyx_PyThreadState_Current; + if (c_line) { + c_line = __Pyx_CLineForTraceback(tstate, c_line); + } + py_code = __pyx_find_code_object(c_line ? -c_line : py_line); + if (!py_code) { + py_code = __Pyx_CreateCodeObjectForTraceback( + funcname, c_line, py_line, filename); + if (!py_code) goto bad; + __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); + } + py_frame = PyFrame_New( + tstate, /*PyThreadState *tstate,*/ + py_code, /*PyCodeObject *code,*/ + __pyx_d, /*PyObject *globals,*/ + 0 /*PyObject *locals*/ + ); + if (!py_frame) goto bad; + __Pyx_PyFrame_SetLineNumber(py_frame, py_line); + PyTraceBack_Here(py_frame); +bad: + Py_XDECREF(py_code); + Py_XDECREF(py_frame); +} + +#if PY_MAJOR_VERSION < 3 +static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { + if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); + if (__Pyx_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); + if (__Pyx_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); + PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); + return -1; +} +static void __Pyx_ReleaseBuffer(Py_buffer *view) { + PyObject *obj = view->obj; + if (!obj) return; + if (PyObject_CheckBuffer(obj)) { + PyBuffer_Release(view); + return; + } + if ((0)) {} + view->obj = NULL; + Py_DECREF(obj); +} +#endif + + + /* MemviewSliceIsContig */ + static int +__pyx_memviewslice_is_contig(const __Pyx_memviewslice mvs, char order, int ndim) { - __pyx_FusedFunctionObject *fusedfunc = - (__pyx_FusedFunctionObject *) __Pyx_CyFunction_New(type, ml, flags, qualname, - self, module, globals, code); - if (!fusedfunc) - return NULL; - fusedfunc->__signatures__ = NULL; - fusedfunc->type = NULL; - fusedfunc->self = NULL; - return (PyObject *) fusedfunc; + int i, index, step, start; + Py_ssize_t itemsize = mvs.memview->view.itemsize; + if (order == 'F') { + step = 1; + start = 0; + } else { + step = -1; + start = ndim - 1; + } + for (i = 0; i < ndim; i++) { + index = start + step * i; + if (mvs.suboffsets[index] >= 0 || mvs.strides[index] != itemsize) + return 0; + itemsize *= mvs.shape[index]; + } + return 1; } -static void __pyx_FusedFunction_dealloc(__pyx_FusedFunctionObject *self) { - __pyx_FusedFunction_clear(self); - __pyx_FusedFunctionType->tp_free((PyObject *) self); + +/* OverlappingSlices */ + static void +__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, + void **out_start, void **out_end, + int ndim, size_t itemsize) +{ + char *start, *end; + int i; + start = end = slice->data; + for (i = 0; i < ndim; i++) { + Py_ssize_t stride = slice->strides[i]; + Py_ssize_t extent = slice->shape[i]; + if (extent == 0) { + *out_start = *out_end = start; + return; + } else { + if (stride > 0) + end += stride * (extent - 1); + else + start += stride * (extent - 1); + } + } + *out_start = start; + *out_end = end + itemsize; } static int -__pyx_FusedFunction_traverse(__pyx_FusedFunctionObject *self, - visitproc visit, - void *arg) +__pyx_slices_overlap(__Pyx_memviewslice *slice1, + __Pyx_memviewslice *slice2, + int ndim, size_t itemsize) { - Py_VISIT(self->self); - Py_VISIT(self->type); - Py_VISIT(self->__signatures__); - return __Pyx_CyFunction_traverse((__pyx_CyFunctionObject *) self, visit, arg); + void *start1, *end1, *start2, *end2; + __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); + __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); + return (start1 < end2) && (start2 < end1); } -static int -__pyx_FusedFunction_clear(__pyx_FusedFunctionObject *self) + +/* Capsule */ + static CYTHON_INLINE PyObject * +__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) { - Py_CLEAR(self->self); - Py_CLEAR(self->type); - Py_CLEAR(self->__signatures__); - return __Pyx_CyFunction_clear((__pyx_CyFunctionObject *) self); + PyObject *cobj; +#if PY_VERSION_HEX >= 0x02070000 + cobj = PyCapsule_New(p, sig, NULL); +#else + cobj = PyCObject_FromVoidPtr(p, NULL); +#endif + return cobj; } -static PyObject * -__pyx_FusedFunction_descr_get(PyObject *self, PyObject *obj, PyObject *type) + +/* IsLittleEndian */ + static CYTHON_INLINE int __Pyx_Is_Little_Endian(void) { - __pyx_FusedFunctionObject *func, *meth; - func = (__pyx_FusedFunctionObject *) self; - if (func->self || func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD) { - Py_INCREF(self); - return self; + union { + uint32_t u32; + uint8_t u8[4]; + } S; + S.u32 = 0x01020304; + return S.u8[0] == 4; +} + +/* BufferFormatCheck */ + static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, + __Pyx_BufFmt_StackElem* stack, + __Pyx_TypeInfo* type) { + stack[0].field = &ctx->root; + stack[0].parent_offset = 0; + ctx->root.type = type; + ctx->root.name = "buffer dtype"; + ctx->root.offset = 0; + ctx->head = stack; + ctx->head->field = &ctx->root; + ctx->fmt_offset = 0; + ctx->head->parent_offset = 0; + ctx->new_packmode = '@'; + ctx->enc_packmode = '@'; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->is_complex = 0; + ctx->is_valid_array = 0; + ctx->struct_alignment = 0; + while (type->typegroup == 'S') { + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = 0; + type = type->fields->type; + } +} +static int __Pyx_BufFmt_ParseNumber(const char** ts) { + int count; + const char* t = *ts; + if (*t < '0' || *t > '9') { + return -1; + } else { + count = *t++ - '0'; + while (*t >= '0' && *t < '9') { + count *= 10; + count += *t++ - '0'; + } } - if (obj == Py_None) - obj = NULL; - meth = (__pyx_FusedFunctionObject *) __pyx_FusedFunction_NewEx( - ((PyCFunctionObject *) func)->m_ml, - ((__pyx_CyFunctionObject *) func)->flags, - ((__pyx_CyFunctionObject *) func)->func_qualname, - ((__pyx_CyFunctionObject *) func)->func_closure, - ((PyCFunctionObject *) func)->m_module, - ((__pyx_CyFunctionObject *) func)->func_globals, - ((__pyx_CyFunctionObject *) func)->func_code); - if (!meth) - return NULL; - Py_XINCREF(func->func.func_classobj); - meth->func.func_classobj = func->func.func_classobj; - Py_XINCREF(func->__signatures__); - meth->__signatures__ = func->__signatures__; - Py_XINCREF(type); - meth->type = type; - Py_XINCREF(func->func.defaults_tuple); - meth->func.defaults_tuple = func->func.defaults_tuple; - if (func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD) - obj = type; - Py_XINCREF(obj); - meth->self = obj; - return (PyObject *) meth; + *ts = t; + return count; } -static PyObject * -_obj_to_str(PyObject *obj) -{ - if (PyType_Check(obj)) - return PyObject_GetAttr(obj, __pyx_n_s_name_2); - else - return PyObject_Str(obj); +static int __Pyx_BufFmt_ExpectNumber(const char **ts) { + int number = __Pyx_BufFmt_ParseNumber(ts); + if (number == -1) + PyErr_Format(PyExc_ValueError,\ + "Does not understand character buffer dtype format string ('%c')", **ts); + return number; } -static PyObject * -__pyx_FusedFunction_getitem(__pyx_FusedFunctionObject *self, PyObject *idx) -{ - PyObject *signature = NULL; - PyObject *unbound_result_func; - PyObject *result_func = NULL; - if (self->__signatures__ == NULL) { - PyErr_SetString(PyExc_TypeError, "Function is not fused"); - return NULL; +static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { + PyErr_Format(PyExc_ValueError, + "Unexpected format string character: '%c'", ch); +} +static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { + switch (ch) { + case 'c': return "'char'"; + case 'b': return "'signed char'"; + case 'B': return "'unsigned char'"; + case 'h': return "'short'"; + case 'H': return "'unsigned short'"; + case 'i': return "'int'"; + case 'I': return "'unsigned int'"; + case 'l': return "'long'"; + case 'L': return "'unsigned long'"; + case 'q': return "'long long'"; + case 'Q': return "'unsigned long long'"; + case 'f': return (is_complex ? "'complex float'" : "'float'"); + case 'd': return (is_complex ? "'complex double'" : "'double'"); + case 'g': return (is_complex ? "'complex long double'" : "'long double'"); + case 'T': return "a struct"; + case 'O': return "Python object"; + case 'P': return "a pointer"; + case 's': case 'p': return "a string"; + case 0: return "end"; + default: return "unparseable format string"; + } +} +static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return 2; + case 'i': case 'I': case 'l': case 'L': return 4; + case 'q': case 'Q': return 8; + case 'f': return (is_complex ? 8 : 4); + case 'd': return (is_complex ? 16 : 8); + case 'g': { + PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); + return 0; } - if (PyTuple_Check(idx)) { - PyObject *list = PyList_New(0); - Py_ssize_t n = PyTuple_GET_SIZE(idx); - PyObject *string = NULL; - PyObject *sep = NULL; - int i; - if (!list) - return NULL; - for (i = 0; i < n; i++) { - PyObject *item = PyTuple_GET_ITEM(idx, i); - string = _obj_to_str(item); - if (!string || PyList_Append(list, string) < 0) - goto __pyx_err; - Py_DECREF(string); - } - sep = PyUnicode_FromString("|"); - if (sep) - signature = PyUnicode_Join(sep, list); -__pyx_err: -; - Py_DECREF(list); - Py_XDECREF(sep); - } else { - signature = _obj_to_str(idx); + case 'O': case 'P': return sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } +} +static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { + switch (ch) { + case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(short); + case 'i': case 'I': return sizeof(int); + case 'l': case 'L': return sizeof(long); + #ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(PY_LONG_LONG); + #endif + case 'f': return sizeof(float) * (is_complex ? 2 : 1); + case 'd': return sizeof(double) * (is_complex ? 2 : 1); + case 'g': return sizeof(long double) * (is_complex ? 2 : 1); + case 'O': case 'P': return sizeof(void*); + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +typedef struct { char c; short x; } __Pyx_st_short; +typedef struct { char c; int x; } __Pyx_st_int; +typedef struct { char c; long x; } __Pyx_st_long; +typedef struct { char c; float x; } __Pyx_st_float; +typedef struct { char c; double x; } __Pyx_st_double; +typedef struct { char c; long double x; } __Pyx_st_longdouble; +typedef struct { char c; void *x; } __Pyx_st_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_st_float) - sizeof(float); + case 'd': return sizeof(__Pyx_st_double) - sizeof(double); + case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; } - if (!signature) - return NULL; - unbound_result_func = PyObject_GetItem(self->__signatures__, signature); - if (unbound_result_func) { - if (self->self || self->type) { - __pyx_FusedFunctionObject *unbound = (__pyx_FusedFunctionObject *) unbound_result_func; - Py_CLEAR(unbound->func.func_classobj); - Py_XINCREF(self->func.func_classobj); - unbound->func.func_classobj = self->func.func_classobj; - result_func = __pyx_FusedFunction_descr_get(unbound_result_func, - self->self, self->type); - } else { - result_func = unbound_result_func; - Py_INCREF(result_func); - } +} +/* These are for computing the padding at the end of the struct to align + on the first member of the struct. This will probably the same as above, + but we don't have any guarantees. + */ +typedef struct { short x; char c; } __Pyx_pad_short; +typedef struct { int x; char c; } __Pyx_pad_int; +typedef struct { long x; char c; } __Pyx_pad_long; +typedef struct { float x; char c; } __Pyx_pad_float; +typedef struct { double x; char c; } __Pyx_pad_double; +typedef struct { long double x; char c; } __Pyx_pad_longdouble; +typedef struct { void *x; char c; } __Pyx_pad_void_p; +#ifdef HAVE_LONG_LONG +typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; +#endif +static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { + switch (ch) { + case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; + case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); + case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); + case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); +#ifdef HAVE_LONG_LONG + case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); +#endif + case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); + case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); + case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); + case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); + default: + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; } - Py_DECREF(signature); - Py_XDECREF(unbound_result_func); - return result_func; } -static PyObject * -__pyx_FusedFunction_callfunction(PyObject *func, PyObject *args, PyObject *kw) -{ - __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; - PyObject *result; - int static_specialized = (cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD && - !((__pyx_FusedFunctionObject *) func)->__signatures__); - if (cyfunc->flags & __Pyx_CYFUNCTION_CCLASS && !static_specialized) { - Py_ssize_t argc; - PyObject *new_args; - PyObject *self; - PyObject *m_self; - argc = PyTuple_GET_SIZE(args); - new_args = PyTuple_GetSlice(args, 1, argc); - if (!new_args) - return NULL; - self = PyTuple_GetItem(args, 0); - if (!self) - return NULL; - m_self = cyfunc->func.m_self; - cyfunc->func.m_self = self; - result = __Pyx_CyFunction_Call(func, new_args, kw); - cyfunc->func.m_self = m_self; - Py_DECREF(new_args); +static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { + switch (ch) { + case 'c': + return 'H'; + case 'b': case 'h': case 'i': + case 'l': case 'q': case 's': case 'p': + return 'I'; + case 'B': case 'H': case 'I': case 'L': case 'Q': + return 'U'; + case 'f': case 'd': case 'g': + return (is_complex ? 'C' : 'R'); + case 'O': + return 'O'; + case 'P': + return 'P'; + default: { + __Pyx_BufFmt_RaiseUnexpectedChar(ch); + return 0; + } + } +} +static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { + if (ctx->head == NULL || ctx->head->field == &ctx->root) { + const char* expected; + const char* quote; + if (ctx->head == NULL) { + expected = "end"; + quote = ""; } else { - result = __Pyx_CyFunction_Call(func, args, kw); + expected = ctx->head->field->type->name; + quote = "'"; } - return result; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected %s%s%s but got %s", + quote, expected, quote, + __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); + } else { + __Pyx_StructField* field = ctx->head->field; + __Pyx_StructField* parent = (ctx->head - 1)->field; + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", + field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), + parent->type->name, field->name); + } } -static PyObject * -__pyx_FusedFunction_call(PyObject *func, PyObject *args, PyObject *kw) -{ - __pyx_FusedFunctionObject *binding_func = (__pyx_FusedFunctionObject *) func; - Py_ssize_t argc = PyTuple_GET_SIZE(args); - PyObject *new_args = NULL; - __pyx_FusedFunctionObject *new_func = NULL; - PyObject *result = NULL; - PyObject *self = NULL; - int is_staticmethod = binding_func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD; - int is_classmethod = binding_func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD; - if (binding_func->self) { - Py_ssize_t i; - new_args = PyTuple_New(argc + 1); - if (!new_args) - return NULL; - self = binding_func->self; - Py_INCREF(self); - PyTuple_SET_ITEM(new_args, 0, self); - for (i = 0; i < argc; i++) { - PyObject *item = PyTuple_GET_ITEM(args, i); - Py_INCREF(item); - PyTuple_SET_ITEM(new_args, i + 1, item); - } - args = new_args; - } else if (binding_func->type) { - if (argc < 1) { - PyErr_SetString(PyExc_TypeError, "Need at least one argument, 0 given."); - return NULL; +static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { + char group; + size_t size, offset, arraysize = 1; + if (ctx->enc_type == 0) return 0; + if (ctx->head->field->type->arraysize[0]) { + int i, ndim = 0; + if (ctx->enc_type == 's' || ctx->enc_type == 'p') { + ctx->is_valid_array = ctx->head->field->type->ndim == 1; + ndim = 1; + if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { + PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %zu", + ctx->head->field->type->arraysize[0], ctx->enc_count); + return -1; } - self = PyTuple_GET_ITEM(args, 0); } - if (self && !is_classmethod && !is_staticmethod && - !PyObject_IsInstance(self, binding_func->type)) { - PyErr_Format(PyExc_TypeError, - "First argument should be of type %.200s, got %.200s.", - ((PyTypeObject *) binding_func->type)->tp_name, - self->ob_type->tp_name); - goto __pyx_err; + if (!ctx->is_valid_array) { + PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", + ctx->head->field->type->ndim, ndim); + return -1; } - if (binding_func->__signatures__) { - PyObject *tup = PyTuple_Pack(4, binding_func->__signatures__, args, - kw == NULL ? Py_None : kw, - binding_func->func.defaults_tuple); - if (!tup) - goto __pyx_err; - new_func = (__pyx_FusedFunctionObject *) __pyx_FusedFunction_callfunction(func, tup, NULL); - Py_DECREF(tup); - if (!new_func) - goto __pyx_err; - Py_XINCREF(binding_func->func.func_classobj); - Py_CLEAR(new_func->func.func_classobj); - new_func->func.func_classobj = binding_func->func.func_classobj; - func = (PyObject *) new_func; + for (i = 0; i < ctx->head->field->type->ndim; i++) { + arraysize *= ctx->head->field->type->arraysize[i]; } - result = __pyx_FusedFunction_callfunction(func, args, kw); -__pyx_err: - Py_XDECREF(new_args); - Py_XDECREF((PyObject *) new_func); - return result; -} -static PyMemberDef __pyx_FusedFunction_members[] = { - {(char *) "__signatures__", - T_OBJECT, - offsetof(__pyx_FusedFunctionObject, __signatures__), - READONLY, - 0}, - {0, 0, 0, 0, 0}, -}; -static PyMappingMethods __pyx_FusedFunction_mapping_methods = { - 0, - (binaryfunc) __pyx_FusedFunction_getitem, - 0, -}; -static PyTypeObject __pyx_FusedFunctionType_type = { - PyVarObject_HEAD_INIT(0, 0) - "fused_cython_function", - sizeof(__pyx_FusedFunctionObject), - 0, - (destructor) __pyx_FusedFunction_dealloc, - 0, - 0, - 0, -#if PY_MAJOR_VERSION < 3 - 0, -#else - 0, -#endif - 0, - 0, - 0, - &__pyx_FusedFunction_mapping_methods, - 0, - (ternaryfunc) __pyx_FusedFunction_call, - 0, - 0, - 0, - 0, - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, - 0, - (traverseproc) __pyx_FusedFunction_traverse, - (inquiry) __pyx_FusedFunction_clear, - 0, - 0, - 0, - 0, - 0, - __pyx_FusedFunction_members, - __pyx_CyFunction_getsets, - &__pyx_CyFunctionType_type, - 0, - __pyx_FusedFunction_descr_get, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, -#if PY_VERSION_HEX >= 0x030400a1 - 0, -#endif -}; -static int __pyx_FusedFunction_init(void) { - __pyx_FusedFunctionType = __Pyx_FetchCommonType(&__pyx_FusedFunctionType_type); - if (__pyx_FusedFunctionType == NULL) { - return -1; + ctx->is_valid_array = 0; + ctx->enc_count = 1; + } + group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); + do { + __Pyx_StructField* field = ctx->head->field; + __Pyx_TypeInfo* type = field->type; + if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { + size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); + } else { + size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); } - return 0; -} - -static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { - int start = 0, mid = 0, end = count - 1; - if (end >= 0 && code_line > entries[end].code_line) { - return count; + if (ctx->enc_packmode == '@') { + size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); + size_t align_mod_offset; + if (align_at == 0) return -1; + align_mod_offset = ctx->fmt_offset % align_at; + if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; + if (ctx->struct_alignment == 0) + ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, + ctx->is_complex); } - while (start < end) { - mid = (start + end) / 2; - if (code_line < entries[mid].code_line) { - end = mid; - } else if (code_line > entries[mid].code_line) { - start = mid + 1; - } else { - return mid; - } + if (type->size != size || type->typegroup != group) { + if (type->typegroup == 'C' && type->fields != NULL) { + size_t parent_offset = ctx->head->parent_offset + field->offset; + ++ctx->head; + ctx->head->field = type->fields; + ctx->head->parent_offset = parent_offset; + continue; + } + if ((type->typegroup == 'H' || group == 'H') && type->size == size) { + } else { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } } - if (code_line <= entries[mid].code_line) { - return mid; - } else { - return mid + 1; + offset = ctx->head->parent_offset + field->offset; + if (ctx->fmt_offset != offset) { + PyErr_Format(PyExc_ValueError, + "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", + (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); + return -1; + } + ctx->fmt_offset += size; + if (arraysize) + ctx->fmt_offset += (arraysize - 1) * size; + --ctx->enc_count; + while (1) { + if (field == &ctx->root) { + ctx->head = NULL; + if (ctx->enc_count != 0) { + __Pyx_BufFmt_RaiseExpected(ctx); + return -1; + } + break; + } + ctx->head->field = ++field; + if (field->type == NULL) { + --ctx->head; + field = ctx->head->field; + continue; + } else if (field->type->typegroup == 'S') { + size_t parent_offset = ctx->head->parent_offset + field->offset; + if (field->type->fields->type == NULL) continue; + field = field->type->fields; + ++ctx->head; + ctx->head->field = field; + ctx->head->parent_offset = parent_offset; + break; + } else { + break; + } } + } while (ctx->enc_count); + ctx->enc_type = 0; + ctx->is_complex = 0; + return 0; } -static PyCodeObject *__pyx_find_code_object(int code_line) { - PyCodeObject* code_object; - int pos; - if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { +static PyObject * +__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) +{ + const char *ts = *tsp; + int i = 0, number; + int ndim = ctx->head->field->type->ndim; +; + ++ts; + if (ctx->new_count != 1) { + PyErr_SetString(PyExc_ValueError, + "Cannot handle repeated arrays in format string"); return NULL; } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + while (*ts && *ts != ')') { + switch (*ts) { + case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; + default: break; + } + number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) + return PyErr_Format(PyExc_ValueError, + "Expected a dimension of size %zu, got %d", + ctx->head->field->type->arraysize[i], number); + if (*ts != ',' && *ts != ')') + return PyErr_Format(PyExc_ValueError, + "Expected a comma in format string, got '%c'", *ts); + if (*ts == ',') ts++; + i++; + } + if (i != ndim) + return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", + ctx->head->field->type->ndim, i); + if (!*ts) { + PyErr_SetString(PyExc_ValueError, + "Unexpected end of format string, expected ')'"); return NULL; } - code_object = __pyx_code_cache.entries[pos].code_object; - Py_INCREF(code_object); - return code_object; + ctx->is_valid_array = 1; + ctx->new_count = 1; + *tsp = ++ts; + return Py_None; } -static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { - int pos, i; - __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; - if (unlikely(!code_line)) { - return; - } - if (unlikely(!entries)) { - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); - if (likely(entries)) { - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = 64; - __pyx_code_cache.count = 1; - entries[0].code_line = code_line; - entries[0].code_object = code_object; - Py_INCREF(code_object); +static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { + int got_Z = 0; + while (1) { + switch(*ts) { + case 0: + if (ctx->enc_type != 0 && ctx->head == NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; } - return; - } - pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); - if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { - PyCodeObject* tmp = entries[pos].code_object; - entries[pos].code_object = code_object; - Py_DECREF(tmp); - return; - } - if (__pyx_code_cache.count == __pyx_code_cache.max_count) { - int new_max = __pyx_code_cache.max_count + 64; - entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( - __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); - if (unlikely(!entries)) { - return; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + if (ctx->head != NULL) { + __Pyx_BufFmt_RaiseExpected(ctx); + return NULL; + } + return ts; + case ' ': + case '\r': + case '\n': + ++ts; + break; + case '<': + if (!__Pyx_Is_Little_Endian()) { + PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '>': + case '!': + if (__Pyx_Is_Little_Endian()) { + PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); + return NULL; + } + ctx->new_packmode = '='; + ++ts; + break; + case '=': + case '@': + case '^': + ctx->new_packmode = *ts++; + break; + case 'T': + { + const char* ts_after_sub; + size_t i, struct_count = ctx->new_count; + size_t struct_alignment = ctx->struct_alignment; + ctx->new_count = 1; + ++ts; + if (*ts != '{') { + PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); + return NULL; + } + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + ctx->enc_count = 0; + ctx->struct_alignment = 0; + ++ts; + ts_after_sub = ts; + for (i = 0; i != struct_count; ++i) { + ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); + if (!ts_after_sub) return NULL; + } + ts = ts_after_sub; + if (struct_alignment) ctx->struct_alignment = struct_alignment; + } + break; + case '}': + { + size_t alignment = ctx->struct_alignment; + ++ts; + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_type = 0; + if (alignment && ctx->fmt_offset % alignment) { + ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); + } + } + return ts; + case 'x': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->fmt_offset += ctx->new_count; + ctx->new_count = 1; + ctx->enc_count = 0; + ctx->enc_type = 0; + ctx->enc_packmode = ctx->new_packmode; + ++ts; + break; + case 'Z': + got_Z = 1; + ++ts; + if (*ts != 'f' && *ts != 'd' && *ts != 'g') { + __Pyx_BufFmt_RaiseUnexpectedChar('Z'); + return NULL; + } + case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': + case 'l': case 'L': case 'q': case 'Q': + case 'f': case 'd': case 'g': + case 'O': case 'p': + if (ctx->enc_type == *ts && got_Z == ctx->is_complex && + ctx->enc_packmode == ctx->new_packmode) { + ctx->enc_count += ctx->new_count; + ctx->new_count = 1; + got_Z = 0; + ++ts; + break; + } + case 's': + if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; + ctx->enc_count = ctx->new_count; + ctx->enc_packmode = ctx->new_packmode; + ctx->enc_type = *ts; + ctx->is_complex = got_Z; + ++ts; + ctx->new_count = 1; + got_Z = 0; + break; + case ':': + ++ts; + while(*ts != ':') ++ts; + ++ts; + break; + case '(': + if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; + break; + default: + { + int number = __Pyx_BufFmt_ExpectNumber(&ts); + if (number == -1) return NULL; + ctx->new_count = (size_t)number; } - __pyx_code_cache.entries = entries; - __pyx_code_cache.max_count = new_max; - } - for (i=__pyx_code_cache.count; i>pos; i--) { - entries[i] = entries[i-1]; - } - entries[pos].code_line = code_line; - entries[pos].code_object = code_object; - __pyx_code_cache.count++; - Py_INCREF(code_object); -} - -#include "compile.h" -#include "frameobject.h" -#include "traceback.h" -static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( - const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyObject *py_srcfile = 0; - PyObject *py_funcname = 0; - #if PY_MAJOR_VERSION < 3 - py_srcfile = PyString_FromString(filename); - #else - py_srcfile = PyUnicode_FromString(filename); - #endif - if (!py_srcfile) goto bad; - if (c_line) { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #else - py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); - #endif - } - else { - #if PY_MAJOR_VERSION < 3 - py_funcname = PyString_FromString(funcname); - #else - py_funcname = PyUnicode_FromString(funcname); - #endif - } - if (!py_funcname) goto bad; - py_code = __Pyx_PyCode_New( - 0, - 0, - 0, - 0, - 0, - __pyx_empty_bytes, /*PyObject *code,*/ - __pyx_empty_tuple, /*PyObject *consts,*/ - __pyx_empty_tuple, /*PyObject *names,*/ - __pyx_empty_tuple, /*PyObject *varnames,*/ - __pyx_empty_tuple, /*PyObject *freevars,*/ - __pyx_empty_tuple, /*PyObject *cellvars,*/ - py_srcfile, /*PyObject *filename,*/ - py_funcname, /*PyObject *name,*/ - py_line, - __pyx_empty_bytes /*PyObject *lnotab*/ - ); - Py_DECREF(py_srcfile); - Py_DECREF(py_funcname); - return py_code; -bad: - Py_XDECREF(py_srcfile); - Py_XDECREF(py_funcname); - return NULL; -} -static void __Pyx_AddTraceback(const char *funcname, int c_line, - int py_line, const char *filename) { - PyCodeObject *py_code = 0; - PyFrameObject *py_frame = 0; - py_code = __pyx_find_code_object(c_line ? c_line : py_line); - if (!py_code) { - py_code = __Pyx_CreateCodeObjectForTraceback( - funcname, c_line, py_line, filename); - if (!py_code) goto bad; - __pyx_insert_code_object(c_line ? c_line : py_line, py_code); } - py_frame = PyFrame_New( - PyThreadState_GET(), /*PyThreadState *tstate,*/ - py_code, /*PyCodeObject *code,*/ - __pyx_d, /*PyObject *globals,*/ - 0 /*PyObject *locals*/ - ); - if (!py_frame) goto bad; - py_frame->f_lineno = py_line; - PyTraceBack_Here(py_frame); -bad: - Py_XDECREF(py_code); - Py_XDECREF(py_frame); + } } -static int +/* TypeInfoCompare */ + static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) { int i; @@ -20608,7 +24740,8 @@ __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) return 1; } -static int +/* MemviewSliceValidateAndInit */ + static int __pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) { if (buf->shape[dim] <= 1) @@ -20789,7 +24922,8 @@ static int __Pyx_ValidateAndInit_memviewslice( return retval; } -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_short(PyObject *obj) { +/* ObjectToMemviewSlice */ + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_short(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; @@ -20811,7 +24945,8 @@ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_sho return result; } -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int(PyObject *obj) { +/* ObjectToMemviewSlice */ + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; @@ -20833,7 +24968,8 @@ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int return result; } -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_long(PyObject *obj) { +/* ObjectToMemviewSlice */ + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_long(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; @@ -20855,7 +24991,8 @@ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_lon return result; } -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_PY_LONG_LONG(PyObject *obj) { +/* ObjectToMemviewSlice */ + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_PY_LONG_LONG(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; @@ -20877,7 +25014,8 @@ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_PY_ return result; } -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_char(PyObject *obj) { +/* ObjectToMemviewSlice */ + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_char(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; @@ -20899,7 +25037,8 @@ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_uns return result; } -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_char(PyObject *obj) { +/* ObjectToMemviewSlice */ + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_char(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; @@ -20921,7 +25060,8 @@ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_cha return result; } -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_int(PyObject *obj) { +/* ObjectToMemviewSlice */ + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_unsigned_int(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; @@ -20943,100 +25083,7 @@ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_uns return result; } -static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { - PyObject *empty_list = 0; - PyObject *module = 0; - PyObject *global_dict = 0; - PyObject *empty_dict = 0; - PyObject *list; - #if PY_VERSION_HEX < 0x03030000 - PyObject *py_import; - py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); - if (!py_import) - goto bad; - #endif - if (from_list) - list = from_list; - else { - empty_list = PyList_New(0); - if (!empty_list) - goto bad; - list = empty_list; - } - global_dict = PyModule_GetDict(__pyx_m); - if (!global_dict) - goto bad; - empty_dict = PyDict_New(); - if (!empty_dict) - goto bad; - { - #if PY_MAJOR_VERSION >= 3 - if (level == -1) { - if (strchr(__Pyx_MODULE_NAME, '.')) { - #if PY_VERSION_HEX < 0x03030000 - PyObject *py_level = PyInt_FromLong(1); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, 1); - #endif - if (!module) { - if (!PyErr_ExceptionMatches(PyExc_ImportError)) - goto bad; - PyErr_Clear(); - } - } - level = 0; - } - #endif - if (!module) { - #if PY_VERSION_HEX < 0x03030000 - PyObject *py_level = PyInt_FromLong(level); - if (!py_level) - goto bad; - module = PyObject_CallFunctionObjArgs(py_import, - name, global_dict, empty_dict, list, py_level, NULL); - Py_DECREF(py_level); - #else - module = PyImport_ImportModuleLevelObject( - name, global_dict, empty_dict, list, level); - #endif - } - } -bad: - #if PY_VERSION_HEX < 0x03030000 - Py_XDECREF(py_import); - #endif - Py_XDECREF(empty_list); - Py_XDECREF(empty_dict); - return module; -} - -#if PY_MAJOR_VERSION < 3 -static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { - if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); - if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); - if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); - PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); - return -1; -} -static void __Pyx_ReleaseBuffer(Py_buffer *view) { - PyObject *obj = view->obj; - if (!obj) return; - if (PyObject_CheckBuffer(obj)) { - PyBuffer_Release(view); - return; - } - Py_DECREF(obj); - view->obj = NULL; -} -#endif - - +/* ObjectToMemviewSlice */ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_double(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; @@ -21059,7 +25106,8 @@ static void __Pyx_ReleaseBuffer(Py_buffer *view) { return result; } -static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_double(PyObject *obj) { +/* ObjectToMemviewSlice */ + static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_double(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; @@ -21081,160 +25129,167 @@ static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_dou return result; } -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { - const long neg_one = (long) -1, const_zero = 0; +/* CIntToPy */ + static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { + const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); - } else if (sizeof(long) <= sizeof(unsigned long long)) { - return PyLong_FromUnsignedLongLong((unsigned long long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); - } else if (sizeof(long) <= sizeof(long long)) { - return PyLong_FromLongLong((long long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(long), + little, !is_unsigned); + } +} + +/* CIntToPy */ + static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { + const int neg_one = (int) -1, const_zero = (int) 0; + const int is_unsigned = neg_one > const_zero; + if (is_unsigned) { + if (sizeof(int) < sizeof(long)) { + return PyInt_FromLong((long) value); + } else if (sizeof(int) <= sizeof(unsigned long)) { + return PyLong_FromUnsignedLong((unsigned long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); +#endif + } + } else { + if (sizeof(int) <= sizeof(long)) { + return PyInt_FromLong((long) value); +#ifdef HAVE_LONG_LONG + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + return PyLong_FromLongLong((PY_LONG_LONG) value); +#endif + } + } + { + int one = 1; int little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&value; + return _PyLong_FromByteArray(bytes, sizeof(int), + little, !is_unsigned); + } +} + +/* CIntFromPyVerify */ + #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) +#define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ + __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) +#define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ + {\ + func_type value = func_value;\ + if (sizeof(target_type) < sizeof(func_type)) {\ + if (unlikely(value != (func_type) (target_type) value)) {\ + func_type zero = 0;\ + if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ + return (target_type) -1;\ + if (is_unsigned && unlikely(value < zero))\ + goto raise_neg_overflow;\ + else\ + goto raise_overflow;\ + }\ + }\ + return (target_type) value;\ + } + +/* MemviewSliceCopyTemplate */ + static __Pyx_memviewslice +__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, + const char *mode, int ndim, + size_t sizeof_dtype, int contig_flag, + int dtype_is_object) +{ + __Pyx_RefNannyDeclarations + int i; + __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; + struct __pyx_memoryview_obj *from_memview = from_mvs->memview; + Py_buffer *buf = &from_memview->view; + PyObject *shape_tuple = NULL; + PyObject *temp_int = NULL; + struct __pyx_array_obj *array_obj = NULL; + struct __pyx_memoryview_obj *memview_obj = NULL; + __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); + for (i = 0; i < ndim; i++) { + if (from_mvs->suboffsets[i] >= 0) { + PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " + "indirect dimensions (axis %d)", i); + goto fail; } } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(long), - little, !is_unsigned); - } -} - -#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value) \ - { \ - func_type value = func_value; \ - if (sizeof(target_type) < sizeof(func_type)) { \ - if (unlikely(value != (func_type) (target_type) value)) { \ - func_type zero = 0; \ - if (is_unsigned && unlikely(value < zero)) \ - goto raise_neg_overflow; \ - else \ - goto raise_overflow; \ - } \ - } \ - return (target_type) value; \ + shape_tuple = PyTuple_New(ndim); + if (unlikely(!shape_tuple)) { + goto fail; } - -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 - #if CYTHON_USE_PYLONG_INTERNALS - #include "longintrepr.h" - #endif -#endif - -static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { - const char neg_one = (char) -1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; -#if PY_MAJOR_VERSION < 3 - if (likely(PyInt_Check(x))) { - if (sizeof(char) < sizeof(long)) { - __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG(x)) - } else { - long val = PyInt_AS_LONG(x); - if (is_unsigned && unlikely(val < 0)) { - goto raise_neg_overflow; - } - return (char) val; - } - } else -#endif - if (likely(PyLong_Check(x))) { - if (is_unsigned) { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 - #if CYTHON_USE_PYLONG_INTERNALS - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: __PYX_VERIFY_RETURN_INT(char, digit, ((PyLongObject*)x)->ob_digit[0]); - } - #endif -#endif - if (unlikely(Py_SIZE(x) < 0)) { - goto raise_neg_overflow; - } - if (sizeof(char) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT(char, unsigned long, PyLong_AsUnsignedLong(x)) - } else if (sizeof(char) <= sizeof(unsigned long long)) { - __PYX_VERIFY_RETURN_INT(char, unsigned long long, PyLong_AsUnsignedLongLong(x)) - } + __Pyx_GOTREF(shape_tuple); + for(i = 0; i < ndim; i++) { + temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); + if(unlikely(!temp_int)) { + goto fail; } else { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 - #if CYTHON_USE_PYLONG_INTERNALS - switch (Py_SIZE(x)) { - case 0: return 0; - case 1: __PYX_VERIFY_RETURN_INT(char, digit, +(((PyLongObject*)x)->ob_digit[0])); - case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); - } - #endif -#endif - if (sizeof(char) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT(char, long, PyLong_AsLong(x)) - } else if (sizeof(char) <= sizeof(long long)) { - __PYX_VERIFY_RETURN_INT(char, long long, PyLong_AsLongLong(x)) - } - } - { -#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) - PyErr_SetString(PyExc_RuntimeError, - "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); -#else - char val; - PyObject *v = __Pyx_PyNumber_Int(x); - #if PY_MAJOR_VERSION < 3 - if (likely(v) && !PyLong_Check(v)) { - PyObject *tmp = v; - v = PyNumber_Long(tmp); - Py_DECREF(tmp); - } - #endif - if (likely(v)) { - int one = 1; int is_little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&val; - int ret = _PyLong_AsByteArray((PyLongObject *)v, - bytes, sizeof(val), - is_little, !is_unsigned); - Py_DECREF(v); - if (likely(!ret)) - return val; - } -#endif - return (char) -1; + PyTuple_SET_ITEM(shape_tuple, i, temp_int); + temp_int = NULL; } - } else { - char val; - PyObject *tmp = __Pyx_PyNumber_Int(x); - if (!tmp) return (char) -1; - val = __Pyx_PyInt_As_char(tmp); - Py_DECREF(tmp); - return val; } -raise_overflow: - PyErr_SetString(PyExc_OverflowError, - "value too large to convert to char"); - return (char) -1; -raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to char"); - return (char) -1; + array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); + if (unlikely(!array_obj)) { + goto fail; + } + __Pyx_GOTREF(array_obj); + memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( + (PyObject *) array_obj, contig_flag, + dtype_is_object, + from_mvs->memview->typeinfo); + if (unlikely(!memview_obj)) + goto fail; + if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) + goto fail; + if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, + dtype_is_object) < 0)) + goto fail; + goto no_fail; +fail: + __Pyx_XDECREF(new_mvs.memview); + new_mvs.memview = NULL; + new_mvs.data = NULL; +no_fail: + __Pyx_XDECREF(shape_tuple); + __Pyx_XDECREF(temp_int); + __Pyx_XDECREF(array_obj); + __Pyx_RefNannyFinishContext(); + return new_mvs; } -static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character) { +/* BytesContains */ + static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character) { const Py_ssize_t length = PyBytes_GET_SIZE(bytes); char* char_start = PyBytes_AS_STRING(bytes); - char* pos; - for (pos=char_start; pos < char_start+length; pos++) { - if (character == pos[0]) return 1; - } - return 0; + return memchr(char_start, (unsigned char)character, (size_t)length) != NULL; } -static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { - const int neg_one = (int) -1, const_zero = 0; +/* CIntFromPy */ + static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { + const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { @@ -21251,36 +25306,129 @@ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 - #if CYTHON_USE_PYLONG_INTERNALS +#if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { - case 0: return 0; - case 1: __PYX_VERIFY_RETURN_INT(int, digit, ((PyLongObject*)x)->ob_digit[0]); + case 0: return (int) 0; + case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) + case 2: + if (8 * sizeof(int) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { + return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 3: + if (8 * sizeof(int) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { + return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; + case 4: + if (8 * sizeof(int) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { + return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); + } + } + break; } - #endif #endif +#if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (int) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif if (sizeof(int) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong(x)) - } else if (sizeof(int) <= sizeof(unsigned long long)) { - __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong(x)) + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif } } else { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 - #if CYTHON_USE_PYLONG_INTERNALS +#if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { - case 0: return 0; - case 1: __PYX_VERIFY_RETURN_INT(int, digit, +(((PyLongObject*)x)->ob_digit[0])); - case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + case 0: return (int) 0; + case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) + case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) + case -2: + if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { + return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 2: + if (8 * sizeof(int) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { + return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -3: + if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { + return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 3: + if (8 * sizeof(int) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { + return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case -4: + if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { + return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; + case 4: + if (8 * sizeof(int) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { + return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); + } + } + break; } - #endif #endif if (sizeof(int) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong(x)) - } else if (sizeof(int) <= sizeof(long long)) { - __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong(x)) + __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif } } { @@ -21289,7 +25437,7 @@ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; - PyObject *v = __Pyx_PyNumber_Int(x); + PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; @@ -21312,7 +25460,7 @@ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { } } else { int val; - PyObject *tmp = __Pyx_PyNumber_Int(x); + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); @@ -21323,174 +25471,40 @@ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { "value too large to convert to int"); return (int) -1; raise_neg_overflow: - PyErr_SetString(PyExc_OverflowError, - "can't convert negative value to int"); - return (int) -1; -} - -static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { - const int neg_one = (int) -1, const_zero = 0; - const int is_unsigned = neg_one > const_zero; - if (is_unsigned) { - if (sizeof(int) < sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(int) <= sizeof(unsigned long)) { - return PyLong_FromUnsignedLong((unsigned long) value); - } else if (sizeof(int) <= sizeof(unsigned long long)) { - return PyLong_FromUnsignedLongLong((unsigned long long) value); - } - } else { - if (sizeof(int) <= sizeof(long)) { - return PyInt_FromLong((long) value); - } else if (sizeof(int) <= sizeof(long long)) { - return PyLong_FromLongLong((long long) value); - } - } - { - int one = 1; int little = (int)*(unsigned char *)&one; - unsigned char *bytes = (unsigned char *)&value; - return _PyLong_FromByteArray(bytes, sizeof(int), - little, !is_unsigned); - } -} - -static int -__pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, - char order, int ndim) -{ - int i, index, step, start; - Py_ssize_t itemsize = mvs->memview->view.itemsize; - if (order == 'F') { - step = 1; - start = 0; - } else { - step = -1; - start = ndim - 1; - } - for (i = 0; i < ndim; i++) { - index = start + step * i; - if (mvs->suboffsets[index] >= 0 || mvs->strides[index] != itemsize) - return 0; - itemsize *= mvs->shape[index]; - } - return 1; -} - -static void -__pyx_get_array_memory_extents(__Pyx_memviewslice *slice, - void **out_start, void **out_end, - int ndim, size_t itemsize) -{ - char *start, *end; - int i; - start = end = slice->data; - for (i = 0; i < ndim; i++) { - Py_ssize_t stride = slice->strides[i]; - Py_ssize_t extent = slice->shape[i]; - if (extent == 0) { - *out_start = *out_end = start; - return; - } else { - if (stride > 0) - end += stride * (extent - 1); - else - start += stride * (extent - 1); - } - } - *out_start = start; - *out_end = end + itemsize; -} -static int -__pyx_slices_overlap(__Pyx_memviewslice *slice1, - __Pyx_memviewslice *slice2, - int ndim, size_t itemsize) -{ - void *start1, *end1, *start2, *end2; - __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); - __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); - return (start1 < end2) && (start2 < end1); -} - -static __Pyx_memviewslice -__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, - const char *mode, int ndim, - size_t sizeof_dtype, int contig_flag, - int dtype_is_object) -{ - __Pyx_RefNannyDeclarations - int i; - __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; - struct __pyx_memoryview_obj *from_memview = from_mvs->memview; - Py_buffer *buf = &from_memview->view; - PyObject *shape_tuple = NULL; - PyObject *temp_int = NULL; - struct __pyx_array_obj *array_obj = NULL; - struct __pyx_memoryview_obj *memview_obj = NULL; - __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); - for (i = 0; i < ndim; i++) { - if (from_mvs->suboffsets[i] >= 0) { - PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " - "indirect dimensions (axis %d)", i); - goto fail; - } - } - shape_tuple = PyTuple_New(ndim); - if (unlikely(!shape_tuple)) { - goto fail; + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to int"); + return (int) -1; +} + +/* ImportNumPyArray */ + static PyObject* __Pyx__ImportNumPyArray(void) { + PyObject *numpy_module, *ndarray_object = NULL; + numpy_module = __Pyx_Import(__pyx_n_s_numpy, NULL, 0); + if (likely(numpy_module)) { + ndarray_object = PyObject_GetAttrString(numpy_module, "ndarray"); + Py_DECREF(numpy_module); } - __Pyx_GOTREF(shape_tuple); - for(i = 0; i < ndim; i++) { - temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); - if(unlikely(!temp_int)) { - goto fail; - } else { - PyTuple_SET_ITEM(shape_tuple, i, temp_int); - temp_int = NULL; - } + if (unlikely(!ndarray_object)) { + PyErr_Clear(); } - array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); - if (unlikely(!array_obj)) { - goto fail; + if (unlikely(!ndarray_object || !PyObject_TypeCheck(ndarray_object, &PyType_Type))) { + Py_XDECREF(ndarray_object); + Py_INCREF(Py_None); + ndarray_object = Py_None; } - __Pyx_GOTREF(array_obj); - memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( - (PyObject *) array_obj, contig_flag, - dtype_is_object, - from_mvs->memview->typeinfo); - if (unlikely(!memview_obj)) - goto fail; - if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) - goto fail; - if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, - dtype_is_object) < 0)) - goto fail; - goto no_fail; -fail: - __Pyx_XDECREF(new_mvs.memview); - new_mvs.memview = NULL; - new_mvs.data = NULL; -no_fail: - __Pyx_XDECREF(shape_tuple); - __Pyx_XDECREF(temp_int); - __Pyx_XDECREF(array_obj); - __Pyx_RefNannyFinishContext(); - return new_mvs; + return ndarray_object; } - -static CYTHON_INLINE PyObject * -__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) -{ - PyObject *cobj; -#if PY_VERSION_HEX >= 0x02070000 - cobj = PyCapsule_New(p, sig, NULL); -#else - cobj = PyCObject_FromVoidPtr(p, NULL); -#endif - return cobj; +static CYTHON_INLINE PyObject* __Pyx_ImportNumPyArrayTypeIfAvailable(void) { + if (unlikely(!__pyx_numpy_ndarray)) { + __pyx_numpy_ndarray = __Pyx__ImportNumPyArray(); + } + Py_INCREF(__pyx_numpy_ndarray); + return __pyx_numpy_ndarray; } -static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { - const long neg_one = (long) -1, const_zero = 0; +/* CIntFromPy */ + static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { + const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { @@ -21507,36 +25521,129 @@ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 - #if CYTHON_USE_PYLONG_INTERNALS +#if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { - case 0: return 0; - case 1: __PYX_VERIFY_RETURN_INT(long, digit, ((PyLongObject*)x)->ob_digit[0]); + case 0: return (long) 0; + case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) + case 2: + if (8 * sizeof(long) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { + return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 3: + if (8 * sizeof(long) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { + return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; + case 4: + if (8 * sizeof(long) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { + return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); + } + } + break; } - #endif #endif +#if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (long) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif if (sizeof(long) <= sizeof(unsigned long)) { - __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong(x)) - } else if (sizeof(long) <= sizeof(unsigned long long)) { - __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong(x)) + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif } } else { -#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 - #if CYTHON_USE_PYLONG_INTERNALS +#if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { - case 0: return 0; - case 1: __PYX_VERIFY_RETURN_INT(long, digit, +(((PyLongObject*)x)->ob_digit[0])); - case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); + case 0: return (long) 0; + case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) + case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) + case -2: + if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 2: + if (8 * sizeof(long) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -3: + if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 3: + if (8 * sizeof(long) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case -4: + if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; + case 4: + if (8 * sizeof(long) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { + return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); + } + } + break; } - #endif #endif if (sizeof(long) <= sizeof(long)) { - __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong(x)) - } else if (sizeof(long) <= sizeof(long long)) { - __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong(x)) + __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif } } { @@ -21545,7 +25652,7 @@ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; - PyObject *v = __Pyx_PyNumber_Int(x); + PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; @@ -21568,7 +25675,7 @@ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { } } else { long val; - PyObject *tmp = __Pyx_PyNumber_Int(x); + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); @@ -21584,7 +25691,269 @@ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { return (long) -1; } -static int __Pyx_check_binary_version(void) { +/* CIntFromPy */ + static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { + const char neg_one = (char) -1, const_zero = (char) 0; + const int is_unsigned = neg_one > const_zero; +#if PY_MAJOR_VERSION < 3 + if (likely(PyInt_Check(x))) { + if (sizeof(char) < sizeof(long)) { + __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG(x)) + } else { + long val = PyInt_AS_LONG(x); + if (is_unsigned && unlikely(val < 0)) { + goto raise_neg_overflow; + } + return (char) val; + } + } else +#endif + if (likely(PyLong_Check(x))) { + if (is_unsigned) { +#if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)x)->ob_digit; + switch (Py_SIZE(x)) { + case 0: return (char) 0; + case 1: __PYX_VERIFY_RETURN_INT(char, digit, digits[0]) + case 2: + if (8 * sizeof(char) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) >= 2 * PyLong_SHIFT) { + return (char) (((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); + } + } + break; + case 3: + if (8 * sizeof(char) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) >= 3 * PyLong_SHIFT) { + return (char) (((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); + } + } + break; + case 4: + if (8 * sizeof(char) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) >= 4 * PyLong_SHIFT) { + return (char) (((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0])); + } + } + break; + } +#endif +#if CYTHON_COMPILING_IN_CPYTHON + if (unlikely(Py_SIZE(x) < 0)) { + goto raise_neg_overflow; + } +#else + { + int result = PyObject_RichCompareBool(x, Py_False, Py_LT); + if (unlikely(result < 0)) + return (char) -1; + if (unlikely(result == 1)) + goto raise_neg_overflow; + } +#endif + if (sizeof(char) <= sizeof(unsigned long)) { + __PYX_VERIFY_RETURN_INT_EXC(char, unsigned long, PyLong_AsUnsignedLong(x)) +#ifdef HAVE_LONG_LONG + } else if (sizeof(char) <= sizeof(unsigned PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(char, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) +#endif + } + } else { +#if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)x)->ob_digit; + switch (Py_SIZE(x)) { + case 0: return (char) 0; + case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, (sdigit) (-(sdigit)digits[0])) + case 1: __PYX_VERIFY_RETURN_INT(char, digit, +digits[0]) + case -2: + if (8 * sizeof(char) - 1 > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { + return (char) (((char)-1)*(((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case 2: + if (8 * sizeof(char) > 1 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { + return (char) ((((((char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case -3: + if (8 * sizeof(char) - 1 > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { + return (char) (((char)-1)*(((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case 3: + if (8 * sizeof(char) > 2 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { + return (char) ((((((((char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case -4: + if (8 * sizeof(char) - 1 > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { + return (char) (((char)-1)*(((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + case 4: + if (8 * sizeof(char) > 3 * PyLong_SHIFT) { + if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { + __PYX_VERIFY_RETURN_INT(char, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) + } else if (8 * sizeof(char) - 1 > 4 * PyLong_SHIFT) { + return (char) ((((((((((char)digits[3]) << PyLong_SHIFT) | (char)digits[2]) << PyLong_SHIFT) | (char)digits[1]) << PyLong_SHIFT) | (char)digits[0]))); + } + } + break; + } +#endif + if (sizeof(char) <= sizeof(long)) { + __PYX_VERIFY_RETURN_INT_EXC(char, long, PyLong_AsLong(x)) +#ifdef HAVE_LONG_LONG + } else if (sizeof(char) <= sizeof(PY_LONG_LONG)) { + __PYX_VERIFY_RETURN_INT_EXC(char, PY_LONG_LONG, PyLong_AsLongLong(x)) +#endif + } + } + { +#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) + PyErr_SetString(PyExc_RuntimeError, + "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); +#else + char val; + PyObject *v = __Pyx_PyNumber_IntOrLong(x); + #if PY_MAJOR_VERSION < 3 + if (likely(v) && !PyLong_Check(v)) { + PyObject *tmp = v; + v = PyNumber_Long(tmp); + Py_DECREF(tmp); + } + #endif + if (likely(v)) { + int one = 1; int is_little = (int)*(unsigned char *)&one; + unsigned char *bytes = (unsigned char *)&val; + int ret = _PyLong_AsByteArray((PyLongObject *)v, + bytes, sizeof(val), + is_little, !is_unsigned); + Py_DECREF(v); + if (likely(!ret)) + return val; + } +#endif + return (char) -1; + } + } else { + char val; + PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); + if (!tmp) return (char) -1; + val = __Pyx_PyInt_As_char(tmp); + Py_DECREF(tmp); + return val; + } +raise_overflow: + PyErr_SetString(PyExc_OverflowError, + "value too large to convert to char"); + return (char) -1; +raise_neg_overflow: + PyErr_SetString(PyExc_OverflowError, + "can't convert negative value to char"); + return (char) -1; +} + +/* FastTypeChecks */ + #if CYTHON_COMPILING_IN_CPYTHON +static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { + while (a) { + a = a->tp_base; + if (a == b) + return 1; + } + return b == &PyBaseObject_Type; +} +static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { + PyObject *mro; + if (a == b) return 1; + mro = a->tp_mro; + if (likely(mro)) { + Py_ssize_t i, n; + n = PyTuple_GET_SIZE(mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) + return 1; + } + return 0; + } + return __Pyx_InBases(a, b); +} +#if PY_MAJOR_VERSION == 2 +static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { + PyObject *exception, *value, *tb; + int res; + __Pyx_PyThreadState_declare + __Pyx_PyThreadState_assign + __Pyx_ErrFetch(&exception, &value, &tb); + res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; + if (unlikely(res == -1)) { + PyErr_WriteUnraisable(err); + res = 0; + } + if (!res) { + res = PyObject_IsSubclass(err, exc_type2); + if (unlikely(res == -1)) { + PyErr_WriteUnraisable(err); + res = 0; + } + } + __Pyx_ErrRestore(exception, value, tb); + return res; +} +#else +static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { + int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; + if (!res) { + res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); + } + return res; +} +#endif +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject* exc_type) { + if (likely(err == exc_type)) return 1; + if (likely(PyExceptionClass_Check(err))) { + return __Pyx_inner_PyErr_GivenExceptionMatches2(err, NULL, exc_type); + } + return PyErr_GivenExceptionMatches(err, exc_type); +} +static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *exc_type1, PyObject *exc_type2) { + if (likely(err == exc_type1 || err == exc_type2)) return 1; + if (likely(PyExceptionClass_Check(err))) { + return __Pyx_inner_PyErr_GivenExceptionMatches2(err, exc_type1, exc_type2); + } + return (PyErr_GivenExceptionMatches(err, exc_type1) || PyErr_GivenExceptionMatches(err, exc_type2)); +} +#endif + +/* CheckBinaryVersion */ + static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); @@ -21599,7 +25968,8 @@ static int __Pyx_check_binary_version(void) { return 0; } -static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { +/* InitStrings */ + static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { @@ -21624,6 +25994,8 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { #endif if (!*t->p) return -1; + if (PyObject_Hash(*t->p) == -1) + PyErr_Clear(); ++t; } return 0; @@ -21632,53 +26004,60 @@ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); } -static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { +static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } -static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT - if ( -#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - __Pyx_sys_getdefaultencoding_not_ascii && -#endif - PyUnicode_Check(o)) { -#if PY_VERSION_HEX < 0x03030000 - char* defenc_c; - PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); - if (!defenc) return NULL; - defenc_c = PyBytes_AS_STRING(defenc); +#if !CYTHON_PEP393_ENABLED +static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + char* defenc_c; + PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); + if (!defenc) return NULL; + defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - { - char* end = defenc_c + PyBytes_GET_SIZE(defenc); - char* c; - for (c = defenc_c; c < end; c++) { - if ((unsigned char) (*c) >= 128) { - PyUnicode_AsASCIIString(o); - return NULL; - } + { + char* end = defenc_c + PyBytes_GET_SIZE(defenc); + char* c; + for (c = defenc_c; c < end; c++) { + if ((unsigned char) (*c) >= 128) { + PyUnicode_AsASCIIString(o); + return NULL; } } + } #endif - *length = PyBytes_GET_SIZE(defenc); - return defenc_c; + *length = PyBytes_GET_SIZE(defenc); + return defenc_c; +} #else - if (__Pyx_PyUnicode_READY(o) == -1) return NULL; +static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { + if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII - if (PyUnicode_IS_ASCII(o)) { - *length = PyUnicode_GET_LENGTH(o); - return PyUnicode_AsUTF8(o); - } else { - PyUnicode_AsASCIIString(o); - return NULL; - } + if (likely(PyUnicode_IS_ASCII(o))) { + *length = PyUnicode_GET_LENGTH(o); + return PyUnicode_AsUTF8(o); + } else { + PyUnicode_AsASCIIString(o); + return NULL; + } #else - return PyUnicode_AsUTF8AndSize(o, length); + return PyUnicode_AsUTF8AndSize(o, length); +#endif +} +#endif #endif +static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { +#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT + if ( +#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII + __Pyx_sys_getdefaultencoding_not_ascii && #endif + PyUnicode_Check(o)) { + return __Pyx_PyUnicode_AsStringAndSize(o, length); } else #endif -#if !CYTHON_COMPILING_IN_PYPY +#if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); @@ -21699,43 +26078,67 @@ static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } -static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { +static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { +#if PY_MAJOR_VERSION >= 3 + if (PyLong_Check(result)) { + if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, + "__int__ returned non-int (type %.200s). " + "The ability to return an instance of a strict subclass of int " + "is deprecated, and may be removed in a future version of Python.", + Py_TYPE(result)->tp_name)) { + Py_DECREF(result); + return NULL; + } + return result; + } +#endif + PyErr_Format(PyExc_TypeError, + "__%.4s__ returned non-%.4s (type %.200s)", + type_name, type_name, Py_TYPE(result)->tp_name); + Py_DECREF(result); + return NULL; +} +static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { +#if CYTHON_USE_TYPE_SLOTS PyNumberMethods *m; +#endif const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 - if (PyInt_Check(x) || PyLong_Check(x)) + if (likely(PyInt_Check(x) || PyLong_Check(x))) #else - if (PyLong_Check(x)) + if (likely(PyLong_Check(x))) #endif - return Py_INCREF(x), x; + return __Pyx_NewRef(x); +#if CYTHON_USE_TYPE_SLOTS m = Py_TYPE(x)->tp_as_number; -#if PY_MAJOR_VERSION < 3 + #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; - res = PyNumber_Int(x); + res = m->nb_int(x); } else if (m && m->nb_long) { name = "long"; - res = PyNumber_Long(x); + res = m->nb_long(x); } -#else - if (m && m->nb_int) { + #else + if (likely(m && m->nb_int)) { name = "int"; - res = PyNumber_Long(x); + res = m->nb_int(x); + } + #endif +#else + if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { + res = PyNumber_Int(x); } #endif - if (res) { + if (likely(res)) { #if PY_MAJOR_VERSION < 3 - if (!PyInt_Check(res) && !PyLong_Check(res)) { + if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { #else - if (!PyLong_Check(res)) { + if (unlikely(!PyLong_CheckExact(res))) { #endif - PyErr_Format(PyExc_TypeError, - "__%.4s__ returned non-%.4s (type %.200s)", - name, name, Py_TYPE(res)->tp_name); - Py_DECREF(res); - return NULL; + return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); } } else if (!PyErr_Occurred()) { @@ -21748,18 +26151,55 @@ static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 - if (likely(PyInt_CheckExact(b))) - return PyInt_AS_LONG(b); + if (likely(PyInt_CheckExact(b))) { + if (sizeof(Py_ssize_t) >= sizeof(long)) + return PyInt_AS_LONG(b); + else + return PyInt_AsSsize_t(x); + } #endif if (likely(PyLong_CheckExact(b))) { - #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 - #if CYTHON_USE_PYLONG_INTERNALS - switch (Py_SIZE(b)) { - case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; - case 0: return 0; - case 1: return ((PyLongObject*)b)->ob_digit[0]; - } - #endif + #if CYTHON_USE_PYLONG_INTERNALS + const digit* digits = ((PyLongObject*)b)->ob_digit; + const Py_ssize_t size = Py_SIZE(b); + if (likely(__Pyx_sst_abs(size) <= 1)) { + ival = likely(size) ? digits[0] : 0; + if (size == -1) ival = -ival; + return ival; + } else { + switch (size) { + case 2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -2: + if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -3: + if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case 4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + case -4: + if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { + return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); + } + break; + } + } #endif return PyLong_AsSsize_t(b); } From 7211fde3ff0e8b9eeb2120c563bc63ccb223e6a9 Mon Sep 17 00:00:00 2001 From: lison Date: Tue, 21 Sep 2021 22:27:26 -0400 Subject: [PATCH 154/155] added pyqpbo as requirement --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 0d1d7b4d..9edb5183 100644 --- a/setup.py +++ b/setup.py @@ -11,7 +11,7 @@ setup(name="pystruct", version="0.3.2", - install_requires=["ad3", "numpy", "cvxopt", "future", "Cython", "scikit-learn"], + install_requires=["ad3", "numpy", "cvxopt", "future", "Cython", "scikit-learn", "pyqpbo"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', 'pystruct.tests', 'pystruct.tests.test_learners', From cc1600612b8b1357c0a7025fa82bfbf427046899 Mon Sep 17 00:00:00 2001 From: lison Date: Wed, 22 Sep 2021 21:19:55 -0400 Subject: [PATCH 155/155] removed pyqpbo as requirement due to problems in other OS --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 9edb5183..0d1d7b4d 100644 --- a/setup.py +++ b/setup.py @@ -11,7 +11,7 @@ setup(name="pystruct", version="0.3.2", - install_requires=["ad3", "numpy", "cvxopt", "future", "Cython", "scikit-learn", "pyqpbo"], + install_requires=["ad3", "numpy", "cvxopt", "future", "Cython", "scikit-learn"], packages=['pystruct', 'pystruct.learners', 'pystruct.inference', 'pystruct.models', 'pystruct.utils', 'pystruct.datasets', 'pystruct.tests', 'pystruct.tests.test_learners',