Example #1
0
    def histograms(self, start_time, stop_time, depth, overlapping=True):

        L = stop_time.year - start_time.year + 1
        modslopes, noiseterm = self.sn_at_time(start_time,
                                               L,
                                               depth,
                                               overlapping=overlapping)
        ns = np.std(noiseterm)

        plt.hist(modslopes / ns,
                 20,
                 normed=True,
                 color=cm.Oranges(.8),
                 alpha=.5)
        lab = str(start_time.year) + "-" + str(stop_time.year)
        da.fit_normals_to_data(modslopes / ns,
                               color=cm.Oranges(.9),
                               lw=3,
                               label=lab + " Model projections")

        plt.hist(noiseterm / ns,
                 20,
                 normed=True,
                 color=cm.Purples(.8),
                 alpha=.5)
        da.fit_normals_to_data(noiseterm / ns,
                               color=cm.Purples(.9),
                               lw=3,
                               label="Noise")
        plt.xlabel("S/N")
        plt.ylabel("Normalized Frequency")
Example #2
0
def clustering_plot(X_clustered, cluster_labels, nclusters, title=None\
, X_center=None):
    z = plt.figure(figsize=(10, 10))

    if len(cluster_labels) > 0:
        if X_center is not None:
            alpha = 0.3
        else:
            alpha = 0.6

        print("clustering_plot()" + str(X_clustered.shape))
        print("clustering_plot()" + str(X_clustered[0, 0]))

        for i in range(X_clustered.shape[0]):
            plt.scatter(X_clustered[i, 0], X_clustered[i, 1],\
            c=cm.Oranges(cluster_labels[i] / nclusters), alpha=alpha)

        if X_center is not None:
            for i in range(X_center.shape[0]):
                plt.scatter(X_center[i, 0],
                            X_center[i, 1],
                            marker="o",
                            s=400,
                            c='red')
                plt.annotate(str(i), (X_center[i, 0], X_center[i, 1]))
    else:
        for i in range(X_clustered.shape[0]):
            plt.scatter(X_clustered[i, 0], X_clustered[i, 1], c='b')
    plt.xticks([])
    plt.yticks([])
    if title is not None:
        plt.title(title, size=17, color='b')
def c_d_Matrix():
    step = 10  #step with which the gammas vary until 1
    n = int(L / step)  #number of transition rates to test for
    stability = np.zeros((n, n, L + 1))
    axis = np.zeros((n, 2))
    for inc in range(1, n):
        Set("param.txt", "c", str(inc * step))
        for dec in range(inc):
            Set("param.txt", "d", str(dec * step))
            stability[inc, dec] = gau.Dummy()
            print('c=', inc * step, 'd=', dec * step, 'a=',
                  stability[inc, dec, int(L / 2)])

    x = y = np.arange(0, L, step)
    # here are the x,y and respective z values
    X, Y = np.meshgrid(x, y)
    Z = np.array(np.amin(stability, axis=-1))
    # this is the value to use for the color
    V = np.amax(stability, axis=-1)

    plt.xlabel('gamma_R')

    # create the figure, add a 3d axis, set the viewing angle
    fig = plt.figure()
    ax = plt.axes(projection='3d')
    ax.view_init(45, 60)

    # here we create the surface plot, but pass V through a colormap
    # to create a different color for each patch
    ax.plot_surface(X, Y, Z, facecolors=cm.Oranges(V))

    plt.show()
    return (stability)
Example #4
0
def da_colors(typ):
    d = {}
    d["h85"] = cm.Oranges(.8)  #cm.Dark2(0.)
    d["piC"] = cm.Greens(.7)  #cm.Dark2(.2)
    d["gpcp"] = cm.Purples(.5)  #cm.Dark2(.4)
    d["cmap"] = cm.Reds(.8)
    d["precl"] = cm.Purples(.9)
    return d[typ]
