コード例 #1
0
    def GetData(self):
        pktbl = self.ui.peaks_tbl
        centers = [
            float(pktbl.item(i, 0).text()) for i in range(pktbl.rowCount())
        ]
        widths = [
            float(pktbl.item(i, 1).text()) for i in range(pktbl.rowCount())
        ]
        amps = [
            float(pktbl.item(i, 2).text()) for i in range(pktbl.rowCount())
        ]
        #xmin = float(self.ui.xmin_edit.text())
        xmin = 0
        xmax = float(self.ui.nchannels_edit.text())
        step = 1  #(xmax - xmin) #(xmax - xmin) / (float(self.ui.points_edit.text()) - 1.0)
        x = np.arange(xmin, xmax + step, step)
        y = [float(self.ui.background_edit.text())] * len(x)
        y = np.add(
            y,
            self.GenMultiPeak(x, centers, widths, amps) +
            float(self.ui.noise_edit.text()) * np.random.rand(len(x)))

        self.src.x_chan = np.arange(0, xmax + 1, 1)
        self.src.nchan = len(self.src.x_chan)
        self.src.AddData(y)
        self.src.dataset.pop(
            0)  #This is the accumulated (sum)  set which we will recalculate
        self.src.CalcAllAxis()
        self.src.CalcSumSetCommon("")
        self.src.CalcSumSet(["raw"])
        self.src.SelectFrame("raw")
        self.src.SelectDataSet(-1)
        self.scanman.Generate()
コード例 #2
0
ファイル: operator_data.py プロジェクト: kankan1987/algorithm
def sample_train(data, count=1, test_size=0.4, order=1, random_state=0):
    res_data = np.zeros((count, 4))
    cols = len(data[0])
    param_values = {}
    count_value = np.arange(count)
    min_value = 0
    res_param = None
    for i in range(count):
        y = data[:, cols - 1]
        data_train, data_check, y_train, y_check = train_test_split(
            data, y, test_size=test_size, random_state=i)
        print("this is the [%d] learnning:" % i)
        print("sample_count:%d" % len(data_train))
        print("check_count:%d" % len(data_check))
        #训练参数与样本准确率
        param, accuracy1 = process_data(data_train, 1)
        #校验数据准确率
        accuracy2 = accuracy_data(data_check, param, 1)
        res_data[i, 0] = accuracy1
        res_data[i, 1] = accuracy2
        res_data[i, 2] = i
        res_data[i, 3] = abs(accuracy1 - accuracy2)
        #print("=====%s"%param)
        #param = np.c_[param,count_value[i-1]]
        #param_values[i] = param
        if i == 0:
            min_value = res_data[i, 3]
            res_param = param
        if res_data[i, 3] < min_value:
            min_value = res_data[i, 3]
            res_param = param
    return res_data, res_param
コード例 #3
0
    def plot(cls, data, figure_folder, msg="", suffix=""):

        fig, ax = plt.subplots()

        plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.2)

        x = np.arange(len(data[:]))

        ax.plot(x, data[:, 0], c="red", linewidth=2, label="agent 01")
        ax.plot(x, data[:, 1], c="blue", linewidth=2, label="agent 12")
        ax.plot(x, data[:, 2], c="green", linewidth=2, label="agent 20")

        plt.ylim([-0.01, 1.01])

        plt.text(0, -0.23, "PARAMETERS. {}".format(msg))

        ax.legend(fontsize=12, bbox_to_anchor=(1.1, 1.05))  # loc='upper center'
        ax.set_xlabel("$t$")
        ax.set_ylabel("Proportion of agents proceeding to indirect exchange")

        ax.set_title("Money emergence with a basal ganglia model")

        # Save fig
        if not exists(figure_folder):
            mkdir(figure_folder)
        fig_name = "{}/figure_{}.pdf".format(figure_folder, suffix.split(".p")[0])
        plt.savefig(fig_name)
        plt.close()
