lefts 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
lefts/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ from .interface import Model, leaf, lift, split, ensemble, tune, feed
2
+
3
+ __all__ = [
4
+ "Model",
5
+ "leaf",
6
+ "lift",
7
+ "split",
8
+ "ensemble",
9
+ "tune",
10
+ "feed",
11
+ ]
lefts/helpers.py ADDED
@@ -0,0 +1,42 @@
1
+ import copy
2
+ import polars as pl
3
+ from typing import Any, Callable
4
+
5
+
6
+ def tabular_model(
7
+ estimator,
8
+ features: list[str],
9
+ target: str,
10
+ ) -> Callable[..., Any]:
11
+ """
12
+ Wraps a sklearn-compatible estimator into a Lefts model factory.
13
+
14
+ The returned factory can be passed directly to `leaf(model_constructor=...)`.
15
+
16
+ Parameters
17
+ ----------
18
+ estimator:
19
+ Any sklearn-compatible estimator (must implement .fit(X, y) and .predict(X)).
20
+ features:
21
+ Column names to use as model inputs.
22
+ target:
23
+ Column name of the target variable.
24
+ """
25
+
26
+ def factory(**hyperparameters):
27
+ est = copy.deepcopy(estimator)
28
+ if hyperparameters:
29
+ est.set_params(**hyperparameters)
30
+
31
+ class _Model:
32
+ def fit(self, training_set: pl.DataFrame):
33
+ X = training_set.select(features).to_numpy()
34
+ y = training_set[target].to_numpy()
35
+ est.fit(X, y)
36
+
37
+ def predict(self, df: pl.DataFrame):
38
+ return est.predict(df.select(features).to_numpy())
39
+
40
+ return _Model()
41
+
42
+ return factory
lefts/interface.py ADDED
@@ -0,0 +1,204 @@
1
+ from dataclasses import dataclass
2
+ from typing import Any, Callable, Iterable
3
+
4
+ from polars import DataFrame, Expr
5
+
6
+ from .interpreter.fit import _fit
7
+ from .interpreter.predict import _Model
8
+ from .interpreter.masks import _collect_masks
9
+ from .interpreter.labels import _print_tree, _collect_labels
10
+ from .nodes import Ensemble, Feed, Leaf, Tune, Lift, Split
11
+ from .validation import _validate
12
+
13
+
14
+ @dataclass
15
+ class Model(_Model):
16
+ def __post_init__(self):
17
+ _validate(self.root)
18
+
19
+ def fit(self, df: DataFrame):
20
+ models, hyperparameters = _fit(self.root, df)
21
+ self.models = models
22
+ self.hyperparameters = hyperparameters
23
+
24
+ def print_tree(self, print_all_labels: bool = False):
25
+ print(_print_tree(self.root, print_all_labels=print_all_labels))
26
+
27
+ def collect_labels(self) -> Iterable[str]:
28
+ return _collect_labels(self.root)
29
+
30
+ def mark_train_validation_test_rows(self, df: DataFrame) -> DataFrame:
31
+ """
32
+ Annotate `df` with boolean columns describing whether each
33
+ row belongs to the train, test and (if applicable) validation
34
+ sets for each sub model.
35
+ """
36
+ new_cols = []
37
+ for label, masks in _collect_masks(self.root).items():
38
+ new_cols.append(masks["train"].alias(f"{label}__train"))
39
+ new_cols.append(masks["test"].alias(f"{label}__test"))
40
+ if masks["validation"] is not None:
41
+ new_cols.append(masks["validation"].alias(f"{label}__validation"))
42
+ return df.with_columns(new_cols)
43
+
44
+
45
+ def leaf(model_constructor: Callable[..., Any], label: str) -> Model:
46
+ """
47
+ Converts a model into the format required for transformation by lefts.
48
+
49
+ Parameters
50
+ ----------
51
+ model_constructor
52
+ A constructor that creates a model with ``.fit()`` and ``.predict()`` methods.
53
+ label
54
+ A label for keeping track of this model.
55
+ """
56
+
57
+ leaf_node = Leaf(label=label, factory=model_constructor)
58
+ return Model(leaf_node)
59
+
60
+
61
+ def lift(
62
+ model: Model,
63
+ values,
64
+ name,
65
+ train_filter,
66
+ test_filter,
67
+ validation_filter=None,
68
+ aggregate_with=None,
69
+ ) -> Model:
70
+ """
71
+ Creates multiple copies of a model that are trained on (possibly overlapping) train, test and validation sets.
72
+
73
+ Parameters
74
+ ----------
75
+ model
76
+ A lefts Model object.
77
+ values
78
+ Values to lift the model over. One copy of the model will be trained for each value.
79
+ name
80
+ The name of the lift transformation. Has no effect on model training, but controls how the resulting
81
+ models are labelled and addressed: each leaf beneath the lift gets a label of the form
82
+ ``"<leaf label>[<name>=<value>]"``. When ``aggregate_with`` is set, the per-value columns are instead
83
+ collapsed into a single output column named ``name``.
84
+ train_filter
85
+ A function mapping each value in ``values`` to a boolean Polars expression indicating whether a given
86
+ row is in the train set associated with that value.
87
+ test_filter
88
+ A function mapping each value in ``values`` to a boolean Polars expression indicating whether a given
89
+ row is in the test set associated with that value.
90
+ validation_filter
91
+ A function mapping each value in ``values`` to a boolean Polars expression indicating whether a given
92
+ row is in the validation set associated with that value.
93
+ aggregate_with
94
+ A function that postprocesses the output columns of the lift. It is called on the set of columns
95
+ output by the lifted ``.predict()``.
96
+ """
97
+ lifted = Lift(
98
+ child=model.root,
99
+ values=values,
100
+ name=name,
101
+ train_filter=train_filter,
102
+ test_filter=test_filter,
103
+ validation_filter=validation_filter,
104
+ aggregate_with=aggregate_with,
105
+ )
106
+
107
+ return Model(lifted)
108
+
109
+
110
+ def split(
111
+ name: str,
112
+ model: Model,
113
+ train_filter: Expr,
114
+ test_filter: Expr,
115
+ validation_filter: Expr | None = None,
116
+ ) -> Model:
117
+ """
118
+ Restricts a model to train, test and (optionally) validate on defined subsets of the available data.
119
+
120
+ Parameters
121
+ ----------
122
+ name
123
+ A name used to keep track of this lefts operation in the workflow. Has no effect on model training.
124
+ model
125
+ A lefts Model object.
126
+ train_filter
127
+ A boolean Polars expression that indicates whether a given row is in the train set.
128
+ test_filter
129
+ A boolean Polars expression that indicates whether a given row is in the test set.
130
+ validation_filter
131
+ A boolean Polars expression that indicates whether a given row is in the validation set.
132
+ """
133
+ node = Split(
134
+ name=name,
135
+ child=model.root,
136
+ train_filter=train_filter,
137
+ test_filter=test_filter,
138
+ validation_filter=validation_filter,
139
+ )
140
+
141
+ return Model(node)
142
+
143
+
144
+ def ensemble(name: str, *models, aggregate_with=None):
145
+ """
146
+ Binds multiple models into a unified model that fits and predicts all of them in parallel.
147
+
148
+ Parameters
149
+ ----------
150
+ name
151
+ A name used to keep track of this lefts operation in the workflow. Has no effect on model training.
152
+ models
153
+ lefts Model objects.
154
+ aggregate_with
155
+ A function that postprocesses the output columns of the ensemble ``.predict()`` method.
156
+ """
157
+ roots = [model.root for model in models]
158
+ node = Ensemble(name, roots, aggregate_with=aggregate_with)
159
+
160
+ return Model(node)
161
+
162
+
163
+ def tune(
164
+ name: str, consumer: Model, source: Model, logic: Callable[[Model, DataFrame], dict]
165
+ ):
166
+ """
167
+ Learn hyperparameters by fitting the source model, applying customisable logic, then passing the resulting
168
+ dictionary of hyperparameters to the consumer.
169
+
170
+ Parameters
171
+ ----------
172
+ name
173
+ A name used to keep track of this lefts operation in the workflow. Has no effect on model training.
174
+ consumer
175
+ A lefts Model object. Its leaf factories are instantiated using the outputs of ``logic`` as keyword
176
+ arguments.
177
+ source
178
+ A lefts Model object. It is fitted first; the fitted model is then handed to ``logic`` to derive the
179
+ hyperparameters.
180
+ logic
181
+ A callable ``(fitted_source_model, df) -> dict`` that reads the fitted source and returns the
182
+ hyperparameters to apply when fitting the consumer.
183
+ """
184
+ node = Tune(name=name, consumer=consumer.root, source=source.root, logic=logic)
185
+
186
+ return Model(node)
187
+
188
+
189
+ def feed(name: str, source: Model, consumer: Model) -> Model:
190
+ """
191
+ Chains two models: the source's predictions are available to the consumer as a feature or target during .fit and .predict.
192
+ Parameters
193
+ ----------
194
+ name: A name used to keep track of this lefts operation in the workflow. Has no effect on model training.
195
+ source: A lefts Model object, which provides the output of its predict to the consumer.
196
+ consumer: A lefts Model object, which has access to the prediction output of the consumer.
197
+
198
+ Returns
199
+ -------
200
+
201
+ """
202
+ node = Feed(name=name, source=source.root, consumer=consumer.root)
203
+
204
+ return Model(node)
File without changes
@@ -0,0 +1,222 @@
1
+ import warnings
2
+
3
+ from ..nodes import LeftsNode, Leaf, Lift, Split, Ensemble, Tune, Feed
4
+ from .labels import _make_label
5
+ from .masks import _collect_masks
6
+ from .predict import _Model, _predict
7
+ from typing import Tuple, Any
8
+ from polars import DataFrame, Expr, lit
9
+ from inspect import signature
10
+
11
+
12
+ def _fit(
13
+ node: LeftsNode,
14
+ df: DataFrame,
15
+ hyperparameters: dict = None,
16
+ label_context: dict = None,
17
+ is_root=True,
18
+ precomputed_masks: dict = None,
19
+ ) -> Tuple[dict[str, Any], dict[str, Any]]:
20
+
21
+ label_context = label_context or dict()
22
+ hyperparameters = hyperparameters or dict()
23
+
24
+ # Define output types
25
+ fitted_models: dict[str, Any] = {}
26
+ output_hyperparameters: dict[str, Any] = {}
27
+
28
+ if is_root:
29
+ precomputed_masks = _collect_masks(node)
30
+
31
+ match node:
32
+ case Leaf(label=label, factory=factory):
33
+ # Note: it is safe to use the passed hyperparameters
34
+ # Without further filtering on label, because the hyperparameters
35
+ # Are passed from a Tune to every node beneath them in the tree.
36
+ model = factory(**hyperparameters)
37
+ model_label = _make_label(label, label_context)
38
+
39
+ train_mask = precomputed_masks[model_label]["train"]
40
+ validation_mask = precomputed_masks[model_label]["validation"]
41
+
42
+ train_df = df.filter(train_mask)
43
+
44
+ fit_signature = signature(model.fit)
45
+
46
+ # Now we inspect the signature of fit to determine whether
47
+ # It expects a validation set, and also to perform runtime checking
48
+ # That it's signature conforms to expectations.
49
+
50
+ allowable_fit_parameters = {"training_set", "validation_set"}
51
+ excess_parameters = set(fit_signature.parameters) - allowable_fit_parameters
52
+ assert excess_parameters == set(), (
53
+ f"Model {label} .fit(...) should only have arguments {allowable_fit_parameters} "
54
+ f" but has unexpected parameters {excess_parameters}"
55
+ )
56
+
57
+ # Now, if required, we compute the validation set and pass it through to the
58
+ # fit function as a kwarg.
59
+ fit_kwargs = dict()
60
+ if (
61
+ "validation_set" in fit_signature.parameters
62
+ and validation_mask is not None
63
+ ):
64
+ fit_kwargs["validation_set"] = df.filter(validation_mask)
65
+
66
+ elif ("validation_set" not in fit_signature.parameters) and (
67
+ validation_mask is not None
68
+ ):
69
+ raise ValueError(
70
+ f"Validation set created but model {label} .fit has no validation_set argument"
71
+ )
72
+
73
+ model.fit(train_df, **fit_kwargs)
74
+
75
+ fitted_models[model_label] = model
76
+
77
+ case Lift(child=child, values=values, name=name):
78
+ # Under a lift, we will take the cartesian product
79
+ # Of the existing labels with the lift values
80
+ # Filtering appropriately based on each value.
81
+ for value in values:
82
+ extended_label_context = {**label_context, name: value}
83
+
84
+ child_models, child_hyperparameters = _fit(
85
+ child,
86
+ df,
87
+ hyperparameters,
88
+ extended_label_context,
89
+ False,
90
+ precomputed_masks,
91
+ )
92
+
93
+ fitted_models |= child_models
94
+ output_hyperparameters |= child_hyperparameters
95
+
96
+ case Split(child=child):
97
+ child_models, child_hyperparameters = _fit(
98
+ child,
99
+ df,
100
+ hyperparameters,
101
+ label_context,
102
+ False,
103
+ precomputed_masks,
104
+ )
105
+ fitted_models |= child_models
106
+ output_hyperparameters |= child_hyperparameters
107
+
108
+ case Ensemble():
109
+ for child in node.children:
110
+ child_fitted_models, child_learned_hyperparameters = _fit(
111
+ child, df, hyperparameters, label_context, False, precomputed_masks
112
+ )
113
+ fitted_models |= child_fitted_models
114
+ output_hyperparameters |= child_learned_hyperparameters
115
+
116
+ case Tune(consumer=consumer, source=source, logic=logic):
117
+ source_models, learned_hyperparameters = _fit(
118
+ source,
119
+ df,
120
+ )
121
+
122
+ tune_model = _Model(source, source_models, learned_hyperparameters)
123
+ learned_hyperparameters |= logic(tune_model, df)
124
+
125
+ consumer_models, consumer_hyperparameters = _fit(
126
+ consumer,
127
+ df,
128
+ learned_hyperparameters,
129
+ label_context,
130
+ False,
131
+ precomputed_masks,
132
+ )
133
+
134
+ fitted_models |= source_models | consumer_models
135
+ output_hyperparameters |= consumer_hyperparameters | learned_hyperparameters
136
+
137
+ case Feed(source=source, consumer=consumer):
138
+ _check_feed_row_compatibility(
139
+ source, consumer, df, precomputed_masks, label_context
140
+ )
141
+ source_models, source_hyperparameters = _fit(
142
+ source,
143
+ df,
144
+ hyperparameters,
145
+ label_context,
146
+ False,
147
+ precomputed_masks,
148
+ )
149
+
150
+ augmented_df = _predict(
151
+ source,
152
+ source_models,
153
+ df,
154
+ precomputed_masks,
155
+ label_context,
156
+ )
157
+ consumer_models, consumer_hyperparameters = _fit(
158
+ consumer,
159
+ augmented_df,
160
+ hyperparameters,
161
+ label_context,
162
+ False,
163
+ precomputed_masks,
164
+ )
165
+ fitted_models |= source_models | consumer_models
166
+ output_hyperparameters |= source_hyperparameters | consumer_hyperparameters
167
+
168
+ case _:
169
+ raise ValueError(f"Unknown node type {type(node)}")
170
+
171
+ return fitted_models, output_hyperparameters
172
+
173
+
174
+ def _check_feed_row_compatibility(
175
+ source_root: LeftsNode,
176
+ consumer_root: LeftsNode,
177
+ df: DataFrame,
178
+ precomputed_masks: dict,
179
+ label_context: dict,
180
+ ) -> None:
181
+ """
182
+ Emits warnings if there is suspicious behaviour in the train/test
183
+ overlap of the source and consumer of a Feed node.
184
+
185
+ Specifically it will warn if:
186
+ - The test set of the source is not a subset of the consumer. This may indicate a data leak.
187
+ - The test set of the source is a strict subset of the consumer, since this will cause NaNs in the fed column.
188
+ """
189
+
190
+ # It's possible to have multiple leaves with separate train/test
191
+ # Specification as one source (i.e. an ensemble with an aggregate)
192
+ # Hence, we take the union of all child masks.
193
+ def union_mask(node: LeftsNode, mask_kind: str) -> Expr:
194
+ result = lit(False)
195
+ for label in _collect_masks(node, label_context):
196
+ result = result | precomputed_masks[label][mask_kind]
197
+ return result
198
+
199
+ source_train = union_mask(source_root, "train")
200
+ source_test = union_mask(source_root, "test")
201
+ consumer_train = union_mask(consumer_root, "train")
202
+
203
+ leak_rows = df.filter(source_train & ~consumer_train).height
204
+ if leak_rows > 0:
205
+ warnings.warn(
206
+ f"Feed: source's train set contains {leak_rows} rows not in consumer's "
207
+ "train set. This may signal a data leak - validate with Model.mark_train_validation_test_rows"
208
+ "if you are unsure",
209
+ UserWarning,
210
+ stacklevel=4,
211
+ )
212
+
213
+ nan_rows = df.filter(consumer_train & ~source_test).height
214
+ if nan_rows > 0:
215
+ warnings.warn(
216
+ f"Feed: {nan_rows} rows in consumer's train set are not in source's "
217
+ "test set. Source's augmentation column will be NaN on those rows "
218
+ "during consumer fit. If this is unexpected, validate your train and test filter"
219
+ "behaviour with Model.mark_train_validation_test_rows",
220
+ UserWarning,
221
+ stacklevel=4,
222
+ )
@@ -0,0 +1,117 @@
1
+ from typing import Iterator
2
+
3
+ from ..nodes import LeftsNode, Leaf, Lift, Split, Ensemble, Feed, Tune
4
+
5
+
6
+ def _make_label(leaf_name: str, label_context: dict) -> str:
7
+ if not label_context:
8
+ return leaf_name
9
+ dims = ", ".join(f"{k}={v}" for k, v in label_context.items())
10
+ return f"{leaf_name}[{dims}]"
11
+
12
+
13
+ # Lists longer than this are abbreviated to [first, ..., last] unless the
14
+ # caller asks for the full listing.
15
+ _MAX_LIST = 6
16
+
17
+
18
+ def _format_list(items, print_all_labels: bool) -> str:
19
+ items = list(items)
20
+ if print_all_labels or len(items) <= _MAX_LIST:
21
+ body = ", ".join(str(i) for i in items)
22
+ else:
23
+ body = f"{items[0]}, ..., {items[-1]}"
24
+ return f"[{body}]"
25
+
26
+
27
+ def _aggregation_suffix(node: LeftsNode) -> str:
28
+ fn = getattr(node, "aggregate_with", None)
29
+ if fn is None:
30
+ return ""
31
+ fn_name = getattr(fn, "__name__", None) or repr(fn)
32
+ return f' ⇒ {fn_name} → "{node.name}"'
33
+
34
+
35
+ def _count_models(node: LeftsNode) -> int:
36
+ """How many leaf models this subtree fits."""
37
+ match node:
38
+ case Leaf():
39
+ return 1
40
+ case Lift(child=child, values=values):
41
+ return len(values) * _count_models(child)
42
+ case _:
43
+ return sum(_count_models(child) for child in node.children)
44
+
45
+
46
+ def _node_header(node: LeftsNode, print_all_labels: bool) -> str:
47
+ count = _count_models(node)
48
+ models = f" ({count} model{'' if count == 1 else 's'})"
49
+ match node:
50
+ case Leaf(label=label):
51
+ return f"Leaf '{label}'{models}"
52
+ case Lift(name=name, values=values):
53
+ vals = _format_list(values, print_all_labels)
54
+ return f"Lift '{name}'{models}: {vals}{_aggregation_suffix(node)}"
55
+ case Split(name=name):
56
+ return f"Split '{name}'{models}"
57
+ case Ensemble(name=name):
58
+ return f"Ensemble '{name}'{models}{_aggregation_suffix(node)}"
59
+ case Tune(name=name):
60
+ return f"Tune '{name}'{models}"
61
+ case Feed(name=name):
62
+ return f"Feed '{name}'{models}"
63
+ case _:
64
+ return getattr(node, "name", repr(node))
65
+
66
+
67
+ def _print_tree(
68
+ node: LeftsNode,
69
+ print_all_labels: bool = False,
70
+ prefix: str = "",
71
+ is_root: bool = True,
72
+ is_last: bool = True,
73
+ ) -> str:
74
+ header = _node_header(node, print_all_labels)
75
+
76
+ if is_root:
77
+ outputs = _format_list(_collect_labels(node), print_all_labels)
78
+ lines = [f"{header} → outputs: {outputs}"]
79
+ child_prefix = " "
80
+ else:
81
+ connector = "└── " if is_last else "├── "
82
+ lines = [f"{prefix}{connector}{header}"]
83
+ child_prefix = prefix + (" " if is_last else "│ ")
84
+
85
+ children = list(node.children)
86
+ for i, child in enumerate(children):
87
+ lines.append(
88
+ _print_tree(
89
+ child,
90
+ print_all_labels,
91
+ prefix=child_prefix,
92
+ is_root=False,
93
+ is_last=(i == len(children) - 1),
94
+ )
95
+ )
96
+
97
+ return "\n".join(lines)
98
+
99
+
100
+ def _collect_labels(
101
+ node: LeftsNode, label_context: dict | None = None
102
+ ) -> Iterator[str]:
103
+ label_context = label_context or {}
104
+
105
+ match node:
106
+ case Lift(aggregate_with=fn) | Ensemble(aggregate_with=fn) if fn is not None:
107
+ # In the case where we have an aggregation function, we
108
+ # halt because all child labels will be pulled into the aggregated column
109
+ yield _make_label(node.name, label_context)
110
+ case Leaf(label=label):
111
+ yield _make_label(label, label_context)
112
+ case Lift(child=child, name=name, values=values):
113
+ for value in values:
114
+ yield from _collect_labels(child, label_context | {name: value})
115
+ case LeftsNode():
116
+ for child in node.children:
117
+ yield from _collect_labels(child, label_context)
@@ -0,0 +1,96 @@
1
+ from polars import Expr, lit
2
+
3
+ from ..nodes import LeftsNode, Leaf, Lift, Split
4
+ from .labels import _make_label
5
+
6
+
7
+ def _collect_masks(
8
+ node: LeftsNode,
9
+ label_context: dict | None = None,
10
+ train_mask: Expr | None = None,
11
+ validation_mask: Expr | None = None,
12
+ test_mask: Expr | None = None,
13
+ ) -> dict[str, dict[str, Expr | None]]:
14
+ """
15
+ Returns a dictionary of label -> {train: train_mask, validation: validation_mask, test: test_mask}
16
+ """
17
+ label_context = label_context or dict()
18
+ train_mask = train_mask if train_mask is not None else lit(True)
19
+ test_mask = test_mask if test_mask is not None else lit(True)
20
+
21
+ result = {}
22
+
23
+ match node:
24
+ case Leaf(label=leaf_label):
25
+ full_label = _make_label(leaf_label, label_context)
26
+ result[full_label] = {
27
+ "train": train_mask,
28
+ "validation": validation_mask,
29
+ "test": test_mask,
30
+ }
31
+
32
+ case Lift(
33
+ child=child,
34
+ name=name,
35
+ values=values,
36
+ train_filter=train_filter,
37
+ validation_filter=validation_filter,
38
+ test_filter=test_filter,
39
+ ):
40
+ for value in values:
41
+ next_label_context = {**label_context, name: value}
42
+ next_train_mask = train_filter(value) & train_mask
43
+ next_test_mask = test_filter(value) & test_mask
44
+
45
+ if validation_filter is None:
46
+ next_validation_mask = validation_mask
47
+ else:
48
+ next_validation_mask = validation_filter(value)
49
+ if validation_mask is not None:
50
+ next_validation_mask = next_validation_mask & validation_mask
51
+
52
+ result.update(
53
+ _collect_masks(
54
+ child,
55
+ next_label_context,
56
+ next_train_mask,
57
+ next_validation_mask,
58
+ next_test_mask,
59
+ )
60
+ )
61
+
62
+ case Split(
63
+ child=child,
64
+ train_filter=train_filter,
65
+ validation_filter=validation_filter,
66
+ test_filter=test_filter,
67
+ ):
68
+ next_train_mask = train_filter & train_mask
69
+ next_test_mask = test_filter & test_mask
70
+
71
+ if validation_filter is None:
72
+ next_validation_mask = validation_mask
73
+ else:
74
+ next_validation_mask = validation_filter
75
+ if validation_mask is not None:
76
+ next_validation_mask = next_validation_mask & validation_mask
77
+
78
+ result.update(
79
+ _collect_masks(
80
+ child,
81
+ label_context,
82
+ next_train_mask,
83
+ next_validation_mask,
84
+ next_test_mask,
85
+ )
86
+ )
87
+
88
+ case LeftsNode():
89
+ for child in node.children:
90
+ result.update(
91
+ _collect_masks(
92
+ child, label_context, train_mask, validation_mask, test_mask
93
+ )
94
+ )
95
+
96
+ return result
@@ -0,0 +1,140 @@
1
+ from dataclasses import dataclass
2
+ from typing import Iterator, Optional
3
+
4
+ from polars import DataFrame, Series
5
+
6
+ from ..nodes import LeftsNode, Leaf, Lift, Split, Ensemble, Tune, Feed
7
+ from .labels import _make_label, _collect_labels
8
+ from .masks import _collect_masks
9
+
10
+
11
+ @dataclass
12
+ class _Model:
13
+ root: LeftsNode
14
+ models: Optional[dict] = None
15
+ hyperparameters: Optional[dict] = None
16
+
17
+ def predict(self, df: DataFrame):
18
+ return _predict(self.root, self.models, df)
19
+
20
+ def fit(self, df: DataFrame):
21
+ raise NotImplementedError()
22
+
23
+
24
+ def _get_aggregation_input_columns(
25
+ node: LeftsNode, label_context: dict
26
+ ) -> Iterator[str]:
27
+ match node:
28
+ case Lift(child=child, name=name, values=values):
29
+ for value in values:
30
+ yield from _collect_labels(child, label_context | {name: value})
31
+ case Ensemble():
32
+ for child in node.children:
33
+ yield from _collect_labels(child, label_context)
34
+
35
+
36
+ def _aggregate(node: LeftsNode, df: DataFrame, label_context: dict) -> DataFrame:
37
+ input_cols = list(_get_aggregation_input_columns(node, label_context))
38
+ full_col = _make_label(node.name, label_context)
39
+ df = df.with_columns(node.aggregate_with(*input_cols).alias(full_col))
40
+ return df.drop(*input_cols)
41
+
42
+
43
+ def _predict(
44
+ node: LeftsNode,
45
+ models: dict,
46
+ df: DataFrame,
47
+ precomputed_masks: dict | None = None,
48
+ label_context: dict | None = None,
49
+ is_root: bool = True,
50
+ ) -> DataFrame:
51
+
52
+ label_context = label_context or {}
53
+
54
+ if is_root:
55
+ if "__lefts_row_index" in df.columns:
56
+ raise ValueError(
57
+ "Trying to create column __lefts_row_index but it already exists"
58
+ )
59
+ df = df.with_row_index(name="__lefts_row_index")
60
+ if precomputed_masks is None:
61
+ precomputed_masks = _collect_masks(node)
62
+
63
+ match node:
64
+ case Leaf(label=label):
65
+ full_label = _make_label(label, label_context)
66
+ test_mask = precomputed_masks[full_label]["test"]
67
+ test_df = df.filter(test_mask)
68
+ predictions = models[full_label].predict(test_df)
69
+ predictions = Series(name=full_label, values=predictions)
70
+ test_df = test_df.with_columns(predictions)
71
+ df = df.join(
72
+ test_df.select("__lefts_row_index", full_label),
73
+ on="__lefts_row_index",
74
+ coalesce=True,
75
+ how="left",
76
+ )
77
+
78
+ case Lift(
79
+ child=child, name=name, values=values, aggregate_with=aggregation_function
80
+ ):
81
+ for value in values:
82
+ df = _predict(
83
+ child,
84
+ models,
85
+ df,
86
+ precomputed_masks,
87
+ label_context | {name: value},
88
+ is_root=False,
89
+ )
90
+ if aggregation_function is not None:
91
+ df = _aggregate(node, df, label_context)
92
+
93
+ case Split(child=child):
94
+ df = _predict(
95
+ child, models, df, precomputed_masks, label_context, is_root=False
96
+ )
97
+
98
+ case Ensemble(aggregate_with=aggregation_function):
99
+ for child in node.children:
100
+ df = _predict(
101
+ child,
102
+ models,
103
+ df,
104
+ precomputed_masks,
105
+ label_context,
106
+ is_root=False,
107
+ )
108
+ if aggregation_function is not None:
109
+ df = _aggregate(node, df, label_context)
110
+
111
+ case Feed(source=source, consumer=consumer):
112
+ df = _predict(
113
+ source, models, df, precomputed_masks, label_context, is_root=False
114
+ )
115
+ df = _predict(
116
+ consumer, models, df, precomputed_masks, label_context, is_root=False
117
+ )
118
+
119
+ case Tune(consumer=consumer, source=source):
120
+ df = _predict(
121
+ source,
122
+ models,
123
+ df,
124
+ precomputed_masks,
125
+ label_context,
126
+ is_root=False,
127
+ )
128
+ df = _predict(
129
+ consumer,
130
+ models,
131
+ df,
132
+ precomputed_masks,
133
+ label_context,
134
+ is_root=False,
135
+ )
136
+
137
+ if is_root:
138
+ df = df.drop("__lefts_row_index")
139
+
140
+ return df
lefts/nodes.py ADDED
@@ -0,0 +1,106 @@
1
+ from abc import ABC, abstractmethod
2
+ from dataclasses import dataclass
3
+ from typing import Callable, Iterable, Protocol, runtime_checkable
4
+
5
+ from polars import DataFrame, DataType, Expr
6
+
7
+
8
+ @runtime_checkable
9
+ class ModelProtocol(Protocol):
10
+ def fit(self, df): ...
11
+
12
+ def predict(self, df): ...
13
+
14
+
15
+ class LeftsNode(ABC):
16
+ name: str
17
+
18
+ @property
19
+ @abstractmethod
20
+ def children(self) -> Iterable["LeftsNode"]:
21
+ """Return iterable of child nodes."""
22
+ ...
23
+
24
+
25
+ @dataclass
26
+ class Leaf(LeftsNode):
27
+ label: str
28
+ factory: Callable[[], ModelProtocol]
29
+
30
+ @property
31
+ def children(self):
32
+ return []
33
+
34
+ @property
35
+ def name(self) -> str:
36
+ return f"Leaf: {self.label}"
37
+
38
+
39
+ @dataclass
40
+ class Lift(LeftsNode):
41
+ name: str
42
+ child: LeftsNode
43
+ values: Iterable[DataType]
44
+ train_filter: Callable[[DataType], Expr]
45
+ test_filter: Callable[[DataType], Expr]
46
+ validation_filter: Callable[[DataType], Expr] | None = None
47
+ aggregate_with: Callable[..., Expr] | None = None
48
+
49
+ def __post_init__(self):
50
+ if len(set(self.values)) != len(self.values):
51
+ raise ValueError("values must contain no duplicates")
52
+ self.values = list(self.values)
53
+
54
+ @property
55
+ def children(self) -> Iterable["LeftsNode"]:
56
+ return [self.child]
57
+
58
+
59
+ @dataclass
60
+ class Split(LeftsNode):
61
+ name: str
62
+ child: LeftsNode
63
+ train_filter: Expr
64
+ test_filter: Expr
65
+ validation_filter: Expr | None = None
66
+
67
+ @property
68
+ def children(self) -> Iterable["LeftsNode"]:
69
+ return [self.child]
70
+
71
+
72
+ @dataclass
73
+ class Ensemble(LeftsNode):
74
+ name: str
75
+ models: Iterable[LeftsNode]
76
+ aggregate_with: Callable[..., Expr] | None = None
77
+
78
+ @property
79
+ def children(self):
80
+ return self.models
81
+
82
+
83
+ @dataclass
84
+ class Tune(LeftsNode):
85
+ name: str
86
+
87
+ consumer: LeftsNode
88
+ source: LeftsNode
89
+ logic: Callable[
90
+ ["LeftsNode", DataFrame], dict
91
+ ] # TODO this should actually typehint Model instead of LeftsNode, but need to re-organise dirs first
92
+
93
+ @property
94
+ def children(self) -> Iterable["LeftsNode"]:
95
+ return [self.source, self.consumer]
96
+
97
+
98
+ @dataclass
99
+ class Feed(LeftsNode):
100
+ name: str
101
+ source: LeftsNode
102
+ consumer: LeftsNode
103
+
104
+ @property
105
+ def children(self) -> Iterable["LeftsNode"]:
106
+ return [self.source, self.consumer]
lefts/validation.py ADDED
@@ -0,0 +1,54 @@
1
+ from typing import Iterator
2
+
3
+ from .nodes import LeftsNode, Leaf, Lift, Feed
4
+
5
+
6
+ _RESERVED_COLUMN_NAMES = {"__lefts_row_index"}
7
+
8
+
9
+ def _validate(root: LeftsNode) -> None:
10
+ _check_unique_node_names(root)
11
+ _check_no_lift_above_feed(root, under_lift=False)
12
+ _check_no_reserved_leaf_labels(root)
13
+
14
+
15
+ def _check_unique_node_names(root: LeftsNode) -> None:
16
+ """Every node's identifying name must be globally unique within the tree."""
17
+ seen = set()
18
+ duplicates = set()
19
+ for name in _collect_node_names(root):
20
+ if name in seen:
21
+ duplicates.add(name)
22
+ seen.add(name)
23
+ if duplicates:
24
+ raise ValueError(
25
+ f"Duplicate node names: {sorted(duplicates)}. Every Leaf label and "
26
+ "every non-leaf node name must be globally unique within the tree."
27
+ )
28
+
29
+
30
+ def _collect_node_names(node: LeftsNode) -> Iterator[str]:
31
+ yield node.label if isinstance(node, Leaf) else node.name
32
+ for child in node.children:
33
+ yield from _collect_node_names(child)
34
+
35
+
36
+ def _check_no_lift_above_feed(node: LeftsNode, under_lift: bool) -> None:
37
+ """Reject Lift as an ancestor of Feed"""
38
+ if isinstance(node, Feed) and under_lift:
39
+ raise ValueError(
40
+ f"Feed {node.name!r} has a Lift as an ancestor. This is currently "
41
+ "unsupported. Re-express by Lifting first and feeding second"
42
+ )
43
+ next_under_lift = under_lift or isinstance(node, Lift)
44
+ for child in node.children:
45
+ _check_no_lift_above_feed(child, next_under_lift)
46
+
47
+
48
+ def _check_no_reserved_leaf_labels(node: LeftsNode) -> None:
49
+ if isinstance(node, Leaf) and node.label in _RESERVED_COLUMN_NAMES:
50
+ raise ValueError(
51
+ f"Leaf label {node.label!r} collides with a reserved column name."
52
+ )
53
+ for child in node.children:
54
+ _check_no_reserved_leaf_labels(child)
@@ -0,0 +1,135 @@
1
+ Metadata-Version: 2.4
2
+ Name: lefts
3
+ Version: 0.1.0
4
+ Summary: Composable transformations for model experimentation
5
+ Author-email: Niklas Mather <niksmather@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/nsmat/lefts
8
+ Project-URL: Repository, https://github.com/nsmat/lefts
9
+ Keywords: machine-learning,ensemble,cross-validation,polars,dsl
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: polars
22
+ Dynamic: license-file
23
+
24
+ # Lefts: composable machine-learning model transformations
25
+
26
+ Lefts is a very simple domain specific language for building complex machine learning workflows from simple ones. Starting with your favourite machine learning models, you can use Lefts operations to:
27
+ - Build complex ensembles.
28
+ - Build complex cross validation and hyper-parametrisation procedures.
29
+ - Allow a model to create features or targets for another model.
30
+ - And any creative combination of the above.
31
+
32
+ Without making subsequent model fitting or evaluation or experimentation any more complex than it was with the original model. This implementation is built on top of the excellent Polars DataFrame library.
33
+
34
+
35
+ # Commands
36
+ Lefts has five commands, which give it its name:
37
+ - **L**ift: trains multiple copies of a model across different subsets of data.
38
+ - **E**nsemble: Takes a set of models and makes them evaluate as one.
39
+ - **T**une: Allows a model to learn its hyperparameters from another.
40
+ - **F**eeds: Allows the output of one model to be used as a feature or target by another.
41
+ - **S**plit: Trains a model on a given train/test/validation split.
42
+
43
+ # Models
44
+
45
+ Lefts can operate on any model that is defined by:
46
+ - a fit method, which maps from training data into the model parameters
47
+ - a predict method, which maps from model parameters and test data into predictions.
48
+
49
+ A Lefts command creates a new model by transforming these functions into a new .fit and .predict. Because this new model also has a .fit and .predict, it can be transformed with further Lefts commands.
50
+
51
+
52
+ ### Conventions
53
+
54
+ Lefts imposes some constraints on model interfaces.
55
+ - All hyperparameters are passed as arguments to the fit method.
56
+ - We expect that data is passed to fit and predict as Polars dataframes.
57
+ - The predict method returns an iterable, with the order of predictions matching the order on the input training data frame.
58
+
59
+ See the example notebooks to understand how to adapt your models to the required format.
60
+
61
+ # An example
62
+
63
+ The following code shows lefts can be used to create complex models out of more basic ones. We start with an LGBM Regression model, and train an ensemble of models to predict each quantile. The ensemble is trained in a monthly rolling retrain.
64
+
65
+ See notebooks/quantile_ensemble.py for the full code.
66
+
67
+ ```python
68
+ features = ["temp", "atemp", "hum", "windspeed", "hr", "weekday", "mnth"]
69
+ target = "cnt"
70
+ quantiles = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
71
+ test_period_start_dates = pl.datetime_range(
72
+ start = dt.datetime(2011, 3, 1),
73
+ end = dt.datetime(2012, 12, 1),
74
+ interval='1mo',
75
+ eager=True
76
+ ).to_list()
77
+
78
+ quantile_models = []
79
+ for q in quantiles:
80
+ # Convert LGBMRegressor into the format required by lefts
81
+ base_model = leaf(tabular_model(
82
+ LGBMRegressor(objective="quantile", alpha=q),
83
+ features=features,
84
+ target=target,
85
+ ),
86
+ label=f"q{q}",
87
+ )
88
+
89
+ # 'Lift' each per-quantile model into a family of models, each with a different train and test period
90
+ rolling_retrain = lift(
91
+ base_model,
92
+ name=f"q{q}_rolling_retrain",
93
+ values=test_period_start_dates,
94
+
95
+ # A row is in a given train period if it is before the start of the test period
96
+ train_filter=lambda test_period_start_date: pl.col("datetime") < test_period_start_date,
97
+ # Each test period is one month long
98
+ test_filter=lambda test_period_start_date: pl.col("datetime").dt.month() == test_period_start_date.month,
99
+ aggregate_with=pl.coalesce,
100
+ )
101
+
102
+ quantile_models.append(rolling_retrain)
103
+
104
+ model = ensemble("quantiles", *quantile_models)
105
+
106
+ # Fits |quantiles| x |test_period_start_dates| models
107
+ model.fit(df)
108
+
109
+ # Adds |quantiles| columns, each with the unique prediction associated with that test row.
110
+ predictions = model.predict(df)
111
+ ```
112
+
113
+ Behind the scenes, the full workflow is constructed as a tree of lefts expression. You can see this tree by calling `model.print_tree()`
114
+
115
+ ```
116
+ Ensemble 'quantiles' (198 models) → outputs: [q0.1_rolling_retrain, ..., q0.9_rolling_retrain]
117
+ ├── Lift 'q0.1_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.1_rolling_retrain"
118
+ │ └── Leaf 'q0.1' (1 model)
119
+ ├── Lift 'q0.2_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.2_rolling_retrain"
120
+ │ └── Leaf 'q0.2' (1 model)
121
+ ├── Lift 'q0.3_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.3_rolling_retrain"
122
+ │ └── Leaf 'q0.3' (1 model)
123
+ ├── Lift 'q0.4_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.4_rolling_retrain"
124
+ │ └── Leaf 'q0.4' (1 model)
125
+ ├── Lift 'q0.5_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.5_rolling_retrain"
126
+ │ └── Leaf 'q0.5' (1 model)
127
+ ├── Lift 'q0.6_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.6_rolling_retrain"
128
+ │ └── Leaf 'q0.6' (1 model)
129
+ ├── Lift 'q0.7_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.7_rolling_retrain"
130
+ │ └── Leaf 'q0.7' (1 model)
131
+ ├── Lift 'q0.8_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.8_rolling_retrain"
132
+ │ └── Leaf 'q0.8' (1 model)
133
+ └── Lift 'q0.9_rolling_retrain' (22 models): [2011-03-01 00:00:00, ..., 2012-12-01 00:00:00] ⇒ coalesce → "q0.9_rolling_retrain"
134
+ └── Leaf 'q0.9' (1 model)
135
+ ```
@@ -0,0 +1,15 @@
1
+ lefts/__init__.py,sha256=tiyRNtX5l5r9fx8pkp1y3XFf7YbOOUoQlgFXYgS1rmc,175
2
+ lefts/helpers.py,sha256=wDMQyMA5L2-n-CkqXUHLQDS8TmstcumZaMgug3p0dEM,1116
3
+ lefts/interface.py,sha256=DV-Yv4MTX0dFEzvtphJVPVout6JkcfOCf_xSWTUkR9s,7086
4
+ lefts/nodes.py,sha256=9z9DEObOZyVn-itLFl4RaKMxHiWTebDi8yGMLovpaLc,2326
5
+ lefts/validation.py,sha256=KCA7bprPkgXBmBbOWgDHIgqTCz0DEHb2vGm_NcpGWH0,1850
6
+ lefts/interpreter/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ lefts/interpreter/fit.py,sha256=ENpd07BOcjvw7QCvMGXHevRpq9R4Ov27uVn1OrYiYUM,8392
8
+ lefts/interpreter/labels.py,sha256=CyC9ug3vXKDBkA34gtaORlwNlwo2PTwmGYMsqbTDuxM,3998
9
+ lefts/interpreter/masks.py,sha256=loqtbma1ds-U9Vrs-LAjPLryXnP_Ge9UcRHrDAcKoBc,3290
10
+ lefts/interpreter/predict.py,sha256=QHVXvtO7EwKs7V-Rxn3igEnlb8nbR2XKjo98seYN6jE,4428
11
+ lefts-0.1.0.dist-info/licenses/LICENSE,sha256=uNlk1ItRGN0hEHbvdbQmiOwPfN5CGxYD_vjNGBj70G8,11384
12
+ lefts-0.1.0.dist-info/METADATA,sha256=SLfclZ6oUYRSzumVLhYkQgnySjrWmJ9cSemlFSR9qrc,6677
13
+ lefts-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
14
+ lefts-0.1.0.dist-info/top_level.txt,sha256=1A9PVKzaLgSp4JMNqUa8GDWf1xHCpX8oogBXG8nJDAQ,6
15
+ lefts-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+ Copyright 2026 Niklas Mather
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ lefts