Example #5
0
    def obs_SN(self, start_time, stop_time, depth, overlapping=True):
        self.project_soilmoisture("MERRA2")
        self.project_soilmoisture("GLEAM")
        L = stop_time.year - start_time.year + 1
        modslopes, noiseterm = self.sn_at_time(start_time,
                                               L,
                                               depth,
                                               overlapping=overlapping)
        ns = np.std(noiseterm)

        plt.hist(modslopes / ns,
                 20,
                 normed=True,
                 color=cm.Oranges(.8),
                 alpha=.5)
        lab = str(start_time.year) + "-" + str(stop_time.year)
        da.fit_normals_to_data(modslopes / ns,
                               color=cm.Oranges(.9),
                               lw=3,
                               label=lab +
                               " trends in H85 projections onto fingerprint")

        plt.hist(noiseterm / ns,
                 20,
                 normed=True,
                 color=cm.Purples(.8),
                 alpha=.5)
        da.fit_normals_to_data(
            noiseterm / ns,
            color=cm.Purples(.9),
            lw=3,
            label=str(L) +
            "-year trends in piControl projection onto fingerprint")
        plt.xlabel("S/N")
        plt.ylabel("Normalized Frequency")

        merra = self.OBS_PROJECTIONS["MERRA2"][depth](time=(start_time,
                                                            stop_time))
        gleam = self.OBS_PROJECTIONS["GLEAM"][depth](time=(start_time,
                                                           stop_time))
        merrasig = cmip5.get_linear_trends(merra) / ns
        plt.axvline(merrasig, label="MERRA2", c="b", lw=3)
        gleamsig = cmip5.get_linear_trends(gleam) / ns
        plt.axvline(gleamsig, label="GLEAM", c="r", lw=3)
        plt.legend()
Example #6
0
def plot_compare_phi_psi(neurons, epsilon_values, tau_y_values, psi_values):

    '''This only works for summary type saves.'''

    fig, axs = plt.subplots(1, len(psi_values), sharey=True, figsize=(5*len(psi_values)+2, 5))
    cm_section = np.linspace(0.3, 1, len(tau_y_values))
    colours = []
    colours.append([ cm.Blues(x) for x in cm_section ])
    colours.append([ cm.Oranges(x) for x in cm_section ])
    colours.append([ cm.Purples(x) for x in cm_section ])
    colours.append([ cm.Greens(x) for x in cm_section ])


    for j, epsilon in enumerate(epsilon_values):

        for k, tau_y in enumerate(tau_y_values):

            label = "$\\tau_y={}$, $\epsilon={}$".format(tau_y,epsilon)

            E = []
            phi_values = []

            for i in range(len(psi_values)):
                E.append([])
                phi_values.append([])

            for neuron in neurons:
                
                if neuron.hyper['psi'] in psi_values:

                    phi_values[psi_values.index(neuron.hyper['psi'])].append(neuron.hyper['phi'])

                    for log in neuron.logs:
                        
                        if log[0]['tau_y'] == tau_y and log[0]['epsilon'] == epsilon:
                    
                            E[psi_values.index(neuron.hyper['psi'])].append(log[2]-log[3])

            for i in range(len(psi_values)):
                
                if i == 0:
                    axs[i].plot(phi_values[i], E[i], label=label, color=colours[j][k])
                    axs[i].set_ylabel('$E$')
                else:
                    axs[i].plot(phi_values[i], E[i], color=colours[j][k])
                axs[i].set_title('$\psi={}$'.format(psi_values[i]))
                axs[i].set_xlabel('$\phi$')

            
    fig.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    # fig.legend(loc='upper center', bbox_to_anchor=(0.5, -0.02), fancybox=True, shadow=True, ncol=6)

    fig.tight_layout()
    plt.show()

    return fig
Example #7
0
def plt_2_trajectories(data,
                       labels,
                       xyt,
                       savepath,
                       usemeans=True,
                       mid=0,
                       plttype='scatter',
                       **kwargs):
    plt.figure(figsize=(30, 10))
    vals = {}
    assert len(data) == len(labels)
    ylims = kwargs.pop('ylims', (0, 1))
    if usemeans:
        means = [np.mean(line) for line in data]
    else:
        means = [mid] * len(data)
    vals['up'] = [
        np.array([x for x in line if x >= means[i]])
        for i, line in enumerate(data)
    ]
    vals['down'] = [
        np.array([x for x in line if x < means[i]])
        for i, line in enumerate(data)
    ]
    cols = {'up': 'green', 'down': 'red'}
    plt.plot(range(len(labels)), means, lw=4, c=cm.Oranges(0.8))
    plt.axhline(y=mid, c=cm.Greys(0.8), alpha=0.7)
    for x in range(0, len(means), 12):
        plt.axvline(x=x, c=cm.Greys(0.8), alpha=0.7, lw=1.5)
    if 'scatter' in plttype:
        for k, v in vals.items():
            ys = [y for line in v for y in line]
            xs = [xval for xval, line in enumerate(v) for y in line]
            plt.scatter(xs, ys, alpha=0.25, c=cols[k], label=k)
    if 'mean' in plttype:
        for k, v in vals.items():
            ys = [np.mean(line) for line in v]
            xs = range(len(v))
            plt.plot(xs, ys, alpha=0.8, lw=2, c=cols[k], label=k)
    if 'box' in plttype:
        for k, v in vals.items():
            plt.boxplot(v, positions=range(len(data)), boxprops={'c': cols[k]})
    plt.legend()
    plt.xlabel(xyt[0], fontsize=20)
    plt.xticks(ticks=range(len(v)),
               labels=labels,
               rotation=45,
               fontsize=10,
               ha='center')
    plt.ylabel(xyt[1], fontsize=20)
    plt.title(xyt[2], fontsize=24)
    plt.ylim(*ylims)
    plt.savefig(savepath + '.png', bbox_inches='tight')
    plt.close('all')