コード例 #4
0
    def plot_profits(self, player, period):

        profits = self.results["profits"][-period:]

        plt.title("Profits")
        time_window = 100
        x = np.arange(len(profits[:, player]))
        y = []
        for i in x:
            if i < time_window:
                y_value = np.mean(profits[:i + 1, player])

            else:
                y_value = np.mean(profits[i - time_window:i + 1, player])

            y.append(y_value)

        plt.plot(x, y, color="black")
        maximum_profit = \
            self.parameters["n_positions"] * \
            self.parameters["n_prices"]
        plt.ylim(0, maximum_profit)

        plt.annotate("Time window: {}".format(time_window),
                     xy=(0.8, 0.1),
                     xycoords='axes fraction',
                     fontsize=6)

        # plt.annotate(self.string_parameters, xy=(-0.05, -0.1), xycoords='axes fraction', fontsize=6)

        plt.savefig(self.format_fig_name("profits_player{}".format(player)))
        plt.close()
コード例 #5
0
ファイル: graph.py プロジェクト: afcarl/MoneyPostProd
    def format_data(choice, agent_type):

        t_max = len(choice)

        x = np.arange(t_max)

        ys = [], [], []

        for t in range(t_max):

            # Will register the number of times each good has been used as a medium of exchange
            y = [0, 0, 0]

            for i, ch, at in zip(range(len(agent_type)), choice[t],
                                 agent_type):

                p = at
                c = (at + 1) % 3
                m = (at + 2) % 3
                if (ch[0] == p and ch[1] == m) or (ch[0] == m and ch[1] == c):
                    y[m] += 1

            for i in range(3):
                ys[i].append(y[i])

        return x, ys
コード例 #6
0
ファイル: analysis.py プロジェクト: AurelienNioche/Hotelling
    def curve_plot(self, variable, t_max):

        print("Doing curve plot for variable '{}'.".format(variable))

        var = Variable(name=variable)

        if var.data is None:
            self.extract_single_dimension(var, t_max=t_max)

        x = np.arange(t_max)

        mean = var.data["mean"]
        std = var.data["std"]

        plt.plot(x, mean, c='black', lw=2)
        plt.plot(x, mean + std, c='black', lw=.1)
        plt.plot(x, mean - std, c='black', lw=.1)
        plt.fill_between(x, mean + std, mean - std, color='black', alpha=.1)
        plt.xlabel("t")
        plt.ylabel(self.format_label(variable))
        plt.savefig("{}/curve_plot_{}.pdf".format(self.fig_folder, variable))

        if self.display:
            plt.show()

        plt.close()
コード例 #7
0
    def draw(cls, t_max, agents_proportions, eco_idx, parameters):

        color_set = ["green", "blue", "red"]

        for agent_type in range(3):
            plt.plot(np.arange(t_max), agents_proportions[:, agent_type],
                     color=color_set[agent_type], linewidth=2.0, label="Type-{} agents".format(agent_type))

            plt.ylim([-0.1, 1.1])

        plt.xlabel("$t$")
        plt.ylabel("Proportion of indirect exchanges")

        # plt.suptitle('Direct choices proportion per type of agents', fontsize=14, fontweight='bold')
        plt.legend(loc='upper right', fontsize=12)

        print(parameters)

        plt.title(
            "Workforce: {}, {}, {};   displacement area: {};   vision area: {};   alpha: {};   tau: {}\n"
            .format(
                parameters["x0"],
                parameters["x1"],
                parameters["x2"],
                parameters["movement_area"],
                parameters["vision_area"],
                parameters["alpha"],
                parameters["tau"]
                          ), fontsize=12)

        if not path.exists("../../figures"):
            mkdir("../../figures")

        plt.savefig("../../figures/figure_{}.pdf".format(eco_idx))
        plt.show()
コード例 #8
0
    def plot(cls, data, figure_folder, msg="", suffix=""):

        fig, ax = plt.subplots()

        plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.2)

        x = np.arange(len(data[:]))

        ax.plot(x, data[:, 0], c="red", linewidth=2, label="agent 01")
        ax.plot(x, data[:, 1], c="blue", linewidth=2, label="agent 12")
        ax.plot(x, data[:, 2], c="green", linewidth=2, label="agent 20")

        plt.ylim([-0.01, 1.01])

        plt.text(0, -0.23, "PARAMETERS. {}".format(msg))

        ax.legend(fontsize=12,
                  bbox_to_anchor=(1.1, 1.05))  # loc='upper center'
        ax.set_xlabel("$t$")
        ax.set_ylabel("Proportion of agents proceeding to indirect exchange")

        ax.set_title("Money emergence with a basal ganglia model")

        # Save fig
        if not exists(figure_folder):
            mkdir(figure_folder)
        fig_name = "{}/figure_{}.pdf".format(figure_folder,
                                             suffix.split(".p")[0])
        plt.savefig(fig_name)
        plt.close()
