def plot_union_of_times(top_n, exclusive, avg):
    function_names = set([])
    parameter = get_parameter_name(exclusive, avg)
    description = get_description(exclusive, avg)

    for name in Path("warpx_outputs/").rglob("*.json"):
        print("adding function name:", name)

        gf = get_graphframe(name)

        top = gf.dataframe.sort_values(by=parameter, ascending=False)[:top_n]
        for function in top["name"]:
            function_names.add(function)

    if len(function_names) > 20:
        print(
            f"WARNING: {len(function_names)} are set to be plotted, this will "
            "cause some distinct functions or regions to have the same color!")

    colors = []
    # For this data I think tab20 was the best color choice
    color = cm.tab20(np.linspace(0, 1, len(function_names)))
    for i, c in zip(range(len(function_names)), color):
        colors.append(c)

    plot_selection_of_times(
        function_names,
        exclusive,
        avg,
        title=f"Top {top_n} {description} times across regions",
        filename=f"top_{top_n}_{description.replace(' ', '_')}_times",
        colors=colors)
Ejemplo n.º 2
0
def plot_N_clusters(N, X, feats_i, feats_o, hit_clusters, filename):
    
    X = np.array(X)
    X[:, 1] *= np.sign(X[:, 2])
    colors = cm.tab20(np.linspace(0, 1, N))
    for i in range(len(X)):
        if (hit_clusters[i] == 0):
            plt.scatter(X[i][3], X[i][1], c=colors[0], alpha=0.2,
                        linewidths=0, marker = 's', s=8)
        elif (hit_clusters[i] < N):
            
            plt.scatter(X[i][3], X[i][1], c=colors[int(hit_clusters[i])],
                        linewidths=0, marker='s', s=30)

    plt.ylabel("R [m]")
    plt.xlabel("z [m]")
    plt.savefig(filename, dpi=1200)
    plt.show()
    plt.clf()
Ejemplo n.º 3
0
def testUnitDiskGraph(seed=0):

    makeCanvas(size=[8, 8])
    un = 1
    G = unitDiskGraph(40, .5, un, seed=seed, NodeSize=.15)
    G.drawLines()
    G.drawNodes()

    ax = plt.gca()
    for i in G.pos:
        circ = plt.Circle(i,
                          radius=un / 2,
                          fc='#00000000',
                          ec='lightgray',
                          zorder=0)
        ax.add_patch(circ)
    plt.title("Unit Disk Graph as Circle Intersections")

    makeCanvas(size=[8, 8])
    un = 1
    G = unitDiskGraph(40, .5, un, seed=seed, NodeSize=.15)

    for i in range(G.size):
        for j in range(i):
            if G.Mat[j, i] == 1 and G.Mat[i, j] == 1:
                G.Mat[j, i] = random.choice([0, 0, 1])

    G.drawArrows(hwd=.05, hln=.05)

    S = stronglyConnected(G)

    ctr = 0
    C = cm.tab20([i for i in range(20)])
    for i in S:
        for j in i:
            G.colors[j] = C[ctr % 20]
            G.texts[j] = ctr
        ctr += 1
    G.drawNodes()
    G.drawText()
    plt.title(
        "Strongly Connected Components\n(After Randomizing Directionality)")
#%%
with open(write_path + "/multi_chain_50_len20000_acc", "rb") as file:
    acc_probs = pkl.load(file)

res_all = az.from_netcdf(write_path + "/multi_chain_50_len20000_all")

#%%
coords = {"cell_type": "k__Bacteria;p__Proteobacteria"}
az.plot_trace(res_all, var_names="beta", coords=coords)
plt.show()

#%%
sns.set(style="ticks", font_scale=1)

n_chains = 50
col = [cm.tab20(i % 20) for i in range(n_chains)]

g = sns.FacetGrid(data=acc_probs.loc[acc_probs["Cell Type"].isin([
    "k__Bacteria;p__Fusobacteria", "k__Bacteria;p__Firmicutes",
    "k__Bacteria;p__Tenericutes"
])],
                  col="Cell Type",
                  col_wrap=3)
g.map(sns.kdeplot, "Inclusion probability")
rug = g.map(sns.rugplot, "Inclusion probability", height=0.3, color="black")
for ax in g.axes:
    ax.axvline(0.81, color="red", linewidth=0.5)

# There is no labels, need to define the labels
legend_labels = [i + 1 for i in range(n_chains)]
Ejemplo n.º 5
0
from cycler import cycler
import numpy as np
import pandas as pd
import matplotlib.colors as colors
import matplotlib.pyplot as plt
from laboratory import config, processing, modelling
from laboratory.processing import Sample
from matplotlib.offsetbox import AnchoredText
import matplotlib.dates as mdates
from matplotlib.pyplot import cm
from impedance import preprocessing as pp
from datetime import datetime as dt
from impedance.models.circuits import fitting
plt.style.use('ggplot')
plt.ion()
color_cycle = cycler(color=cm.tab20(np.linspace(0, 1, 20)))

K_OHM = r'k\Omega'
degC = r'$^\degree$C'
CONDUCTIVITY = r'$Conductivity~[S/m]$'
THERMOPOWER = r'$Thermopower~[\mu V/K]$'
TEMP_C = r'$Temperature~[\degree C]$'
TEMP_K = r'$Temperature~[\degree K]$'
FUGACITY = r'$fo2p~[log Pa]$'
RESISTIVITY = r'$Resistivity [\omega m^-1]$'


def plot(func):
    @wraps(func)
    def wrapper(data, *args, **kwargs):
        if isinstance(data, Sample):