Example #8
0
def colorregions(region):
    """Set the colors to ensure a uniform scheme for each region """
    d={}
    d["ALL"]="k"
    d["NHDA"]=cm.gray(.5)
    d["NADA"]=cm.Purples(.5)
    d["OWDA"]=cm.Blues(.5)
    d["MXDA"]=cm.PiYG(.1)
    d["ANZDA"]=cm.PiYG(.8)
    d["MADA"]=cm.Oranges(.5)
    d["GDA"]="k"
    return d[region]
def get_colors(color_c=3, color_step=100):
    cmap_colors = np.vstack((
        cm.Oranges(np.linspace(0.4, 1, color_step)),
        cm.Reds(np.linspace(0.4, 1, color_step)),
        cm.Greys(np.linspace(0.4, 1, color_step)),
        cm.Purples(np.linspace(0.4, 1, color_step)),
        cm.Blues(np.linspace(0.4, 1, color_step)),
        cm.Greens(np.linspace(0.4, 1, color_step)),
        cm.pink(np.linspace(0.4, 1, color_step)),
        cm.copper(np.linspace(0.4, 1, color_step)),
    ))
    return cmap_colors[np.arange(color_c * color_step) % (color_step * 8)]
Example #10
0
    def obs_SN(self,start_time,stop_time=None,overlapping=True,include_dai=False):
        if stop_time is None:
            stop_time=cmip5.stop_time(self.projection)
        target_obs = self.projection(time=(start_time,stop_time))
        L=len(target_obs)
        modslopes,noiseterm = self.sn_at_time(start_time,L,overlapping=True)
        ns=np.std(noiseterm)
        signal = float(cmip5.get_linear_trends(target_obs))/ns
        plt.hist(modslopes/ns,20,normed=True,color=cm.Oranges(.8),alpha=.5)
        lab = str(start_time.year)+"-"+str(stop_time.year)
        da.fit_normals_to_data(modslopes/ns,color=cm.Oranges(.9),label=lab+" Model projections")

        plt.hist(noiseterm/ns,20,normed=True,color=cm.Greens(.8),alpha=.5)
        da.fit_normals_to_data(noiseterm/ns,color=cm.Greens(.9),label="Pre-1850 tree-ring reconstructions")
        plt.axvline(signal,color=cm.Blues(.8),lw=3,label=lab+" Tree-ring reconstructions")
        print signal
        if include_dai:
            dai_proj = self.project_dai_on_solver(start=start_time)
            daitrend = cmip5.get_linear_trends(dai_proj(time=(start_time,stop_time)))
            
            
            
        plt.legend(loc=0)
Example #11
0
    def plot_sct(self, drop_point, wind_speed_array, launcher_elev_angle,
                 fall_type):
        # -------------------
        # plot landing distribution
        # hardcoded for noshiro
        #
        # INPUT:
        #        drop_point: (n_speed * n_angle * 2(xy) ndarry): landing point coordinate
        #        wind_speed_array: array of wind speeds
        #        lancher_elev_angle: elevation angle [deg]
        #        fall_type = 'Parachute' or 'Ballistic'
        #
        # -------------------

        # plot map
        self.plot_map()

        # file existence check
        #file_exist = os.path.exists("./output")

        #if file_exist == False:
        #    os.mkdir("./output")

        title_name = fall_type + ", Launcher elev. " + str(
            int(launcher_elev_angle)) + " deg"

        imax = len(wind_speed_array)
        for i in range(imax):

            # cmap = plt.get_cmap("winter")

            labelname = str(wind_speed_array[i]) + " m/s"
            plt.plot(drop_point[i, :, 0],
                     drop_point[i, :, 1],
                     label=labelname,
                     linewidth=2,
                     color=cm.Oranges(i / imax))

        # output_name = "output/Figure_elev_" + str(int(rail_elev)) + ".png"
        output_name = 'results/Figure_' + fall_type + '_elev' + str(
            int(launcher_elev_angle)) + 'deg.eps'

        plt.title(title_name)
        plt.legend()
        plt.savefig(output_name, bbox_inches='tight')
        plt.show()