コード例 #9
0
    def make_a_selection(self, n_select, extrema_only):

        n_eco = len(self.stats.data["idx"])

        for key in self.stats.data.keys():
            self.stats.data[key] = np.asarray(self.stats.data[key])

        all_str_cost = sorted(np.unique(
            self.stats.data["transportation_cost"]))

        if extrema_only:
            tr_cost_selected = [all_str_cost[0], all_str_cost[-1]]
        else:
            tr_cost_selected = all_str_cost

        idx_selected = []
        for tr_cost in tr_cost_selected:
            idx_selected += \
                list(np.random.choice(np.arange(n_eco)[self.stats.data["transportation_cost"] == tr_cost],
                                      size=n_select, replace=False))

        idx_selected = np.asarray(idx_selected)

        for key in self.stats.data.keys():
            self.stats.data[key] = self.stats.data[key][idx_selected]

        print("Selection done.")
コード例 #10
0
ファイル: main.py プロジェクト: afcarl/KalterKriegDerKulturen
    def one_step(self, verbose=False):

        # Take a random order among the indexes of the agents.
        random_order = np.random.permutation(self.n_agent)

        for i in random_order:

            # Each agent is "initiator' during one period.
            initiator = self.agents[i]
            # A 'responder' is randomly selected.
            responder = self.agents[np.random.choice(
                np.delete(np.arange(self.n_agent), i))]
            if verbose:
                print("Agent initiator: " + str(i))
                print("Agent influenced: " + str(self.agents.index(responder)))

            # Sanity checks/asserts
            self._assert_agent(initiator)
            self._assert_agent(responder)

            arg_idx, arg_strength = initiator.try_to_convince()

            if self.influence_type == 'linear':
                responder.get_influenced(arguments_idx=arg_idx,
                                         arguments_strength=arg_strength)
            elif self.influence_type == 'nonlinear':
                responder.get_influenced_nonlinear(
                    arguments_idx=arg_idx, arguments_strength=arg_strength)
            else:
                str_err = "self.influence_type not set to a correct value: " + str(
                    self.influence_type)
                raise Exception(str_err)
コード例 #11
0
def animate(_):
    global data, keys, _index
    if not bool_animate_pause:
        if _index > 0:
            time.extend(time[-1] + _index*np.arange(1/n, 1+0.5/n, 1/n) * SAMP_TS)
            for idx, ax in enumerate(ax_list):
                ax.cla()
                exec(f'{keys[idx]}.extend(data[keys[idx]][(_index-1)*n:_index*n])')
                try:
                    ax.plot(time, eval(f'{keys[idx]}'))
                except ValueError as error:
                    # print(str(error))
                    data_backup = data
                    data, keys = get_data(fname)
                    print('Read data.')
                    if len(data[keys[0]]) == len(data_backup[keys[0]]):
                        print('Plotting data are exausted. Quit now.')
                        _index = -1
                        break
                else:
                    ax.set_ylabel(keys[idx])
            ax_list[-1].set_xlabel('Time [s]')
        if _index == -1:
            raise KeyboardInterrupt
        _index += 1
コード例 #12
0
ファイル: analysis.py プロジェクト: afcarl/Prices
def main(data_folder="../data", figure_folder="../figures"):

    deviation_from_equilibrium = dict()
    for i in [(1, 0), (2, 0), (2, 1)]:

        deviation_from_equilibrium[i] = \
            json.load(open("{}/deviation_from_equilibrium_{}.json".format(data_folder, i), mode="r"))

    x = np.arange(len(list(deviation_from_equilibrium.values())[0]))

    fig, ax = plt.subplots()

    for i in deviation_from_equilibrium.keys():
        ax.plot(x,
                deviation_from_equilibrium[i],
                label='{} against {}'.format(i[0], i[1]))

    ax.legend(fontsize=12)  # loc='upper center
    ax.set_xlabel("generation")
    ax.set_ylabel("actual price / equilibrium price")

    ax.set_title(
        "Price Dynamics in Scarf Three-good Economy \n(relative deviation from equilibrium prices)"
    )

    if not path.exists(figure_folder):
        mkdir(figure_folder)
    plt.savefig("{}/figure.pdf".format(figure_folder))

    plt.show()
