Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Plotting - major steps towards final product #2

Merged
merged 6 commits into from
Aug 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions pliffy/blocks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
from typing import NamedTuple, Tuple, Union, Literal
from pathlib import Path

from pliffy import estimate


class ABD(NamedTuple):
"""Helper namedtuple"""

a: Union[str, int, float, "estimate.Estimates"] = None
b: Union[str, int, float, "estimate.Estimates"] = None
diff: Union[str, int, float, "estimate.Estimates"] = None


class PlotInfo(NamedTuple):
"""Information used to generate plot

Includes sensible defaults to reduce need for user input
"""

x_tick_labels: ABD = ABD(a="a", b="b", diff="diff")
measure_units: str = "Amplitude (a.u.)"
plot_name: str = "figure"
save: Literal[True, False] = False
save_path: Path = None

summary_symbol: ABD = ABD(a="o", b="o", diff="^")
symbol_color: ABD = ABD(a="black", b="black", diff="black")
summary_symbol_size: ABD = ABD(a=5, b=5, diff=6)
raw_data_symbol_size: ABD = ABD(a=3, b=3, diff=3)
paired_data_joining_lines: bool = True
paired_data_line_width: int = 1
paired_data_line_color: str = "gainsboro"
ci_line_width: ABD = ABD(a=1, b=1, diff=1)
horiz_line_to_diffs: bool = False
join_ab_means: bool = True
ax1_y_range: Tuple = None
ax2_y_range: Tuple = None
ax1_y_ticks: Tuple = None
ax2_y_ticks: Tuple = None
ab_sub_label: str = None
bottom_box: bool = False
alpha: float = 0.2


class PliffyData(NamedTuple):
"""Data and details required from user

See :function:`pliffy.estimates.calc` parameters for details.
"""

a: list = None
b: list = None
design: Literal["paired", "unpaired"] = "unpaired"
ci_percentage: int = 95
21 changes: 8 additions & 13 deletions pliffy/estimate.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
from scipy.stats import t
import numpy as np

from pliffy import plot
from pliffy import blocks


def calc(pliffy_data: plot.PliffyData) -> Tuple["Estmates", Union[list, None]]:
def calc(pliffy_data: "blocks.PliffyData") -> "Estmates":
"""Calculate mean difference and confidence interval

Parameters
Expand All @@ -18,9 +18,6 @@ def calc(pliffy_data: plot.PliffyData) -> Tuple["Estmates", Union[list, None]]:
Second set of data
design
Flag to identify if data `a` and `b` are `paired` or `unpaired`
measure_units
Identifies the measure and units of data `a` and `b`.
Example: "Torque (Nm)" or "amplitude (Volts)"
ci_percentage
Desired confidence interval.
Example: 95 or 99
Expand All @@ -31,16 +28,15 @@ def calc(pliffy_data: plot.PliffyData) -> Tuple["Estmates", Union[list, None]]:
)
estimates_a, estimates_b = _calc_means_and_confidence_intervals(pliffy_data)
estimates_diff = None
diff_vals = None
if pliffy_data.design == "unpaired":
estimates_diff = _unpaired_diff_mean_and_confidence_interval(
pliffy_data, estimates_a, estimates_b
)
if pliffy_data.design == "paired":
estimates_diff, diff_vals = _paired_diff_mean_and_confidence_interval(
estimates_diff = _paired_diff_mean_and_confidence_interval(
pliffy_data
)
return estimates_diff, diff_vals
return estimates_a, estimates_b, estimates_diff


class Estimates(NamedTuple):
Expand Down Expand Up @@ -85,7 +81,7 @@ def _t_value(ci: int, degrees_of_freedom: int):


def _unpaired_diff_mean_and_confidence_interval(
pliffy_data: plot.PliffyData, estimates_a: "Estimates", estimates_b: "Estimates"
pliffy_data: "blocks.PliffyData", estimates_a: "Estimates", estimates_b: "Estimates"
) -> "Estimates":
"""Calculate mean difference of confidence interval of the mean difference