Example #12
0
def _prediction_1D(axe,
                   xlim,
                   varname,
                   xlabels,
                   Xmean,
                   Xweight,
                   xtitle,
                   StdMean=None,
                   Xref=None,
                   StdRef=None,
                   modal_label=None):
    if xlim is not None:
        axe.set_ylim(*xlim)
        axe.yaxis.set_major_locator(
            ticker.MultipleLocator((xlim[1] - xlim[0]) / 10))

    axe.set_xlabel(xtitle, fontsize=15)
    axe.set_ylabel(varname, fontsize=20)

    if Xmean is not None:
        axe.plot(xlabels, Xmean, color="indigo", marker="*", label="Mean")

    if StdMean is not None:
        axe.fill_between(xlabels,
                         Xmean - StdMean,
                         Xmean + StdMean,
                         alpha=0.3,
                         color="indigo",
                         label="Std on mean",
                         hatch="/")

    if Xweight is not None:
        colors = cm.Oranges(np.linspace(0.4, 0.9, Xweight.shape[1]))
        for i, X in enumerate(Xweight.T):
            label = (modal_label or "Weight prediction {}").format(i)
            axe.plot(xlabels, X, marker="+", label=label, color=colors[i])

    if Xref is not None:
        axe.plot(xlabels, Xref, color="g", marker=".", label="Reference")
    if StdRef is not None:
        axe.fill_between(xlabels,
                         Xref + StdRef,
                         Xref - StdRef,
                         alpha=0.3,
                         color="g",
                         label="Std on reference")
Example #13
0
def create_colormap_2colors(proportion_colors1):

    number_colors1 = math.floor(proportion_colors1 * 256)
    number_colors2 = 256 - number_colors1

    # sample the colormaps that you want to use. Use 128 from each so we get 256
    # colors in total
    colors1 = cmx.Blues(np.linspace(0, 1, number_colors1))
    oranges = cmx.Oranges(np.linspace(0, 1, number_colors2))
    orange = oranges[math.ceil(number_colors2*0.65),:]
    colors2 = np.zeros( (number_colors2,4), dtype=np.float64)
    colors2[:number_colors2] = orange

    # combine them and build a new colormap
    colors = np.vstack((colors1, colors2))

    mymap = mcolors.LinearSegmentedColormap.from_list('my_colormap', colors)

    return mymap
Example #14
0
    def __init__(self,data_pred,data_gt,colors,img,types,gif_name = "test.gif", plot_ = False, save = True):

        self.img = img
        self.xs_pred = data_pred[:,:,0]
        self.ys_pred = data_pred[:,:,1]

        self.xs_gt = data_gt[:,:,0]
        self.ys_gt = data_gt[:,:,1]

        self.types = types 


        self.nb_agents = self.xs_pred.shape[0]
        self.margin = 1

        self.nb_frames = self.xs_pred.shape[1]
        self.gif_name = gif_name
        self.plot_ = plot_
        self.save = save

        self.fps = 1
        self.colors = colors

        self.lin_size = 100

        lin = np.linspace(0.6, 0.8, self.lin_size)
 
        self.color_dict = {
            "bicycle":cm.Blues(lin),
            "pedestrian":cm.Reds(lin),
            "car":cm.Greens(lin),
            "skate":cm.Greys(lin),
            "cart":cm.Purples(lin),
            "bus":cm.Oranges(lin)
        }

        self.colors = [self.color_dict[type_][np.random.randint(self.lin_size)] for type_ in self.types]

        self.history = 4

        self.get_plots()