コード例 #13
0
    def draw(cls, t_max, agents_proportions, eco_idx, parameters):

        color_set = ["green", "blue", "red"]

        for agent_type in range(3):
            plt.plot(np.arange(t_max),
                     agents_proportions[:, agent_type],
                     color=color_set[agent_type],
                     linewidth=2.0,
                     label="Type-{} agents".format(agent_type))

            plt.ylim([-0.1, 1.1])

        plt.xlabel("$t$")
        plt.ylabel("Proportion of indirect exchanges")

        # plt.suptitle('Direct choices proportion per type of agents', fontsize=14, fontweight='bold')
        plt.legend(loc='upper right', fontsize=12)

        print(parameters)

        plt.title(
            "Workforce: {}, {}, {};   displacement area: {};   vision area: {};   alpha: {};   tau: {}\n"
            .format(parameters["x0"], parameters["x1"], parameters["x2"],
                    parameters["movement_area"], parameters["vision_area"],
                    parameters["alpha"], parameters["tau"]),
            fontsize=12)

        if not path.exists("../../figures"):
            mkdir("../../figures")

        plt.savefig("../../figures/figure_{}.pdf".format(eco_idx))
        plt.show()
コード例 #14
0
ファイル: ACMAnimate.py プロジェクト: PeterShi2734/Test
def animate(_):
    global data, keys, _index
    if not bool_animate_pause:
        if _index > 0:
            time = np.arange(1, n * _index + 1) * SAMP_TS
            for idx, ax in enumerate(ax_list):
                ax.cla()
                try:
                    ax.plot(time, data[keys[idx]][:n * _index])

                except ValueError as error:
                    # print(str(error))
                    data_backup = data
                    data, keys = get_data(fname)
                    print('Read data.')
                    if len(data[keys[0]]) == len(data_backup[keys[0]]):
                        print('Plotting data are exausted. Quit now.')
                        _index = -1
                        break
                else:
                    ax.set_ylabel(keys[idx])
            ax_list[-1].set_xlabel('Time [s]')
            # ax.set_title("Frame {}".format(i))
            # ax.relim()
            # ax.autoscale_view()

        if _index == -1:
            restart()
            # raise KeyboardInterrupt
        _index += 1
コード例 #15
0
ファイル: fig18.py プロジェクト: rschmehl/parotor
def Marzmean(lK, Rg, alpha, betas, beta, delta):
    pos = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi])
    omegat = np.arange(0, 360, 1)
    alpha, betas = orientation(lK, Rg, alpha, betas, beta, delta, omegat, pos)
    return alpha, np.mean(
        Marzsum(lK, Rg, alpha, betas, beta, delta, omegat,
                pos)), Ftrminmax(lK, Rg, alpha, betas, beta, delta, omegat,
                                 pos)
コード例 #16
0
ファイル: graph.py プロジェクト: afcarl/MoneyPostProd
    def format_data(reward_amount):

        x = np.arange(min(reward_amount), max(reward_amount), 2)
        y = []
        for i in x:
            y.append(reward_amount.count(i) + reward_amount.count(i + 1))

        return x, y
コード例 #17
0
ファイル: fig17.py プロジェクト: rschmehl/parotor
def Marzmean(lK, Rg, alpha, betas, beta, delta):
    pos = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi])
    omegat = np.arange(0, 360, 1)
    a, b = orientation(lK, Rg, alpha, betas, beta, delta, omegat, pos)
    alpha = a
    betas = b
    Ma = np.mean(Marzsum(lK, Rg, a, b, beta, delta, omegat, pos))
    Mg = np.mean(Marzsum(lK, Rg, a, b, beta, delta, omegat, pos))
    return alpha, betas, Ma, Mg
