graphscribe 0.0.1__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.
@@ -0,0 +1,6 @@
1
+ """graphscribe: a line chart that explains itself, from 5 points to 100 million."""
2
+
3
+ from .core import LineChart, line
4
+
5
+ __version__ = "0.0.1"
6
+ __all__ = ["LineChart", "__version__", "line"]
graphscribe/core.py ADDED
@@ -0,0 +1,175 @@
1
+ from __future__ import annotations
2
+
3
+ import html
4
+ import os
5
+ import tempfile
6
+ import webbrowser
7
+ from typing import Any, Optional
8
+
9
+ import numpy as np
10
+
11
+ from . import teach
12
+ from .insights import Data, run_all
13
+ from .render.svg import render_line
14
+
15
+
16
+ class Explanation(str):
17
+ """A string that prints nicely in a terminal or notebook."""
18
+
19
+ def __repr__(self) -> str:
20
+ return str(self)
21
+
22
+
23
+ def _numbers(raw: Any, what: str) -> np.ndarray:
24
+ arr = np.asarray(raw)
25
+ if arr.dtype.kind in "iufb":
26
+ return arr.astype(float, copy=False)
27
+ try:
28
+ return arr.astype(float)
29
+ except (TypeError, ValueError):
30
+ raise ValueError(f"{what} must be numbers. Text values are not supported in a line "
31
+ "chart.") from None
32
+
33
+
34
+ def _prepare(y: Any, x: Any, y_label: str, x_label: str):
35
+ """Accept lists, arrays, pandas Series. Returns clean sorted float arrays."""
36
+ if hasattr(y, "index") and hasattr(y, "values"): # pandas Series
37
+ if x is None and np.asarray(y.index).dtype.kind in "iufM":
38
+ x = np.asarray(y.index)
39
+ y_label = y_label or str(getattr(y, "name", "") or "")
40
+ y = y.values
41
+ yv = _numbers(y, "Values")
42
+ if yv.ndim != 1:
43
+ raise ValueError("A line chart needs one list of values (and optionally an x list).")
44
+ is_time = False
45
+ if x is None:
46
+ xv = np.arange(yv.size, dtype=float)
47
+ else:
48
+ xa = np.asarray(x)
49
+ if xa.dtype.kind == "M":
50
+ nat = np.isnat(xa)
51
+ xv = xa.astype("datetime64[s]").astype(np.int64).astype(float)
52
+ xv[nat] = np.nan
53
+ is_time = True
54
+ elif xa.dtype.kind in "iuf":
55
+ xv = xa.astype(float, copy=False)
56
+ else:
57
+ raise ValueError("x must be numbers or dates.")
58
+ if xv.size != yv.size:
59
+ raise ValueError(f"x has {xv.size} items but the values have {yv.size}.")
60
+ ok = ~(np.isnan(yv) | np.isnan(xv))
61
+ missing = int(ok.size - ok.sum())
62
+ if missing:
63
+ xv, yv = xv[ok], yv[ok]
64
+ if yv.size == 0:
65
+ raise ValueError("There is no usable data (everything is empty or NaN).")
66
+ if yv.size > 1 and not bool(np.all(xv[1:] >= xv[:-1])):
67
+ order = np.argsort(xv, kind="stable")
68
+ xv, yv = xv[order], yv[order]
69
+ return xv, yv, is_time, missing, y_label
70
+
71
+
72
+ class LineChart:
73
+ def __init__(self, y: Any, x: Any = None, *, title: str = "", x_label: str = "",
74
+ y_label: str = ""):
75
+ self.x, self.y, self.is_time, self.missing, self.y_label = _prepare(
76
+ y, x, y_label, x_label)
77
+ self.title, self.x_label = title, x_label
78
+ self._found = None
79
+ self._drawn = None
80
+
81
+ # ----- understanding the data -------------------------------------------------------
82
+ def _insights(self):
83
+ if self._found is None: # computed once, reused by explain() and svg()
84
+ self._found = run_all(Data(self.x, self.y, self.is_time, self.x_label, self.y_label))
85
+ return self._found
86
+
87
+ def headline(self) -> str:
88
+ """One line that says what the chart shows, written by graphscribe."""
89
+ found = self._insights()
90
+ main = next((i.headline for i in found if i.headline and i.kind != "outliers"), "")
91
+ extra = next((i.headline for i in found if i.kind == "outliers" and i.headline), "")
92
+ return f"{main}, {extra}" if main and extra else (main or extra)
93
+
94
+ def findings(self) -> list:
95
+ lines = [i.text for i in self._insights()]
96
+ if self.missing:
97
+ lines.append(f"{self.missing:,} missing value(s) were skipped.")
98
+ return lines
99
+
100
+ def explain(self) -> Explanation:
101
+ """Plain-English explanation of what the chart shows."""
102
+ name = f" of '{self.y_label}'" if self.y_label else ""
103
+ lines = ["WHAT YOU ARE LOOKING AT",
104
+ f" A line chart{name} with {self.y.size:,} points. Your values come in order, "
105
+ "so a line shows how they change from one point to the next.",
106
+ "", "WHAT THE DATA SAYS"]
107
+ lines += [f" - {t}" for t in self.findings()]
108
+ if self.y.size > 3200:
109
+ lines += ["", "HOW IT WAS DRAWN",
110
+ f" Your {self.y.size:,} points are more than a screen can show. For every "
111
+ "pixel-wide slice the highest and the lowest value are kept, so no spike or "
112
+ "dip is hidden. All statistics above use every single point."]
113
+ return Explanation("\n".join(lines))
114
+
115
+ def teach(self) -> Explanation:
116
+ """A short lesson on how to read a line chart."""
117
+ return Explanation(teach.LINE)
118
+
119
+ # ----- drawing ----------------------------------------------------------------------
120
+ def svg(self, width: int = 800, height: int = 480, annotate: bool = True) -> str:
121
+ """Draw the chart. annotate=True adds a headline and points at what matters."""
122
+ marks, headline = (), ""
123
+ if annotate:
124
+ headline = self.headline()
125
+ marks = [m for i in self._insights() for m in i.marks]
126
+ rings = {m.x for m in marks if m.kind == "point"}
127
+ marks = tuple(m for m in marks if not (m.kind == "dot" and m.x in rings))
128
+ svg, self._drawn = render_line(
129
+ self.x, self.y, title=self.title, x_label=self.x_label, y_label=self.y_label,
130
+ x_is_time=self.is_time, headline=headline, marks=marks, width=width, height=height,
131
+ alt=f"line chart: {headline or self.title or self.y_label}")
132
+ return svg
133
+
134
+ def html(self) -> str:
135
+ esc = html.escape
136
+ pre = "white-space:pre-wrap;font:14px/1.6 system-ui,sans-serif"
137
+ return ("<div style='font-family:system-ui,sans-serif;max-width:820px'>"
138
+ f"<style>svg{{max-width:100%;height:auto}}</style>{self.svg()}"
139
+ f"<pre style='{pre}'>{esc(str(self.explain()))}</pre>"
140
+ "<details><summary style='cursor:pointer;font:600 14px system-ui'>"
141
+ f"Teach me how to read this</summary><pre style='{pre}'>"
142
+ f"{esc(str(self.teach()))}</pre></details></div>")
143
+
144
+ def _repr_html_(self) -> str: # Jupyter shows the chart and its explanation automatically
145
+ return self.html()
146
+
147
+ def __repr__(self) -> str:
148
+ return f"<graphscribe.LineChart {self.y.size:,} points>"
149
+
150
+ def save(self, path: str) -> "LineChart":
151
+ """Save as .svg (chart only) or .html (chart + explanation + lesson)."""
152
+ ext = os.path.splitext(path)[1].lower()
153
+ if ext == ".svg":
154
+ text = self.svg()
155
+ elif ext in (".html", ".htm"):
156
+ text = f"<!doctype html><meta charset='utf-8'><title>graphscribe</title>{self.html()}"
157
+ else:
158
+ raise ValueError("Save as .svg or .html. PNG export is planned, not built yet.")
159
+ with open(path, "w", encoding="utf-8") as f:
160
+ f.write(text)
161
+ return self
162
+
163
+ def show(self) -> "LineChart":
164
+ """Open the chart with its explanation in your web browser."""
165
+ fd, path = tempfile.mkstemp(suffix=".html", prefix="graphscribe_")
166
+ os.close(fd)
167
+ self.save(path)
168
+ webbrowser.open("file://" + path)
169
+ return self
170
+
171
+
172
+ def line(y: Any, x: Optional[Any] = None, *, title: str = "", x_label: str = "",
173
+ y_label: str = "") -> LineChart:
174
+ """Draw a line chart that explains itself. Works from 5 points to 100 million."""
175
+ return LineChart(y, x, title=title, x_label=x_label, y_label=y_label)
@@ -0,0 +1,6 @@
1
+ """Importing a module here registers its rule. Add new rules as new files."""
2
+
3
+ from . import extremes, outliers, summary, trend # noqa: F401
4
+ from .base import Data, Insight, Mark, fmt, register_insight, run_all
5
+
6
+ __all__ = ["Data", "Insight", "Mark", "fmt", "register_insight", "run_all"]
@@ -0,0 +1,20 @@
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+
5
+
6
+ def fit_line(x: np.ndarray, y: np.ndarray):
7
+ """Least-squares straight line in one pass. Returns (slope, intercept, r_squared)."""
8
+ xm, ym = float(x.mean()), float(y.mean())
9
+ dx = x - xm
10
+ sxx = float(np.dot(dx, dx))
11
+ if sxx == 0:
12
+ return 0.0, ym, 0.0
13
+ dy = y - ym
14
+ slope = float(np.dot(dx, dy)) / sxx
15
+ intercept = ym - slope * xm
16
+ ss_tot = float(np.dot(dy, dy))
17
+ if ss_tot == 0:
18
+ return slope, intercept, 0.0
19
+ r2 = (float(np.dot(dx, dy)) ** 2) / (sxx * ss_tot) # same as 1 - SSres/SStot for a line
20
+ return slope, intercept, max(0.0, min(1.0, r2))
@@ -0,0 +1,64 @@
1
+ """Insight registry. One insight rule = one small function = one file."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Callable, List, Optional
7
+
8
+ import numpy as np
9
+
10
+ from ..render.ticks import fmt, format_time
11
+
12
+ __all__ = ["Data", "Insight", "Mark", "fmt", "register_insight", "run_all"]
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Mark:
17
+ """Something to point at ON the chart, in data coordinates."""
18
+
19
+ kind: str # "point" (ring + callout), "dot" (quiet marker), "trend" (dashed line)
20
+ x: float
21
+ label: str
22
+ y: float = 0.0
23
+ x2: float = 0.0
24
+ y2: float = 0.0
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Insight:
29
+ kind: str
30
+ text: str
31
+ importance: int = 5 # 1 (minor) .. 10 (major): decides the order in explain()
32
+ headline: str = "" # a few words for the chart's title line
33
+ marks: tuple = () # Mark objects drawn on the chart itself
34
+
35
+
36
+ @dataclass
37
+ class Data:
38
+ """What a rule gets to look at. Arrays are clean (no NaN) and sorted by x."""
39
+
40
+ x: np.ndarray
41
+ y: np.ndarray
42
+ x_is_time: bool = False
43
+ x_name: str = ""
44
+ y_name: str = ""
45
+
46
+ def fmt_x(self, v: float) -> str:
47
+ if self.x_is_time:
48
+ return format_time(v, whole_days=(self.x[-1] - self.x[0]) >= 2 * 86400)
49
+ return fmt(v)
50
+
51
+
52
+ Rule = Callable[[Data], Optional[Insight]]
53
+ _RULES: List[Rule] = []
54
+
55
+
56
+ def register_insight(func: Rule) -> Rule:
57
+ """Decorator: add a rule so every chart runs it automatically."""
58
+ _RULES.append(func)
59
+ return func
60
+
61
+
62
+ def run_all(d: Data) -> List[Insight]:
63
+ found = [r for r in (rule(d) for rule in _RULES) if r is not None]
64
+ return sorted(found, key=lambda i: -i.importance)
@@ -0,0 +1,19 @@
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+
5
+ from .base import Data, Insight, Mark, fmt, register_insight
6
+
7
+
8
+ @register_insight
9
+ def extremes(d: Data):
10
+ if d.y.size < 3:
11
+ return None
12
+ hi, lo = int(np.argmax(d.y)), int(np.argmin(d.y))
13
+ text = (f"The highest value is {fmt(d.y[hi])} at {d.fmt_x(float(d.x[hi]))}. "
14
+ f"The lowest is {fmt(d.y[lo])} at {d.fmt_x(float(d.x[lo]))}.")
15
+ marks = ()
16
+ if d.y.size > 12: # with 12 or fewer points every value is already written on the chart
17
+ marks = (Mark("dot", float(d.x[hi]), f"high: {fmt(d.y[hi])}", float(d.y[hi])),
18
+ Mark("dot", float(d.x[lo]), f"low: {fmt(d.y[lo])}", float(d.y[lo])))
19
+ return Insight("extremes", text, importance=6, marks=marks)
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+
5
+ from ._stats import fit_line
6
+ from .base import Data, Insight, Mark, fmt, register_insight
7
+
8
+
9
+ @register_insight
10
+ def outliers(d: Data):
11
+ if d.y.size < 8:
12
+ return None
13
+ slope, intercept, _ = fit_line(d.x, d.y)
14
+ score = d.y - (slope * d.x + intercept) # distance from the trend, not from zero
15
+ q1, q3 = np.percentile(score, [25, 75])
16
+ iqr = q3 - q1
17
+ if iqr == 0:
18
+ return None
19
+ mild = (score < q1 - 1.5 * iqr) | (score > q3 + 1.5 * iqr)
20
+ far = (score < q1 - 3 * iqr) | (score > q3 + 3 * iqr)
21
+ n_mild, n_far = int(mild.sum()), int(far.sum())
22
+ if n_mild == 0:
23
+ return Insight("outliers", "No unusual values (outliers) were found.", importance=4)
24
+
25
+ idx = np.where(far if n_far else mild)[0]
26
+ idx = idx[np.argsort(-np.abs(score[idx] - np.median(score)))][:5]
27
+ where = (lambda i: f"{fmt(d.y[i])} on {d.fmt_x(float(d.x[i]))}") if d.x_is_time else (
28
+ lambda i: f"{fmt(d.y[i])} at x = {d.fmt_x(float(d.x[i]))}")
29
+ shown = ", ".join(where(i) for i in idx)
30
+
31
+ if not n_far:
32
+ word = "value is" if n_mild == 1 else "values are"
33
+ return Insight(
34
+ "outliers",
35
+ f"{n_mild:,} {word} a little unusual, but none is extreme (for example {shown}). "
36
+ "Some of this is normal in real data.", importance=5)
37
+
38
+ word = "extreme value sits" if n_far == 1 else "extreme values sit"
39
+ more = f" (showing the 5 biggest of {n_far:,})" if n_far > 5 else ""
40
+ extra = f" {n_mild - n_far:,} more are mildly unusual." if n_mild > n_far else ""
41
+ marks = tuple(Mark("point", float(d.x[i]), f"extreme: {fmt(d.y[i])}", float(d.y[i]))
42
+ for i in idx[:3])
43
+ check = "it is a real event or a data error" if n_far == 1 else (
44
+ "they are real events or data errors")
45
+ return Insight(
46
+ "outliers",
47
+ f"{n_far:,} {word} far from the rest: {shown}{more}. Check whether {check}.{extra}",
48
+ importance=8, headline=f"with {n_far:,} extreme value" + ("" if n_far == 1 else "s"),
49
+ marks=marks)
@@ -0,0 +1,15 @@
1
+ from __future__ import annotations
2
+
3
+ import numpy as np
4
+
5
+ from .base import Data, Insight, fmt, register_insight
6
+
7
+
8
+ @register_insight
9
+ def summary(d: Data):
10
+ n = d.y.size
11
+ subject = f"{d.y_name} ranges" if d.y_name else "The values range"
12
+ text = (f"There are {n:,} points. {subject} from {fmt(d.y.min())} to {fmt(d.y.max())}. "
13
+ f"The average is {fmt(d.y.mean())} and the middle value (median) is "
14
+ f"{fmt(np.median(d.y))}.")
15
+ return Insight("summary", text, importance=3)
@@ -0,0 +1,31 @@
1
+ from __future__ import annotations
2
+
3
+ from ._stats import fit_line
4
+ from .base import Data, Insight, Mark, fmt, register_insight
5
+
6
+
7
+ @register_insight
8
+ def trend(d: Data):
9
+ if d.y.size < 3:
10
+ return None
11
+ slope, intercept, r2 = fit_line(d.x, d.y)
12
+ x0, x1 = float(d.x[0]), float(d.x[-1])
13
+ start, end = slope * x0 + intercept, slope * x1 + intercept
14
+ scale = abs(float(d.y.mean())) or 1.0
15
+ if r2 < 0.1 or abs(end - start) / scale < 0.01:
16
+ return Insight("trend", "There is no clear upward or downward trend. The values stay "
17
+ "around the same level.", importance=7, headline="Holding steady")
18
+ up = slope > 0
19
+ strength = "strong" if r2 >= 0.7 else "moderate" if r2 >= 0.4 else "weak"
20
+ if r2 >= 0.4:
21
+ head = "Rising steadily" if up else "Falling steadily"
22
+ else:
23
+ head = "Drifting " + ("up" if up else "down") + " slightly"
24
+ return Insight(
25
+ "trend",
26
+ f"There is a {strength} {'upward' if up else 'downward'} trend. The overall line "
27
+ f"{'rises' if up else 'falls'} from about {fmt(start)} to {fmt(end)}. A straight line "
28
+ f"explains about {r2 * 100:.0f}% of the ups and downs (R-squared = {r2:.2f}).",
29
+ importance=9, headline=head,
30
+ marks=(Mark("trend", x0, f"overall trend: {'up' if up else 'down'}", start, x1, end),),
31
+ )
@@ -0,0 +1 @@
1
+ """graphscribe's own renderer. No matplotlib, no plotting dependency. Output is SVG."""
@@ -0,0 +1,21 @@
1
+ """Shrink huge data to what a screen can show, without hiding the shape.
2
+
3
+ A screen is about 1000 pixels wide, so drawing 10 million points is pointless. For every
4
+ pixel-wide slice of the data we keep its lowest and highest value. Spikes and dips survive.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+
11
+
12
+ def minmax_decimate(x: np.ndarray, y: np.ndarray, buckets: int):
13
+ n = y.size
14
+ if n <= buckets * 4:
15
+ return x, y
16
+ k = n // buckets
17
+ body = y[: k * buckets].reshape(buckets, k)
18
+ base = np.arange(buckets) * k
19
+ pair = np.stack([base + body.argmin(axis=1), base + body.argmax(axis=1)], axis=1)
20
+ idx = np.unique(np.concatenate([[0], pair.ravel(), [n - 1]]))
21
+ return x[idx], y[idx]
@@ -0,0 +1,139 @@
1
+ """Draws a line chart as a clean, scalable SVG that explains itself."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from xml.sax.saxutils import escape
6
+
7
+ import numpy as np
8
+
9
+ from .reduce import minmax_decimate
10
+ from .ticks import fmt, format_number, nice_ticks, time_ticks
11
+
12
+ INK, MUTED, GRID = "#1f2937", "#6b7280", "#ece9e1"
13
+ BLUE, ACCENT, PAPER = "#1d4ed8", "#ea580c", "#fbfaf7"
14
+ FONT = "system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif"
15
+
16
+
17
+ def _linmap(lo, hi, a, b):
18
+ span = (hi - lo) or 1.0
19
+ return lambda v: a + (np.asarray(v, dtype=float) - lo) / span * (b - a)
20
+
21
+
22
+ def _x_ticks(lo, hi, is_time):
23
+ if is_time:
24
+ return time_ticks(lo, hi)
25
+ ticks, step = nice_ticks(lo, hi)
26
+ return ticks, [format_number(t, step) for t in ticks]
27
+
28
+
29
+ def _text(x, y, s, size=12, fill=INK, anchor="start", weight=400, italic=False, halo=False):
30
+ style = ' font-style="italic"' if italic else ""
31
+ common = (f'x="{x:.1f}" y="{y:.1f}" text-anchor="{anchor}" font-size="{size}" '
32
+ f'font-weight="{weight}"{style}')
33
+ main = f'<text {common} fill="{fill}">{escape(s)}</text>'
34
+ if not halo:
35
+ return main
36
+ # an outline layer underneath keeps the label readable where it crosses the line
37
+ under = (f'<text {common} fill="{PAPER}" stroke="{PAPER}" stroke-width="5" '
38
+ f'stroke-linejoin="round">{escape(s)}</text>')
39
+ return under + main
40
+
41
+
42
+ def _title_block(title, headline, left, pw):
43
+ if headline:
44
+ size = max(15, min(24, int(pw / (0.56 * len(headline)))))
45
+ if title:
46
+ return [_text(left, 26, title.upper(), 11, MUTED, weight=600),
47
+ _text(left, 58, headline, size, INK, weight=700)]
48
+ return [_text(left, 40, headline, size, INK, weight=700)]
49
+ return [_text(left, 28, title, 17, INK, weight=600)] if title else []
50
+
51
+
52
+ def _marks(marks, mx, my, left, top, pw):
53
+ out, right = [], left + pw
54
+ for m in marks:
55
+ if m.kind == "trend":
56
+ x1, y1, x2, y2 = float(mx(m.x)), float(my(m.y)), float(mx(m.x2)), float(my(m.y2))
57
+ out.append(f'<line x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" '
58
+ f'stroke="{ACCENT}" stroke-width="1.6" stroke-dasharray="6 5"/>')
59
+ w = 6.6 * len(m.label) # a small legend, top right, so it never covers the data
60
+ out.append(f'<line x1="{right - w - 36:.1f}" x2="{right - w - 10:.1f}" '
61
+ f'y1="{top - 14}" y2="{top - 14}" stroke="{ACCENT}" stroke-width="1.6" '
62
+ f'stroke-dasharray="6 5"/>')
63
+ out.append(_text(right, top - 10, m.label, 12, ACCENT, "end", 600))
64
+ continue
65
+ px, py = float(mx(m.x)), float(my(m.y))
66
+ ring = m.kind == "point"
67
+ gap = 34 if ring else 14
68
+ if px - left < 80: # near the left edge: write the label to the right of the point
69
+ lx, ly, anchor = px + (16 if ring else 10), py + 4, "start"
70
+ elif right - px < 80:
71
+ lx, ly, anchor = px - (16 if ring else 10), py + 4, "end"
72
+ elif py - gap - 8 > top:
73
+ lx, ly, anchor = px, py - gap, "middle"
74
+ else: # no room above: put it beside the point, not on top of the line
75
+ lx, ly, anchor = px + (16 if ring else 10), py + 4, "start"
76
+ if ring:
77
+ out.append(f'<circle cx="{px:.1f}" cy="{py:.1f}" r="7" fill="none" '
78
+ f'stroke="{ACCENT}" stroke-width="2"/>')
79
+ if anchor == "middle":
80
+ out.append(f'<line x1="{px:.1f}" y1="{py - 8:.1f}" x2="{px:.1f}" '
81
+ f'y2="{ly + 4:.1f}" stroke="{ACCENT}"/>')
82
+ else: # "dot": a quiet marker for the highest / lowest point
83
+ out.append(f'<circle cx="{px:.1f}" cy="{py:.1f}" r="4.5" fill="{ACCENT}"/>')
84
+ out.append(_text(lx, ly, m.label, 12, ACCENT, anchor, 600, halo=True))
85
+ return out
86
+
87
+
88
+ def render_line(x, y, *, title="", x_label="", y_label="", x_is_time=False, headline="",
89
+ marks=(), width=800, height=480, alt=""):
90
+ """Return (svg_text, points_actually_drawn)."""
91
+ left, right, bottom = 72, 28, 64
92
+ top = (92 if title else 72) if headline else 48
93
+ pw, ph = width - left - right, height - top - bottom
94
+ xlo, xhi = float(x[0]), float(x[-1])
95
+ ylo, yhi = float(y.min()), float(y.max())
96
+ pad = (yhi - ylo) * 0.14 or 1.0
97
+ ylo, yhi = ylo - pad, yhi + pad
98
+ mx, my = _linmap(xlo, xhi, left, left + pw), _linmap(ylo, yhi, top + ph, top)
99
+
100
+ body = []
101
+ yt, ystep = nice_ticks(ylo, yhi, 5)
102
+ for t in yt:
103
+ py = float(my(t))
104
+ body.append(f'<line x1="{left}" x2="{left + pw}" y1="{py:.1f}" y2="{py:.1f}" '
105
+ f'stroke="{GRID}"/>')
106
+ body.append(_text(left - 10, py + 4, format_number(t, ystep), 12, MUTED, "end"))
107
+ xt, xlabels = _x_ticks(xlo, xhi, x_is_time)
108
+ for t, lab in zip(xt, xlabels, strict=True):
109
+ body.append(_text(float(mx(t)), top + ph + 22, lab, 12, MUTED, "middle"))
110
+
111
+ xs, ys = minmax_decimate(x, y, pw)
112
+ px, py = mx(xs), my(ys)
113
+ pts = " L".join(f"{a:.1f},{b:.1f}" for a, b in zip(px, py, strict=True))
114
+ base = top + ph
115
+ body.append(f'<path d="M{pts} L{px[-1]:.1f},{base} L{px[0]:.1f},{base} Z" '
116
+ f'fill="{BLUE}" fill-opacity="0.07"/>')
117
+ body.append(f'<path d="M{pts}" fill="none" stroke="{BLUE}" stroke-width="2" '
118
+ f'stroke-linejoin="round" stroke-linecap="round"/>')
119
+ if xs.size <= 60:
120
+ for a, b in zip(px, py, strict=True):
121
+ body.append(f'<circle cx="{a:.1f}" cy="{b:.1f}" r="3.2" fill="{BLUE}"/>')
122
+ if xs.size <= 12: # tiny data: write every value on the chart
123
+ for a, b, v in zip(px, py, ys, strict=True):
124
+ body.append(_text(a, b - 11, fmt(v), 12, INK, "middle", 600, halo=True))
125
+ body.append(f'<line x1="{left}" x2="{left + pw}" y1="{base}" y2="{base}" '
126
+ f'stroke="{INK}" stroke-width="1.4"/>')
127
+ body += _marks(marks, mx, my, left, top, pw)
128
+ body += _title_block(title, headline, left, pw)
129
+ if x_label:
130
+ body.append(_text(left + pw / 2, height - 14, x_label, 13, MUTED, "middle"))
131
+ if y_label:
132
+ body.append(f'<text transform="translate(16,{top + ph / 2}) rotate(-90)" '
133
+ f'text-anchor="middle" font-size="13" fill="{MUTED}">{escape(y_label)}</text>')
134
+ label = escape(alt or headline or title or "line chart")
135
+ svg = (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" '
136
+ f'width="{width}" height="{height}" role="img" aria-label="{label}" '
137
+ f'font-family="{FONT}" data-drawn-points="{xs.size}">'
138
+ f'<rect width="{width}" height="{height}" fill="{PAPER}"/>' + "".join(body) + "</svg>")
139
+ return svg, int(xs.size)
@@ -0,0 +1,105 @@
1
+ """Pick clean axis tick values and format them for people."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+
7
+ import numpy as np
8
+
9
+
10
+ def nice_ticks(lo: float, hi: float, target: int = 6):
11
+ """Return (tick_values, step) with round numbers like 0, 20, 40 or 0.25, 0.5."""
12
+ if not (math.isfinite(lo) and math.isfinite(hi)):
13
+ return np.array([0.0, 1.0]), 1.0
14
+ if lo == hi:
15
+ pad = abs(lo) * 0.5 or 1.0
16
+ lo, hi = lo - pad, hi + pad
17
+ raw = (hi - lo) / target
18
+ mag = 10 ** math.floor(math.log10(raw))
19
+ step = mag * 10
20
+ for m in (1, 2, 2.5, 5, 10):
21
+ if raw <= m * mag:
22
+ step = m * mag
23
+ break
24
+ first = math.ceil(lo / step - 1e-9)
25
+ last = math.floor(hi / step + 1e-9)
26
+ return np.arange(first, last + 1) * step, step
27
+
28
+
29
+ def format_number(v: float, step: float) -> str:
30
+ a = abs(v)
31
+ if a >= 1e9:
32
+ return f"{v / 1e9:g}B"
33
+ if a >= 1e6:
34
+ return f"{v / 1e6:g}M"
35
+ d = 0
36
+ while d < 8 and abs(round(step, d) - step) > 1e-9 * max(step, 1e-12):
37
+ d += 1
38
+ if a >= 1e4 and d == 0:
39
+ return f"{v:,.0f}"
40
+ return f"{v:.{d}f}"
41
+
42
+
43
+ def format_time(seconds: float, whole_days: bool) -> str:
44
+ stamp = str(np.datetime64(int(round(seconds)), "s"))
45
+ return stamp[:10] if whole_days else stamp[:16].replace("T", " ")
46
+
47
+
48
+ def fmt(v: float) -> str:
49
+ """Numbers for people: 11,590 not 1.159e+04, and no pointless decimals."""
50
+ v = float(v)
51
+ a = abs(v)
52
+ if a >= 1e4:
53
+ return f"{v:,.0f}"
54
+ if a >= 100:
55
+ return f"{v:,.1f}".rstrip("0").rstrip(".")
56
+ return f"{v:.4g}"
57
+
58
+
59
+ _MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
60
+
61
+
62
+ def time_ticks(lo: float, hi: float, target: int = 6):
63
+ """Calendar-aware ticks for a time axis (seconds since 1970): month and year starts, not
64
+ random days. Returns (tick_seconds, labels)."""
65
+ days = (hi - lo) / 86400
66
+ lo_dt, hi_dt = np.datetime64(int(lo), "s"), np.datetime64(int(hi), "s")
67
+
68
+ def keep(secs):
69
+ secs = np.asarray(secs, dtype=float)
70
+ return secs[(secs >= lo - 1e-6) & (secs <= hi + 1e-6)]
71
+
72
+ if days < 2: # hours and minutes
73
+ ticks, _ = nice_ticks(lo, hi, target)
74
+ return ticks, [format_time(t, False) for t in ticks]
75
+ if days <= 45: # whole days
76
+ step = next((s for s in (1, 2, 3, 7, 14) if days / s <= target), 14)
77
+ d0 = int(np.ceil(lo / 86400 / step)) * step
78
+ secs = keep(np.arange(d0, int(hi // 86400) + 1, step) * 86400.0)
79
+ labels = []
80
+ for s in secs:
81
+ d = np.datetime64(int(s), "s").astype("datetime64[D]")
82
+ labels.append(f"{_MONTHS[int(str(d)[5:7]) - 1]} {int(str(d)[8:10]):02d}")
83
+ return secs, labels
84
+ months = days / 30.44
85
+ step = next((s for s in (1, 2, 3, 6) if months / s <= target), None)
86
+ if step is not None: # month starts
87
+ m_lo = int(lo_dt.astype("datetime64[M]").astype(int))
88
+ m_hi = int(hi_dt.astype("datetime64[M]").astype(int))
89
+ ms = np.arange(-(-m_lo // step) * step, m_hi + 1, step)
90
+ stamps = ms.astype("datetime64[M]").astype("datetime64[s]").astype(np.int64)
91
+ secs = keep(stamps)
92
+ labels = []
93
+ for s in secs:
94
+ m = np.datetime64(int(s), "s").astype("datetime64[M]")
95
+ labels.append(f"{_MONTHS[int(str(m)[5:7]) - 1]} {str(m)[:4]}")
96
+ return secs, labels
97
+ years = months / 12 # year starts
98
+ step = next((s for s in (1, 2, 5, 10, 20, 25, 50, 100) if years / s <= target), 100)
99
+ y_lo = int(lo_dt.astype("datetime64[Y]").astype(int)) + 1970
100
+ y_hi = int(hi_dt.astype("datetime64[Y]").astype(int)) + 1970
101
+ ys = np.arange(-(-y_lo // step) * step, y_hi + 1, step)
102
+ stamps = (ys - 1970).astype("datetime64[Y]").astype("datetime64[s]").astype(np.int64)
103
+ secs = keep(stamps)
104
+ inside = [lo - 1e-6 <= s <= hi + 1e-6 for s in stamps]
105
+ return secs, [str(int(y)) for y, ok in zip(ys, inside, strict=True) if ok]
graphscribe/teach.py ADDED
@@ -0,0 +1,16 @@
1
+ """Teaching text: how to read a line chart. Plain English, no assumed knowledge."""
2
+
3
+ LINE = """HOW TO READ A LINE CHART
4
+ 1. The bottom axis (X) is usually time or order. Read the line from left to right.
5
+ 2. The side axis (Y) is the thing being measured. Higher on the page means a bigger value.
6
+ 3. If the line goes up, the value is growing. If it goes down, the value is shrinking.
7
+ 4. A steeper line means faster change. A flat line means no change.
8
+ 5. A sudden spike or dip is an outlier. Ask what happened at that moment.
9
+ 6. The trend is the overall direction, ignoring the small wiggles.
10
+
11
+ WORDS YOU WILL MEET
12
+ - Mean (average): add everything up, divide by how many there are.
13
+ - Median: the middle value when you sort them. Extreme values do not move it.
14
+ - Outlier: a value far away from the others.
15
+ - R-squared: a number from 0 to 1. Near 1 means a straight line fits the data well.
16
+ """
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.5
2
+ Name: graphscribe
3
+ Version: 0.0.1
4
+ Summary: A line chart that explains itself and teaches you to read it. Own renderer, NumPy only.
5
+ Project-URL: Homepage, https://github.com/YOUR_USERNAME/graphscribe
6
+ Project-URL: Issues, https://github.com/YOUR_USERNAME/graphscribe/issues
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: education,explainable,line-chart,time-series,visualization
10
+ Classifier: Development Status :: 2 - Pre-Alpha
11
+ Classifier: Intended Audience :: Education
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Education
15
+ Classifier: Topic :: Scientific/Engineering :: Visualization
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: numpy>=1.22
18
+ Provides-Extra: dev
19
+ Requires-Dist: build; extra == 'dev'
20
+ Requires-Dist: pip-audit; extra == 'dev'
21
+ Requires-Dist: pytest>=8; extra == 'dev'
22
+ Requires-Dist: ruff>=0.5; extra == 'dev'
23
+ Requires-Dist: twine; extra == 'dev'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # graphscribe
27
+
28
+ A line chart that explains itself.
29
+
30
+ You give it numbers. It draws the chart, writes a headline, points at the important things on the
31
+ picture, and teaches you how to read it. It works the same from 5 points to 50 million.
32
+
33
+ ![12 months of sales: every value written on the chart](docs/img/small.svg)
34
+
35
+ ## Why one chart only
36
+
37
+ I want visualization to be so simple that someone who knows nothing about data can still understand
38
+ it. That is a big goal, so I am starting with one graph and going as deep as I can before adding
39
+ the next. The line chart is the right first one: it covers a tiny list of monthly sales and a
40
+ sensor that logs ten million readings, and a beginner meets it on day one.
41
+
42
+ The idea underneath: most libraries draw a picture and leave you alone with it. graphscribe also
43
+ tells you what you are looking at, the way a good teacher would, and it does that on the chart
44
+ itself, not in a paragraph somewhere else.
45
+
46
+ ```python
47
+ import graphscribe as gs
48
+
49
+ chart = gs.line(sales, x=months, title="Monthly sales")
50
+
51
+ chart # in Jupyter: the chart, the explanation and a lesson
52
+ print(chart.explain()) # what the data says, in plain English
53
+ print(chart.teach()) # how to read a line chart
54
+ chart.show() # opens in your browser
55
+ chart.save("sales.svg") # or "sales.html" (chart + explanation + lesson)
56
+ ```
57
+
58
+ ## What it does
59
+
60
+ - **Writes its own headline.** "Rising steadily, with 1 extreme value."
61
+ - **Points at what matters.** A ring around a strange value, a dashed trend line, the highest and
62
+ lowest point. No hunting.
63
+ - **Adapts to the size of your data.** With 12 points every value is written on the chart. With
64
+ 730 you get the shape and the one odd day. With 10 million you get the same clean chart.
65
+ - **Understands dates.** Axis labels land on month and year starts, not random days.
66
+ - **Never hides a spike.** For every pixel-wide slice of data it keeps the highest and lowest
67
+ value. All the statistics use every single point.
68
+ - **Its own renderer.** No matplotlib or any plotting library underneath. The only dependency is
69
+ NumPy. Output is SVG.
70
+
71
+ ![730 days of visitors with one strange day](docs/img/medium.svg)
72
+
73
+ ## Test it from small to big
74
+
75
+ `python benchmarks/bench_line.py` runs this on your machine. Every row plants one spike and checks
76
+ that graphscribe finds it. These numbers are from a small cloud machine (4 GB RAM):
77
+
78
+ | Points | Load | Explain | Draw | Total | SVG size | Peak memory | Spike found |
79
+ |---:|---:|---:|---:|---:|---:|---:|:---:|
80
+ | 1,000 | 0.000 s | 0.010 s | 0.002 s | 0.012 s | 28 KB | 39 MB | yes |
81
+ | 10,000 | 0.000 s | 0.001 s | 0.003 s | 0.004 s | 38 KB | 39 MB | yes |
82
+ | 100,000 | 0.000 s | 0.006 s | 0.002 s | 0.009 s | 38 KB | 43 MB | yes |
83
+ | 1,000,000 | 0.004 s | 0.053 s | 0.003 s | 0.060 s | 38 KB | 79 MB | yes |
84
+ | 10,000,000 | 0.077 s | 0.783 s | 0.029 s | 0.889 s | 39 KB | 375 MB | yes |
85
+ | 50,000,000 | 0.268 s | 2.587 s | 0.150 s | 3.005 s | 39 KB | 1,660 MB | yes |
86
+
87
+ ![10 million sensor readings, same code](docs/img/big.svg)
88
+
89
+ ## Honest limits (v0.0.1)
90
+
91
+ - **Memory is the real limit.** It uses about 33 bytes per point, so 100 million points needs
92
+ about 3.5 GB. Reading data in chunks instead of all at once is the first thing to fix.
93
+ - **One series per chart.** No multiple lines yet.
94
+ - **Missing values are skipped.** The line joins across them. It should show a gap instead.
95
+ - **SVG and HTML only.** No PNG yet.
96
+ - **Not interactive.** No zoom or hover yet.
97
+ - **Explanations are basic.** Trend, extreme values, highest and lowest. A good statistician or
98
+ teacher could make this much better, and that is exactly what I am looking for.
99
+
100
+ ## Where this goes next
101
+
102
+ Going deeper on the line chart before any new chart type:
103
+
104
+ 1. Multiple lines, with automatic "which one changed most" explanation.
105
+ 2. Gaps for missing data, and detecting repeating patterns (daily, weekly, yearly).
106
+ 3. Reading data in chunks, so memory stays small for any size.
107
+ 4. PNG export from a pure-NumPy encoder.
108
+ 5. Zoom: re-draw the detail of any region you select.
109
+
110
+ ## Install
111
+
112
+ Not on PyPI yet. For now:
113
+
114
+ ```bash
115
+ pip install git+https://github.com/YOUR_USERNAME/graphscribe
116
+ ```
117
+
118
+ ## Help build it
119
+
120
+ The easiest first contribution is one new insight rule: one small function in one file that says
121
+ something useful about a line chart in plain English. Read [CONTRIBUTING.md](CONTRIBUTING.md).
122
+
123
+ ## License
124
+
125
+ Apache License 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,18 @@
1
+ graphscribe/__init__.py,sha256=HLtIpbbIIhb_fidP02RD90Sqc1wTlaTZUvLAd7U7MIM,189
2
+ graphscribe/core.py,sha256=KEkl8IM_3TlCUfI_NptCdpVlaYCYDdDFHFUidVenWVU,7470
3
+ graphscribe/teach.py,sha256=7Pd2ZfXPS_WPY8IKValxmRQ3ECfjfD5ekyn3bQp36wk,889
4
+ graphscribe/insights/__init__.py,sha256=f8oILIgMeDU-BqGZF6WFJUn5YEjGdZEzqrTvdtX5AnY,289
5
+ graphscribe/insights/_stats.py,sha256=fDyL7FcdhedZVig5hUYPsMR2I9QiMsk3wLaWzFN91Ec,655
6
+ graphscribe/insights/base.py,sha256=52R8axHe64JpuY8IOvqWNys90cLxC3EytJxrK03FBZc,1667
7
+ graphscribe/insights/extremes.py,sha256=fEtpGbmyTb_sGurT_lIs7PG1KR4tH_7IdN5Xjxc7UmY,757
8
+ graphscribe/insights/outliers.py,sha256=1BRopmcqjdTFVkZgaKAVHIbjgHNOBqtPVco5BvBxLVY,2076
9
+ graphscribe/insights/summary.py,sha256=XnU9R2cgpz8KVlf2LqmKnoI_t4vBGR2d76xoqbFTuvw,505
10
+ graphscribe/insights/trend.py,sha256=IVtT6ILYDTkaj3gR_MWBjzN1Bnd34HbFsLUmrEHdkPI,1346
11
+ graphscribe/render/__init__.py,sha256=h5_s8pjnR67sYYFrjoWhI2T5aAyAHQKmq_wEURq5C9s,88
12
+ graphscribe/render/reduce.py,sha256=A5MG5kMOAvc8yLkpnS1sYyg_RQRax9PiauV2rYa0KJk,723
13
+ graphscribe/render/svg.py,sha256=XH8gVaz09-Lfdd2ZuMHTtjGurHkX7xOu80E6Q15rowc,6720
14
+ graphscribe/render/ticks.py,sha256=NYlaWgGemEsoPpYpBnYat-Ze6KXTP0HGeMWnKK7IFEY,3947
15
+ graphscribe-0.0.1.dist-info/METADATA,sha256=1CZxq4_1uyL1dVg2XNv0SNB-_GM3EIEqdAlCFyKFflU,5430
16
+ graphscribe-0.0.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
17
+ graphscribe-0.0.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
18
+ graphscribe-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.