Example #15
0
def _axe_density_1D(axe, x, y, xlims, varname, modal_preds, truex, title):
    # axe.xaxis.set_minor_locator(ticker.MultipleLocator((xlims[1] - xlims[0]) / 100))
    # axe.xaxis.set_major_locator(ticker.MultipleLocator((xlims[1] - xlims[0]) / 20))
    axe.plot(x, y, "-", linewidth=1)
    axe.set_xlim(*xlims)
    axe.set_xlabel(varname)
    axe.set_title(title)

    colors = cm.Oranges(np.linspace(0.4, 0.9, len(modal_preds)))
    for i, (X, height, weight) in enumerate(modal_preds):
        axe.axvline(
            x=X,
            color=colors[i],
            linestyle="--",
            label="$x_{{est}}^{{( {2} )}}$, $w_{{  {2} }} = {1:.3f}$".format(
                height, weight, i),
            alpha=0.5)

    if truex:
        axe.axvline(x=truex, label="True value", color="black", alpha=0.5)
    axe.legend()
Example #16
0
def plot_wz_align(neuron):

    sigma_s, epsilon, sigma_y, tau_y = env_extract(neuron)

    cm_section = np.linspace(0.3, 1, neuron.S)
    colors = [ cm.Oranges(x) for x in cm_section ]

    fig, axs = plt.subplots(len(tau_y), len(epsilon), squeeze=True, figsize=(4*len(epsilon),3*len(tau_y)), sharey=True)

    for log in neuron.logs:
        i = tau_y.index(log.env_parameters['tau_y'])
        j = epsilon.index(log.env_parameters['epsilon'])
        x_low = 0
        x_up = log.timeline[-1]+1
        for k in np.arange(0, neuron.S, 1):
            axs[i, j].plot(
                log.timeline, 
                (log.W[:, [k], :] @ log.z / (np.sqrt(log.W[:, [k], :] @ np.transpose(log.W[:, [k], :], (0,2,1))) * np.sqrt(np.transpose(log.z, (0,2,1)) @ log.z))).squeeze(), 
                # (neuron.po.T[None, :, :] @ log.W @ log.z / (np.sqrt(neuron.po.T[None, :, :] @ log.W @ np.transpose(neuron.po.T[None, :, :] @ log.W, (0,2,1))) * np.sqrt(np.transpose(log.z, (0,2,1)) @ log.z))).squeeze(),
                color = colors[k],
                label = '$\mathbf{{w}}_{{{k}}}$'.format(k=k+1)
            )
            axs[i, j].set_xlabel('$t$', fontsize=14)
            axs[i, j].set_title('$\\tau_y = {}$, $\epsilon = {}$'.format(tau_y[i], epsilon[j]))
        
        tag_R_E(axs[i, j], log, x_low, x_up)
        
        axs[i, j].set_xlim(x_low, x_up)
        if j == 0:
            axs[i, j].set_ylabel('$\cos(\\theta_{{\mathbf{{z}},\mathbf{{w}}_{{a}}}})$', fontsize=14)
            if i == 0:
                axs[i, j].legend(loc="upper left")

    fig.tight_layout()
    plt.show()

    return fig
Example #17
0
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
data=pd.read_csv("data",sep="\s+",header=None)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = data[0]
y = data[1]
z = data[2]
c = data[3]
ax.view_init(45,60)
img = ax.scatter(x, y, z, c=c, cmap=plt.hot())
fig.colorbar(img)
fig.savefig("plot.png")

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x,y = np.meshgrid(data[0], data[1])
z = data[2]
c = data[3]

ax.view_init(45,60)

# here we create the surface plot, but pass V through a colormap
# to create a different color for each patch
ax.plot_surface(x, y, z, facecolors=cm.Oranges(c))
fig.savefig("plot2.png")
Example #18
0
import numpy as np
from numpy.random import binomial
from scipy.stats import multivariate_normal, norm
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import math
import os
import errno
import seaborn as sns
from matplotlib.colors import ListedColormap
from mpl_toolkits.mplot3d import Axes3D

blue_cmap = ListedColormap(cm.Blues(np.linspace(0, 1, 20))[10:, :-1])
oran_cmap = ListedColormap(cm.Oranges(np.linspace(0, 1, 20))[10:, :-1])
green_cmap = ListedColormap(cm.Greens(np.linspace(0, 1, 20))[10:, :-1])


def setup_plotting():
    """This function sets up Latex-like fonts, font sizes and other
    parameter to make plots look prettier."""
    sns.set_style('darkgrid')
    plt.rcParams['mathtext.fontset'] = 'stix'
    plt.rcParams['font.family'] = 'STIXGeneral'
    plt.rcParams['font.size'] = 14
    plt.rcParams['figure.figsize'] = (12, 6)
    plt.rc("savefig", dpi=300)
    plt.rc('figure', titlesize=16)


def mkdir_p(path):
    """Creates a directory in the specified path."""