コード例 #18
0
def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(sample_folders))
    plt.xticks(tick_marks, sample_folders, rotation=45)
    plt.yticks(tick_marks, sample_folders)
    plt.ylabel('True label')
    plt.xlabel('Predicted label')
    plt.show()
コード例 #19
0
    def plot(cls, data, msg=""):

        x = np.arange(len(data[:]))

        plt.plot(x, data[:, 0], c="red", linewidth=2)
        plt.plot(x, data[:, 1], c="blue", linewidth=2)
        plt.plot(x, data[:, 2], c="green", linewidth=2)
        plt.ylim([-0.01, 1.01])
        plt.text(0, -0.12, "{}".format(msg))

        plt.show()
コード例 #20
0
    def plot(cls, data, msg=""):

        x = np.arange(len(data[:]))

        plt.plot(x, data[:, 0], c="red", linewidth=2)
        plt.plot(x, data[:, 1], c="blue", linewidth=2)
        plt.plot(x, data[:, 2], c="green", linewidth=2)
        plt.ylim([-0.01, 1.01])
        plt.text(0, -0.12, "{}".format(msg))

        plt.show()
コード例 #21
0
def profits_over_fov(pool_backup, ax):

    # Shortcuts
    parameters = pool_backup.parameters
    backups = pool_backup.backups

    # Look at the parameters
    t_max = parameters["t_max"]

    # How many time steps from the end of the simulation are included in analysis
    span_ratio = 0.33  # Take last third
    span = int(span_ratio * t_max)

    # Number of bins for the barplot
    n_bins = 50

    # Compute the boundaries
    boundaries = np.linspace(0, 1, (n_bins + 1))

    # Container for data
    data = [[] for i in range(n_bins)]

    for b in backups:

        r = b.parameters.r

        for i, bound in enumerate(boundaries[1:]):
            if r <= bound:
                mean_profit = np.mean(b.profits[-span:, :])
                data[i].append(mean_profit)
                break

    mean_data = [np.mean(d) for d in data]
    std_data = [np.std(d) for d in data]

    # Enhance aesthetics
    ax.set_xlim(-0.01, 1.01)

    ax.set_xticks(np.arange(0, 1.1, 0.25))
    ax.set_ylim(0, 120)

    ax.tick_params(labelsize=9)

    ax.set_xlabel("$r$")
    ax.set_ylabel("Profit")

    # ax.set_title("Mean profits over $r$")

    # Do the hist plot
    width = boundaries[1] - boundaries[0]
    where = [np.mean((boundaries[i+1], boundaries[i])) for i in range(len(boundaries)-1)]
    ax.bar(where, height=mean_data, yerr=std_data, width=width,
           edgecolor='white', linewidth=2, facecolor="0.75")
コード例 #22
0
def compute():

    fov = np.arange(0, 1, 1 / n_positions)
    pos = np.arange(0, n_positions)

    a = np.zeros((len(fov), len(pos)))

    for f_i, f in enumerate(fov):

        for c in pos:  # For each client

            if mode == "fixed_radius":
                field_of_view = get_field_of_view_with_fixed_radius(c, f)

            else:
                field_of_view = get_field_of_view(c, f)

            for x in pos:  # For each position of the firm
                a[f_i, x] += int(field_of_view[0] <= x <= field_of_view[1])

    return a
コード例 #23
0
 def draw_sentiment_data(self, comment_scores):
     # 字典变量的Key为网评数据集
     comments = comment_scores.keys()
     # 字典变量的Value为情感分数集
     scores = comment_scores.values()
     # 绘制网评情感统计分析图:X坐标为网评索引,Y坐标为情感分数,连线样式为虚线'--',连线颜色为蓝色,坐标点形状为圆圈'o',坐标点大小为5号,坐标点颜色为红色
     pylab.plot(np.arange(len(comments)),
                list(scores),
                linestyle='--',
                color='green',
                marker='o',
                markersize=4,
                markerfacecolor='red')
     # 统计分析图的标题
     pyplot.title(u'B站网评情感统计分析图')
     # 统计分析图的X坐标轴标签
     pyplot.xlabel(u'网评索引')
     # 统计分析图的Y坐标轴标签
     pyplot.ylabel(u'情感程度')
     # 统计分析图的Y坐标轴刻度:最小值为-0.5,最大值为0.5,步长为0.1
     pyplot.yticks(ticks=np.arange(start=-0.5, stop=0.5, step=0.1))
     # 显示统计分析图
     pyplot.show()