Expand All @@ -107,7 +103,7 @@ def _unpaired_diff_mean_and_confidence_interval(
return Estimates(mean=diff_mean, ci=diff_ci_vals)


def _data_len(pliffy_data: plot.PliffyData) -> Tuple[int, int]:
def _data_len(pliffy_data: "blocks.PliffyData") -> Tuple[int, int]:
"""Determine length of data `a` and `b`"""
return len(pliffy_data.a), len(pliffy_data.b)

Expand All @@ -118,7 +114,7 @@ def _weighted_sd(data: List[float]) -> float:


def _paired_diff_mean_and_confidence_interval(
pliffy_data: plot.PliffyData,
pliffy_data: "blocks.PliffyData",
) -> Tuple["Estimates", List[float]]:
"""Calculate mean difference of confidence interval of the mean difference"""
len_a, len_b = _data_len(pliffy_data)
Expand All @@ -130,7 +126,7 @@ def _paired_diff_mean_and_confidence_interval(
estimates_diff = _calc_mean_and_confidence_interval(
diff_vals, pliffy_data.ci_percentage
)
return estimates_diff, diff_vals
return estimates_diff


def _paired_diffs(pliffy_data):
Expand All @@ -140,5 +136,4 @@ def _paired_diffs(pliffy_data):

class UnequalLength(Exception):
"""Custom exception for paired analysis when data_a/data_b not same length"""

pass
157 changes: 157 additions & 0 deletions pliffy/figure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
from pathlib import Path

import matplotlib.pyplot as plt
import matplotlib

from pliffy import estimate, blocks

matplotlib.rcParams.update({"font.size": 9})


X_VALS = blocks.ABD(a=1, b=2, diff=2.8)


class Figure:
def __init__(self, pliffy_data, plot_info, estimates, ax_ab):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should it be ax_ab=None?

self.pliffy_data = pliffy_data
self.plot_info = plot_info
self.estimates = estimates
if ax_ab is None:
ax_ab = self._make_figure_axis()
self.ax_ab = ax_ab
self.jitter = 0.05 / max([len(self.pliffy_data.a), len(self.pliffy_data.b)])
self._plot_ab()

def _make_figure_axis(self):
width_height_in_inches = (8.2 / 2.54, 8.2 / 2.54)
_, ax = plt.subplots(figsize=width_height_in_inches, dpi=600)
return ax

def _create_diff_axis(self):
pass

def _plot_ab(self):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like you signaled what is "internal"

self._plot_raw_data()
self._plot_ab_means()
self._plot_ab_cis()
self._tweak_ab_xaxis()
self._tweak_ab_yaxis()

if self.plot_info.save:
plot_name = self.plot_info.plot_name + ".png"
fig_path = Path(self.plot_info.save_path) / plot_name
plt.savefig(fig_path)
plt.show()

def _plot_raw_data(self):
if (
self.pliffy_data.design == "paired"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

constant, also would expect and to be part of the () formatting?

) and self.plot_info.paired_data_joining_lines:
self._plot_paired_lines()
else:
self._plot_ab_raw_data()

def _plot_ab_means(self):
self.ax_ab.plot(
X_VALS.a,
self.estimates.a.mean,
marker=self.plot_info.summary_symbol.a,
color=self.plot_info.symbol_color.a,
markersize=self.plot_info.summary_symbol_size.a,
)
self.ax_ab.plot(
X_VALS.b,
self.estimates.b.mean,
marker=self.plot_info.summary_symbol.b,
color=self.plot_info.symbol_color.b,
markersize=self.plot_info.summary_symbol_size.b,
)

def _plot_ab_cis(self):
self.ax_ab.plot(
[X_VALS.a, X_VALS.a],
self.estimates.a.ci,
color=self.plot_info.symbol_color.a,
linewidth=self.plot_info.ci_line_width.a,
)
self.ax_ab.plot(
[X_VALS.b, X_VALS.b],
self.estimates.b.ci,
color=self.plot_info.symbol_color.b,
linewidth=self.plot_info.ci_line_width.b,
)

def _plot_paired_lines(self):
x_vals = [X_VALS.a, X_VALS.b]
for a, b in zip(self.pliffy_data.a, self.pliffy_data.b):
self.ax_ab.plot(
x_vals,
[a, b],
color=self.plot_info.paired_data_line_color,
linewidth=self.plot_info.paired_data_line_width,
alpha=self.plot_info.alpha,
)
x_vals[0] += self.jitter
x_vals[1] -= self.jitter

def _plot_ab_raw_data(self):
x_val_a = X_VALS.a + 0.1
x_val_b = X_VALS.b - 0.1
for a, b in zip(self.pliffy_data.a, self.pliffy_data.b):
self.ax_ab.plot(
x_val_a,
a,
color=self.plot_info.symbol_color.a,
marker=self.plot_info.summary_symbol.a,
markeredgewidth=0,
markersize=self.plot_info.raw_data_symbol_size.a,
alpha=self.plot_info.alpha,
)
self.ax_ab.plot(
x_val_b,
b,
color=self.plot_info.symbol_color.b,
marker=self.plot_info.summary_symbol.b,
markeredgewidth=0,
markersize=self.plot_info.raw_data_symbol_size.b,
alpha=self.plot_info.alpha,
)
x_val_a += self.jitter
x_val_b -= self.jitter

def _tweak_ab_xaxis(self):
self.ax_ab.spines["top"].set_visible(False)
self.ax_ab.set_xlim((0.8, 3))
self.ax_ab.set_xticks([X_VALS.a, X_VALS.b, X_VALS.diff])
self.ax_ab.set_xticklabels(
[
self.plot_info.x_tick_labels.a,
self.plot_info.x_tick_labels.b,
self.plot_info.x_tick_labels.diff,
]
)

def _tweak_ab_yaxis(self):
self.ax_ab.spines["right"].set_visible(False)
self.ax_ab.set_ylabel(self.plot_info.measure_units)
ab_yticks = self.ax_ab.get_yticks()
self.ab_ytick_step = ab_yticks[1] - ab_yticks[0]
min_past_lowest_ytick = ab_yticks[0] > min(
min(self.pliffy_data.a), min(self.pliffy_data.b)
)
max_past_highest_ytick = ab_yticks[-1] < max(
max(self.pliffy_data.a), max(self.pliffy_data.b)
)
if min_past_lowest_ytick and max_past_highest_ytick:
y_ticks_adjusted = (
[ab_yticks[0] - self.ab_ytick_step]
+ list(ab_yticks)
+ [ab_yticks[-1] + self.ab_ytick_step]
)
if min_past_lowest_ytick and not max_past_highest_ytick:
y_ticks_adjusted = [ab_yticks[0] - self.ab_ytick_step] + list(ab_yticks)
if not min_past_lowest_ytick and max_past_highest_ytick:
y_ticks_adjusted = list(ab_yticks) + [ab_yticks[-1] + self.ab_ytick_step]
if not min_past_lowest_ytick and not max_past_highest_ytick:
y_ticks_adjusted = list(ab_yticks)
self.ax_ab.set_yticks(y_ticks_adjusted)
49 changes: 7 additions & 42 deletions pliffy/plot.py
Original file line number Diff line number Diff line change
@@ -1,50 +1,15 @@
from typing import NamedTuple, Tuple, Union, Literal

from pliffy import estimate

from pliffy import blocks, estimate, figure

class _ABD(NamedTuple):
"""Helper namedtuple used by PlotInfo"""
a: Union[str, int] = None
b: Union[str, int] = None
diff: Union[str, int] = None


class PlotInfo(NamedTuple):
"""Information used to generate plot

Includes sensible defaults to reduce need for user input
"""
colors: _ABD = _ABD(a="black", b="black", diff="black")
symbol_size_summary: _ABD = _ABD(a=3, b=3, diff=3)
symbol_size_subject: _ABD = _ABD(a=1, b=1, diff=1)
symbols: _ABD = _ABD(a="o", b="o", diff="^")
x_values: _ABD = _ABD(a=1, b=2, diff=3)
horiz_line_to_diffs: bool = False
join_ab_means: bool = True
ax1_y_range: Tuple = None
ax2_y_range: Tuple = None
ax1_y_ticks: Tuple = None
ax2_y_ticks: Tuple = None
ab_sub_label: str = None
bottom_box: bool = False
alpha: float = 0.7


class PliffyData(NamedTuple):
"""Data and details required from user

See :function:`pliffy.estimates.calc` parameters for details.
def plot(pliffy_data: blocks.PliffyData, plot_info: blocks.PlotInfo = blocks.PlotInfo(), ax=None):
"""Main user interface to generate plot
"""
a: list = None
b: list = None
design: Literal["paired", "unpaired"] = "unpaired"
measure_units: str = "au"
ci_percentage: int = 95
estimates_a, estimates_b, estimates_diff = estimate.calc(pliffy_data)
estimates = blocks.ABD(a=estimates_a, b=estimates_b, diff=estimates_diff)
#TODO: print to screen and save to file all estimates
figure.Figure(pliffy_data, plot_info, estimates, ax)


def plot(pliffy_data: PliffyData, plot_info: PlotInfo = PlotInfo()):
"""Main user interfact to generate plot
"""
estimates_diff, diff_vals = estimate.calc(pliffy_data)

Loading