def LinReg(training,
           teacher,
           train_len,
           test_len,
           delay,
           washout=8000,
           plot=0,
           save=0):

    #Y_input = narma_10_input[washout:train_len].ravel()
    Y_train = teacher[washout:train_len].ravel()
    Y_test = teacher[train_len:train_len + test_len].ravel()

    #X_input=input_signal[set_number][0][washout+delay:train_len+delay]
    X_train = training[washout + delay:train_len + delay]
    X_test = training[train_len + delay:train_len + test_len + delay]
    #X_nodes = nodes_list[set_number][washout+delay:train_len+delay]

    scaler = preprocessing.StandardScaler().fit(X_train)
    sX_train = scaler.transform(X_train)
    sX_test = scaler.transform(X_test)

    nscaler = preprocessing.MinMaxScaler(feature_range=(-1, 1)).fit(X_train)
    nX_train = nscaler.transform(X_train)
    nX_test = nscaler.transform(X_test)

    norm_training = preprocessing.normalize(training, axis=0, norm='max')
    norm_X_train = norm_training[washout + delay:train_len + delay]
    norm_X_test = norm_training[train_len + delay:train_len + test_len + delay]

    lm = linear_model.LinearRegression()
    lm.fit(X_train, Y_train)
    pred_train = lm.predict(X_train)
    pred_test = lm.predict(X_test)

    if plot == 1:
        colors = np.vstack(
            (cm.Blues(np.linspace(0.5, 1,
                                  5)), cm.Greens(np.linspace(0.5, 1, 5)),
             cm.Oranges(np.linspace(0.5, 1,
                                    5)), cm.Reds(np.linspace(0.5, 1, 5))))
        plt.figure()

        for row, c in zip(X_train[2000:12000].T, colors):
            plt.plot(range(2000, 12000), row, color=c, linewidth=2.5)

        plt.xlabel("time (ms)")
        plt.ylabel("spring lengths (m)")

        #plt.plot(Y_train[2000:12000])
        if save == 1:
            plt.savefig("spring_lengths.png")

        plt.figure()
        plt.plot(range(2000, 12000), pred_test[:10000], linewidth=3.0)
        plt.plot(range(2000, 12000), Y_test[:10000], 'r--', linewidth=2.5)
        plt.xlabel("time (ms)")
        plt.ylabel("y(t)/O(t)")

        plt.legend(['system output', 'target output'])
        if save == 1:
            plt.savefig("spring_output.png")

    slm = linear_model.LinearRegression()
    slm.fit(sX_train, Y_train)
    spred_train = slm.predict(sX_train)
    spred_test = slm.predict(sX_test)

    nlm = linear_model.LinearRegression()
    nlm.fit(nX_train, Y_train)
    npred_train = nlm.predict(nX_train)
    npred_test = nlm.predict(nX_test)

    norm_lm = linear_model.LinearRegression()
    norm_lm.fit(norm_X_train, Y_train)
    norm_pred_train = norm_lm.predict(norm_X_train)
    norm_pred_test = norm_lm.predict(norm_X_test)

    error = mean_squared_error(Y_test, pred_test)
    serror = mean_squared_error(Y_test, spred_test)
    nerror = mean_squared_error(Y_test, npred_test)
    norm_error = mean_squared_error(Y_test, norm_pred_test)
    #print(mean_squared_error(pred_test,Y_test))

    coefs = [lm.coef_, slm.coef_, nlm.coef_, norm_lm.coef_]
    errors = [error, serror, nerror, norm_error]
    return coefs, errors

def how_long_within(start, nb_max_iter):
    z0 = start
    z = z0
    for i in range(nb_max_iter):
        if abs(z) > 2:
            return i
        z = z * z + z0
    return nb_max_iter


MAX = 255
# COLORS = [(random.random(), random.random(), random.random()) for i in range(MAX+1)]
COLORS = [None] * 256
COLORS = [cm.Oranges(i)[0:3] for i in range(256)]


def mandelbrot_image_matrix(nb_pxls, start, radius):
    mtrx = np.zeros((nb_pxls, nb_pxls, 3))
    for i, row in enumerate(mtrx):
        for j, pxl in enumerate(row):
            x0 = start.real - (radius / 2) + (j * radius / nb_pxls)
            y0 = start.imag - (radius / 2) + (i * radius / nb_pxls)
            z0 = complex(x0, y0)
            # gray = (MAX - how_long_within(z0, MAX))/MAX
            # color = (gray, gray, gray)
            index = MAX - how_long_within(z0, MAX)
            color = COLORS[index]
            mtrx[i, j] = color
    return mtrx