コード例 #24
0
    def draw(cls, t_max, agents_proportions, suffix):

        color_set = ["green", "blue", "red"]

        for agent_type in range(3):
            plt.plot(np.arange(t_max), agents_proportions[:, agent_type],
                     color=color_set[agent_type], linewidth=1.0)

            plt.ylim([0, 1])

        # plt.suptitle('Direct choices proportion per type of agents', fontsize=14, fontweight='bold')
        # plt.legend(loc='lower left', frameon=False)

        plt.savefig("figure_{}.pdf".format(suffix))
def profit_firmA_against_profit_firmB(file_name, folder=None):

    if folder is None:
        folder = "data/figures"

    os.makedirs(folder, exist_ok=True)

    bkp = backup.RunBackup.load(file_name=file_name)
    parameters = bkp.parameters

    profit_max = parameters.n_positions * parameters.n_prices * parameters.unit_value

    x = np.arange(parameters.t_max)
    y = np.zeros((2, parameters.t_max))

    for f in range(2):
        for t in range(parameters.t_max):
            y[f, t] = np.mean(bkp.profits[:t + 1, f] / profit_max)

        # y = np.array([np.mean(for_y[i][t]) for t in range(parameters.t_max)])
        # y_err = np.array([np.std(for_y[i][t]) for t in range(parameters.t_max)])

    fig = plt.Figure()

    plt.plot(x, y[0], label="Firm A")
    plt.plot(x, y[1], label="Firm B")
    # plt.fill_between(x, y - (y_err / 2), y + (y_err / 2), color="C{}".format(i), alpha=.25)

    plt.legend()
    plt.xlabel("t")
    plt.ylabel("Mean profit")

    plt.text(0.005,
             0.005,
             file_name,
             transform=fig.transFigure,
             fontsize='x-small',
             color='0.5')

    plt.title("Evolution of profits over time ($r={}$)".format(
        bkp.field_of_view / 2))

    plt.tight_layout()

    plt.savefig("{}/{}_mean_profit.pdf".format(folder, file_name))

    plt.show()
コード例 #26
0
ファイル: ACMPlot.py プロジェクト: yceugene/_TINY_ACMSIMC
def draw_trend():
    # plot style
    style = np.random.choice(plt.style.available); print(style); plt.style.use('grayscale') # [u'dark_background', u'bmh', u'grayscale', u'ggplot', u'fivethirtyeight']
    # plot setting
    mpl.rcParams['mathtext.fontset'] = 'stix'
    mpl.rcParams['font.family'] = 'STIXGeneral'
    mpl.rcParams['legend.fontsize'] = 11
    # mpl.rcParams['legend.family'] = 'Times New Roman'
    mpl.rcParams['font.family'] = ['Times New Roman']
    mpl.rcParams['font.size'] = 11.0
    # mpl.style.use('classic')
    font = {'family' : 'Times New Roman', #'serif',
            'color' : 'darkblue',
            'weight' : 'normal',
            'size' : 11,}
    textfont = {'family' : 'Times New Roman', #'serif',
                'color' : 'darkblue',
                'weight' : 'normal',
                'size' : 9,}

    df_profiles = pd.read_csv(r"./algorithm.dat", na_values = ['1.#QNAN', '-1#INF00', '-1#IND00'])
    df_info = pd.read_csv(r"./info.dat", na_values = ['1.#QNAN', '-1#INF00', '-1#IND00'])
    
    # df_profiles["rpm_cmd"]=df_profiles["ACM.rpm_cmd"]
    # df_profiles["rpm_mes"]=df_profiles["ACM.rpm_cmd"]-df_profiles["e_omega"]
    #print(df_profiles.keys())
    
    no_samples = df_profiles.shape[0]
    no_traces  = df_profiles.shape[1]
    print(df_info, 'Simulated time: %g s.'%(no_samples * df_info['TS'].values[0] * df_info['DOWN_SAMPLE'].values[0]), 'Key list:', sep='\n')
    for key in df_profiles.keys():
        print('\t', key)

    time = np.arange(1, no_samples+1) * df_info['DOWN_SAMPLE'].values[0] * df_info['TS'].values[0]

    ax_list = []
    for i in range(0, no_traces, 6):
        ax_list += list(get_axis((1,6)))

    for idx, key in enumerate(df_profiles.keys()):
        plot_it(ax_list[idx], key, O([
                                        (str(idx), df_profiles[key]),  
                                        # (str(idx), df_profiles[key]),  
                                        ]),time,font)
        #print(idx,key)
    # ax_list[12].plot(time,df_profiles["rpm_mes"],color="red")
    plt.show()