Ejemplo n.º 6
0
import scipy.io
import matplotlib.pyplot as plt
from sklearn.decomposition import KernelPCA
from scipy.cluster.hierarchy import linkage, dendrogram, fcluster
import scipy.spatial.distance as ssd
import matplotlib as mpl
from matplotlib.pyplot import cm
from scipy.cluster import hierarchy
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import v_measure_score

# Custom imports
from modules import RC_model

# Set the colormap for the histogram plot
cmap = cm.tab20(np.linspace(0, 1, 12))
hierarchy.set_link_color_palette([mpl.colors.rgb2hex(rgb[:3]) for rgb in cmap])

# Fix the random seed for reproducibility
np.random.seed(0)

# ============ RC model configuration and hyperparameter values ============
config = {}

# Reservoir
config['n_internal_units'] = 450  # size of the reservoir
config['spectral_radius'] = 0.59  # largest eigenvalue of the reservoir
config[
    'leak'] = 0.6  # amount of leakage in the reservoir state update (None or 1.0 --> no leakage)
config[
    'connectivity'] = 0.25  # percentage of nonzero connections in the reservoir
Ejemplo n.º 7
0
    tod_sb = my_file['spectrometer/band_average'][:, :, ncut:ncut + nuse] / 1e6
    pixels = np.array(my_file['spectrometer/feeds'][:]) - 1
    t = my_file['spectrometer/MJD'][ncut:ncut + nuse]
    t = (t - t[0]) * 24 * 60  # minutes
n_det = 20
n_sb = 4
n_samp = len(tod_sb[0, 0])
tod = np.zeros((n_det, n_sb, n_samp))
tod[pixels] = tod_sb
tod[19] *= np.nan
tod[3] *= np.nan
tod[6] *= np.nan

plt.figure(figsize=(5, 4))
# color=cm.rainbow(np.linspace(0,1,n_det))
color = iter(cm.tab20(np.linspace(0, 1, n_det)))
for i in range(n_det - 1):
    c = next(color)
    plt.plot(t, tod[i, :].mean(0), c=c, label='feed %02i' % (i + 1))
    # for j in range(n_sb):
    #     if j == 0:
    #         plt.plot(t, tod[i, j], c=c, label='feed %02i' % (i+1))
    #     else:
    #         plt.plot(t, tod[i, j], c=c)
plt.xlim(t[0], t[-1])
plt.xlabel('time [m]')
plt.ylabel(r'power [MW Hz${}^{-1}$]')
plt.legend(bbox_to_anchor=(1.01, 1.01), fontsize=8)
plt.savefig('all_feed_plot_good.pdf', bbox_inches='tight')
# plt.show()
Ejemplo n.º 8
0
first_order_err_bilin = np.array(first_order_err_bilin)
second_order_err = np.array(second_order_err)
second_order_err_bilin = np.array(second_order_err_bilin)

print("Mean PSNR: %.03f" % psnrs.mean())
print("Mean SSIM: %.03f" % ssims.mean())
print("Mean bilinear PSNR: %.03f" % psnrs_bilin.mean())
print("Mean bilinear SSIM: %.03f" % ssims_bilin.mean())

create_graph(np.arange(len(psnrs)), [psnrs, psnrs_bilin],
             "PSNR per frame on 17 channel CM1 data", "PSNR", "frame",
             ['blue', 'red'], ['Network', 'Bilinear'])

create_graph(np.arange(len(psnrs)), psnr_diff_per_channel,
             "PSNR difference (network - bilinear) per channel", "PSNR",
             "frame", cm.tab20(np.linspace(0, 1, len(psnr_diff_per_channel))),
             [str(i) for i in range(len(psnr_diff_per_channel))])

create_graph(np.arange(len(psnrs)), [ssims, ssims_bilin],
             "SSIM per frame on 17 channel CM1 data", "SSIM", "frame",
             ['blue', 'red'], ['Network', 'Bilinear'])

create_graph(np.arange(len(psnrs)), [first_order_err, first_order_err_bilin],
             "First order gradient error per frame on 17 channel CM1 data",
             "First order gradient error", "frame", ['blue', 'red'],
             ['Network', 'Bilinear'])

create_graph(np.arange(len(psnrs)), [second_order_err, second_order_err_bilin],
             "Second order error per frame on 17 channel CM1 data",
             "Second order error", "frame", ['blue', 'red'],
             ['Network', 'Bilinear'])
Ejemplo n.º 9
0
                                                lmax=lmax,
                                                start_at_zero=False)

my_spectra = ["TT", "TE", "EE"]
count = 0
for s1, spec in enumerate(my_spectra):
    plt.figure(figsize=(12, 6))

    if spec == "TE":
        cross_freq_list = [
            "%sx%s" % (f0, f1) for f0, f1 in product(freq_list, freq_list)
        ]
    else:
        cross_freq_list = ["%sx%s" % (f0, f1) for f0, f1 in cwr(freq_list, 2)]

    color = iter(cm.tab20(np.linspace(0, 1, 10)))

    for cross_freq in cross_freq_list:
        ps = Dlth[spec].copy()

        if spec == "TT":
            plt.semilogy()
            f0, f1 = cross_freq.split("x")
            _, flth = np.loadtxt("%s/fg_%sx%s_TT.dat" % (bestfit_dir, f0, f1),
                                 unpack=True)
            ps += flth[:lmax]

        Db = proj_data_vec_mean[count * n_bins:(count + 1) * n_bins]
        sigmab = np.sqrt(proj_cov_mat.diagonal()[count * n_bins:(count + 1) *
                                                 n_bins])