detG2 = np.vectorize(_detG2)
#_detG=sy.lambdify([y1,y2,x11,x22],sy.det(G))
#detG=np.vectorize(_detG,excluded={0,1})
Xx1 = np.arange(-1, 1, 0.01)
Xx2 = np.arange(-1, 1, 0.01)
Yy = np.arange(-5, 5, 0.1)

mode = 1

if mode == 0:
    X1, X2, Y1 = np.meshgrid(Xx1, Xx2, Yy)
    fig = pl.figure()
    axes = fig.add_subplot(111, projection='3d')
    Z = detG2(Y1, X1, X2)
    axes.scatter(X1, X2, Y1, facecolors=cm.Oranges(Z))
    pl.plot()

    X1, X2 = np.meshgrid(Xx1, Xx2)
    fig, ax = pl.subplot(1)

if mode == 2:
    X1, X2 = np.meshgrid(Xx1, Xx2)
    fig, axes = pl.subplots(1, 1, sharex=True, sharey=True)
    fig.subplots_adjust(hspace=0, wspace=0)
    matplotlib.rcParams['contour.negative_linestyle'] = 'solid'

    Z = np.arctan(detG3(1, 1, np.tan(np.pi / 2 * X1), np.tan(
        np.pi / 2 * X2))) * 2 / np.pi
    CS = axes.pcolormesh(X1, X2, Z)
    CS2 = axes.contour(X1, X2, Z, colors='k')
    print(m)
    print("Accuracy: %s \n"%c)

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm

# create some fake data
x = data['visibility']
y = data['wind']
# here are the x,y and respective z values
X, Y = np.meshgrid(x, y)
Z = np.sinc(np.sqrt(X*X+Y*Y))
# this is the value to use for the color
V = np.sin(Y)

# create the figure, add a 3d axis, set the viewing angle
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.view_init(45,60)

# here we create the surface plot, but pass V through a colormap
# to create a different color for each patch
ax.plot_surface(X, Y, Z, facecolors=cm.Oranges(V))
ax.set_xlabel('visibility')
ax.set_ylabel('wind')
plt.title('Space Shuttle Auto-Landing Control')
plt.show()


Example #23
0
        del geojson['properties']['city']
        del geojson['properties']['fill']
        geojson['properties']['category_distrib'] = list(cat_distr)
        geojson['properties']['category_more'] = list(cat_distinct)
        geojson['properties']['time_distrib'] = list(timeofday_distr)
        geojson['properties']['time_more'] = list(timeofday_distinct)
        geojson['properties']['days_distrib'] = list(dayofweek_distr)
        geojson['properties']['days_more'] = list(dayofweek_distinct)
        geojson['properties']['weight'] = float(theta)
        neighborhoods.append(geojson)

    neighborhoods.sort(key=lambda x: x['properties']['weight'], reverse=True)
    a = pretty_floats({"type": "FeatureCollection", "features": neighborhoods})

    cat_colors = [
        cmlib.Oranges(x) for x in np.linspace(0, 1, len(main_cats_plot))
    ]
    time_colors = [cmlib.Greens(x) for x in np.linspace(0, 1, len(timeOfDay))]
    day_colors = [cmlib.Purples(x) for x in np.linspace(0, 1, len(dayOfWeek))]

    # select top regions based on volume
    MAX_REGIONS = args.max_regions
    results = sorted(enumerate(a['features']),
                     key=lambda x: x[1]['properties']['weight'],
                     reverse=True)[:MAX_REGIONS]

    with zipfile.ZipFile(city + '.zip', 'w') as myzip:
        for region_id, res in results:
            stats = res['properties']

            fig, ax = plt.subplots(1, 4, figsize=(21, 6))