コード例 #27
0
ファイル: ui_curve_v2.py プロジェクト: horychen/snippets
def my_curve_fitting(xdata, ydata):
    xdata = np.asarray(xdata)
    popt, pcov = curve_fit(
        func, xdata, ydata
    )  # bounds=(0, [3., 1., 0.5])) # https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html
    print('a1,a2,a3 =', popt)
    plt.figure()
    plt.plot(xdata, ydata, 'x', label='original data')
    x = np.arange(min(xdata) * 3, max(xdata) * 3, 0.1)
    plt.plot(x,
             func(x, *popt),
             'r--',
             label='fit: a1=%5.3f, a2=%5.3f, a3=%5.3f' % tuple(popt))
    plt.plot(x,
             func(x, 0.0, popt[1], popt[2]),
             'b--',
             label='fit: a1=%5.3f, a2=%5.3f, a3=%5.3f' % tuple(popt))
コード例 #28
0
ファイル: graph.py プロジェクト: afcarl/MoneyPostProd
    def format_data(choice):

        t_max = len(choice)

        x = np.arange(t_max)

        y0 = []
        y1 = []
        y2 = []
        for t in range(t_max):
            y0.append(choice[t].count([0, 1]) + choice[t].count([1, 0]))
            y1.append(choice[t].count([1, 2]) + choice[t].count([2, 1]))
            y2.append(choice[t].count([2, 0]) + choice[t].count([0, 2]))

        ys = y0, y1, y2

        return x, ys
コード例 #29
0
ファイル: graph.py プロジェクト: afcarl/MoneyPostProd
    def format_data(choice, success, agent_type):

        t_max = len(choice)

        x = np.arange(t_max)
        y = []

        for t in range(t_max):

            consumption = 0
            for c, s, at, in zip(choice[t], success[t], agent_type):
                if c[1] == (at + 1) % 3 and s:
                    consumption += 1

            y.append(consumption)

        return x, y
コード例 #30
0
ファイル: graph.py プロジェクト: afcarl/MoneyPostProd
    def format_data(choice):

        t_max = len(choice)

        x = np.arange(t_max)

        y0, y1, y2, y3, y4, y5 = [], [], [], [], [], []

        for t in range(t_max):
            y0.append(choice[t].count([0, 1]))
            y1.append(choice[t].count([1, 0]))
            y2.append(choice[t].count([1, 2]))
            y3.append(choice[t].count([2, 1]))
            y4.append(choice[t].count([2, 0]))
            y5.append(choice[t].count([0, 2]))

        ys = y0, y1, y2, y3, y4, y5

        return x, ys
コード例 #31
0
def compute():
    pos = np.arange(0, n_positions)

    a = np.zeros((len(pos), len(pos)))

    b = np.zeros((len(pos), len(pos)), dtype=list)
    for x1, x2 in it.product(pos, repeat=2):
        b[x1, x2] = list()

    for c in pos:  # For each client

        print("Customer", c)

        if mode == "fixed_radius":
            field_of_view = get_field_of_view_with_fixed_radius(c)

        else:
            field_of_view = get_field_of_view(c)

        print("Field of view", field_of_view)

        for x1, x2 in it.product(pos, repeat=2):

            see_firm_1 = field_of_view[0] <= x1 <= field_of_view[1]
            see_firm_2 = field_of_view[0] <= x2 <= field_of_view[1]

            if cond == "see_both" and see_firm_1 and see_firm_2:
                a[x1, x2] += 1
                b[x1, x2].append(c)

            if cond == "see_firm_1" and see_firm_1 and not see_firm_2:
                a[x1, x2] += 1

            if cond == "see_firm_2" and not see_firm_1 and see_firm_2:
                a[x1, x2] += 1

    # for i in np.arange(n_positions - 1, -1, -1):
    #     print(i, [j for j in b[i]])
    return a
コード例 #32
0
    def plotFuncObj(self, func):
        x = np.arange(0, 2*np.pi, 0.5/180*np.pi)
        y = [func(el) for el in x]
        x = [el/np.pi for el in x] # x for plot. unit is pi
        
        self.fig_plotFuncObj = plt.figure()
        ax = plt.subplot(111) #注意:一般都在ax中设置,不在plot中设置
        ax.plot(x, y)

        xmajorLocator   = plt.MultipleLocator(0.25) #将x主刻度标签设置为20的倍数
        xmajorFormatter = plt.FormatStrFormatter('%.2fπ') #设置x轴标签文本的格式
        ax.xaxis.set_major_locator(xmajorLocator)  
        ax.xaxis.set_major_formatter(xmajorFormatter)

        ##matplotlib.pyplot.minorticks_on()
        ##xminorLocator   = MultipleLocator(0.25)
        ##xminorFormatter = FormatStrFormatter(u'%.2fπ')
        ##ax.xaxis.set_minor_locator(xminorLocator)  
        ##ax.xaxis.set_minor_formatter(xminorFormatter)

        plt.xlabel('Angular location along the gap [mech. rad.]')
        plt.ylabel('Turns of winding [1]')
        # plt.title('Turn Function or Winding Function')
        plt.grid(True) # or ax.grid(True)
コード例 #33
0
from matplotlib.widgets import MultiCursor
from pylab import figure, show, np

t = np.arange(0.0, 2.0, 0.01)
s1 = np.sin(2*np.pi*t)
s2 = np.sin(4*np.pi*t)
fig = figure()
ax1 = fig.add_subplot(211)
ax1.plot(t, s1)

ax2 = fig.add_subplot(212, sharex=ax1)
ax2.plot(t, s2)

multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=1,
                    horizOn=False, vertOn=True)
show()
コード例 #34
0
ファイル: legend_unit.py プロジェクト: 4over7/matplotlib
from __future__ import print_function
from pylab import figure, show, np

Ntests = 3
t = np.arange(0.0, 1.0, 0.05)
s = np.sin(2 * np.pi * t)

# scatter creates a RegPolyCollection
fig = figure()
ax = fig.add_subplot(Ntests, 1, 1)
N = 100
x, y = 0.9 * np.random.rand(2, N)
area = np.pi * (10 * np.random.rand(N)) ** 2  # 0 to 10 point radiuses
ax.scatter(x, y, s=area, marker='^', c='r', label='scatter')
ax.legend()

# vlines creates a LineCollection
ax = fig.add_subplot(Ntests, 1, 2)
ax.vlines(t, [0], np.sin(2 * np.pi * t), label='vlines')
ax.legend()

# vlines creates a LineCollection
ax = fig.add_subplot(Ntests, 1, 3)
ax.plot(t, s, 'b-', lw=2, label='a line')
ax.legend()

fig.savefig('legend_unit')
show()
コード例 #35
0
ファイル: fig17.py プロジェクト: rschmehl/parotor
def Marzmean0(lK, Rg, alpha, betas, beta, delta):
    pos = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi])
    omegat = np.arange(0, 360, 1)
    return np.mean(Marzsum(lK, Rg, alpha, betas, beta, delta, omegat, pos))
コード例 #36
0
        plt.show()


def simple_run():

    param = json.load(open("single-shot-and-plot-parameters.json", mode="r"))

    param["cpu_count"] = cpu_count()
    param["model"] = "BG"

    results = Launcher.launch(param, single=True)

    msg = "workforce: {}, t_max: {}, hebbian: {}, \nparameters: {}" \
        .format(param["workforce"],
                param["t_max"],
                param["hebbian"],
                param["model_parameters"])

    Analysis.simple_analysis(results["indirect_exchanges"], msg=msg)


if __name__ == "__main__":

    if system() == 'Linux':

        # Test visual output
        plt.plot(np.arange(10), np.arange(10))
        plt.show()

    simple_run()