Example #24
0
def plot_ed_log(full_df, save=True):
    norm = mpl.colors.Normalize(vmin=0, vmax=3.75)
    #FULL EIGENPROPERTIES and EIGENVALUES

    av_df = pd.read_pickle('analysis/av_sorted_ed_log_og_d.pickle')
    #av_df = pd.read_pickle('analysis/av_ed_log_d.pickle')

    ## TO GET NICE FORMATTING
    g = sns.FacetGrid(av_df, col='model', col_wrap=3, hue='Sz')
    limits = [(0.5, 2.5), (2.5, 4.5), (1.5, 4.5), (0.5, 2.5), (1.5, 4.5),
              (0, 1.5), (-1.0, 1.5), (-1.5, 1.5), (-1.5, 1.5), (-1.5, 1.5),
              (-1, 1), (-0.5, 1.0)]
    for model in np.arange(32):
        for beta in [0.0, 1.0, 2.0]:
            rgba_color = cm.Blues(norm(3.75 - beta))
            rgba_color2 = cm.Oranges(norm(3.75 - beta))
            z = -1
            fig, axes = plt.subplots(nrows=2,
                                     ncols=6,
                                     sharey=True,
                                     figsize=(12, 6))
            for parm in [
                    'iao_n_3dz2', 'iao_n_3dpi', 'iao_n_3dd', 'iao_n_2pz',
                    'iao_n_2ppi', 'iao_n_4s', 'iao_t_pi', 'iao_t_ds',
                    'iao_t_dz', 'iao_t_sz', 'iao_Jsd', 'iao_Us'
            ]:
                z += 1
                ax = axes[z // 6, z % 6]

                p = parm
                if (parm == 'iao_Jsd'): p = 'Jsd'
                if (parm == 'iao_Us'): p = 'Us'

                full_df['energy'] -= min(full_df['energy'])
                full_df = full_df[full_df['basestate'] == -1]

                f_df = full_df[full_df['Sz'] == 0.5]
                x = f_df[p].values
                y = f_df['energy'].values
                yerr = f_df['energy_err'].values
                ax.errorbar(x, y, yerr, fmt='s', c=rgba_color, alpha=0.5)

                f_df = full_df[full_df['Sz'] == 1.5]
                x = f_df[p].values
                y = f_df['energy'].values
                yerr = f_df['energy_err'].values
                ax.errorbar(x, y, yerr, fmt='s', c=rgba_color2, alpha=0.5)

                sub_df = av_df[(av_df['model'] == model) & (av_df['Sz'] == 0.5)
                               & (av_df['beta'] == beta)]
                x = sub_df[parm].values
                xerr_u = sub_df[parm + '_u'].values
                xerr_d = sub_df[parm + '_l'].values
                y = sub_df['energy'].values
                yerr_u = sub_df['energy_u'].values
                yerr_d = sub_df['energy_l'].values
                ax.errorbar(x,
                            y,
                            xerr=[xerr_d, xerr_u],
                            yerr=[yerr_d, yerr_u],
                            markeredgecolor='k',
                            fmt='o',
                            c=rgba_color)

                sub_df = av_df[(av_df['model'] == model) & (av_df['Sz'] == 1.5)
                               & (av_df['beta'] == beta)]
                x = sub_df[parm].values
                xerr_u = sub_df[parm + '_u'].values
                xerr_d = sub_df[parm + '_l'].values
                y = sub_df['energy'].values
                yerr_u = sub_df['energy_u'].values
                yerr_d = sub_df['energy_l'].values
                ax.errorbar(x,
                            y,
                            xerr=[xerr_d, xerr_u],
                            yerr=[yerr_d, yerr_u],
                            markeredgecolor='k',
                            fmt='o',
                            c=rgba_color2)

                ax.set_ylim((-0.2, 6.0))
                ax.set_xlabel(parm)
                ax.set_ylabel('energy (eV)')
                ax.set_xlim(limits[z])
            if (save):
                plt.savefig('analysis/sorted_ed_' + str(model) + '_' +
                            str(beta) + '_log_og.pdf',
                            bbox_inches='tight')
            else:
                plt.show()
            plt.clf()
    '''
Example #25
0
            # ys = [[j[0], j[1]] for j in y]
            # ys = list(zip(*ys))
            # min_y, max_y = min(ys[1]), max(ys[1])
            # min_x, max_x = min(ys[0]), max(ys[0])

            # pdb.set_trace()
            if args.dists:
                dists = torch.norm(z - x, dim=1)
                ax.plot(dists)

            else:
                # plot actual goal points
                n_pts = y.shape[0]

                goal_colors = iter(cm.Oranges(np.linspace(.2, 1, n_pts)))
                for j in range(n_pts):
                    ax.scatter(y[j][0],
                               y[j][1],
                               color=next(goal_colors),
                               s=144)
                    ax.annotate(j + 1, (y[j][0], y[j][1]),
                                ha='center',
                                va='center')

                # plot potential
                if config.goals_potential != 'none':
                    p_lim = 15
                    px = np.outer(np.linspace(-p_lim, p_lim, 100),
                                  np.ones(100))
                    py = px.copy().T