Пример #1
0
def _plot_shortest_paths(g: ig.Graph, path_prefix: Path) -> None:
    file_path = path_prefix.joinpath("shortest_paths.png")

    # Estimate diameter and paths
    paths = g.get_all_shortest_paths(0, mode=ig.ALL)
    path_lens = list(map(len, paths))

    diam = max(path_lens)
    eff_diam = np.percentile(path_lens, 90)
    cnts = Counter(path_lens)

    # Plot
    plt.style.use("ggplot")
    f: plt.Figure = plt.Figure(figsize=(8, 5), dpi=150)
    ax: plt.Axes = f.add_subplot()
    ax.plot(
        cnts.keys(),
        cnts.values(),
        ".",
        label="Path.Len.Distr.\nDiam.: {:d}\nEff.Diam.: {:.2f}".format(
            diam, eff_diam),
    )
    ax.legend()
    ax.set_xlabel("Path. length")
    ax.set_ylabel("Count paths")

    f.savefig(str(file_path.absolute()))
    plt.close(f)
Пример #2
0
def _plot_degrees_correlations(g: ig.Graph, path_prefix: Path) -> None:
    file_path = path_prefix.joinpath("degree_correlations.png")

    # Compute correlations
    num_nodes = int(g.vcount() * 0.35)
    visited = set()
    corrs = np.zeros((num_nodes, 2), dtype=np.float32)

    # Compute coefficient
    assortativity = g.assortativity_degree(directed=False)

    for i in range(num_nodes):
        while True:
            rnd_id = choice(g.vs)
            if rnd_id.index not in visited:
                visited.add(rnd_id.index)
                break

        deg = rnd_id.degree()

        for nbh in rnd_id.neighbors():
            corrs[i, 1] += nbh.degree() / deg

        corrs[i, 0] = deg

    # Drop heavy tail
    corrs = corrs[np.argsort(corrs[:, 0])[:-50], :]

    # Fit line
    solution = np.polyfit(corrs[:, 0], corrs[:, 1], deg=1)

    # Plot scatter
    plt.style.use("ggplot")
    f: plt.Figure = plt.Figure(figsize=(8, 5), dpi=150)
    ax: plt.Axes = f.add_subplot()

    ax.plot(corrs[:, 0], corrs[:, 1], ".", label="Real data")
    ax.plot(
        corrs[np.argsort(corrs[:, 0]), 0],
        corrs[np.argsort(corrs[:, 0]), 0] * solution[0] + solution[1],
        "-",
        label="Fitted line: {:2f}x + {:2f}\nAssortativity coeff.: {:.3f}".
        format(solution[0], solution[1], assortativity),
    )

    ax.legend()
    ax.set_xlabel("Node degree")
    ax.set_ylabel("Neighborhood avg degree")

    f.savefig(str(file_path.absolute()))

    plt.close(f)
def calc_spec_peak(freqs, powers, fitting_bw=[1, 55], out_image_path=None):
    '''Spectral fitting routine from the FOOOF toolbox
    https://fooof-tools.github.io/fooof/index.html
    
        
    doi: https://doi.org/10.1101/299859 
    
    Fit the spectral peaks and return the fit parameters
    Save the image of the spectral data and peak fits
    
    Inputs:
        freqs - numpy array of frequencies
        powers - numpy array of spectral power
        fitting_bw - Reduce the total bandwidth to fit the 1/f and spectral peaks
        
    Outputs:
        params - parameters from the FOOOF fit
        
    '''

    #Crop Frequencies for 1/f
    powers = powers[(freqs > fitting_bw[0]) & (freqs <= fitting_bw[1])]
    freqs = freqs[(freqs > fitting_bw[0]) & (freqs <= fitting_bw[1])]

    # Initialize power spectrum model objects and fit the power spectra
    fm1 = FOOOF(min_peak_height=0.05, verbose=False)
    fm1.fit(freqs, powers)

    if out_image_path is not None:
        import matplotlib
        from matplotlib import pylab
        matplotlib.use('Agg')
        # import pylab
        fig = pylab.Figure(figsize=[10, 6])  #, dpi=150)
        ax = fig.add_subplot()
        plot_annotated_model(fm1, annotate_peaks=False, ax=ax)
        fig.tight_layout()
        fig.savefig(out_image_path, dpi=150, bbox_inches="tight")

    params = fm1.get_results()
    params.peak_params[0]

    # plot_spectrum(freqs, powers, log_powers=True,
    #               color='black', label='Original Spectrum')
    return params
Пример #4
0
def plot_scatter_matrix(title, tr, fig=None):
    if (fig is None):
        fig = plt.Figure()
    t6 = pandas.Series(tr['c'])
    t8 = pandas.Series(tr['gmm'][:, 0])
    t9 = pandas.Series(tr['gmm'][:, 1])
    t10 = pandas.Series(tr['gmm_p'][:, 0])
    t11 = pandas.Series(tr['pbeta'])
    df = pandas.DataFrame({
        'cat': t6,
        'gmm_0': t8,
        'gmm_1': t9,
        'p': t10,
        'pbeta': t11
    })
    pandas.scatter_matrix(df)
    plt.title(title)
    return fig
Пример #5
0
def plot_p_prior_vs_posterior(prior_trace, posterior_trace, fig=None):
    if (fig is None):
        fig = plt.Figure()
    pr = pandas.Series(prior_trace['gmm_p'][:, 0])
    po = pandas.Series(posterior_trace['gmm_p'][:, 0])
    plt.hist(pr,
             bins=40,
             range=(-0.1, 1.1),
             color='b',
             alpha=0.5,
             label='Prior')
    plt.hist(po,
             bins=40,
             range=(-0.1, 1.1),
             color='g',
             alpha=0.5,
             label='Posterior')
    plt.legend()
    plt.show()
Пример #6
0
 def _create_dendrogram(self) -> None:
     dend_out = Output(layout={
         "width": "99%",
         "height": "310px",
         "overflow_y": "auto"
     })
     with dend_out:
         print("This is the hierarchy of the routes")
         fig = plt.Figure()
         dendrogram(
             ClusteringHelper(
                 self._routes.distance_matrix()).linkage_matrix(),
             color_threshold=0.0,
             labels=np.arange(1,
                              len(self._routes) + 1),
             ax=fig.gca(),
         )
         fig.gca().set_xlabel("Route")
         fig.gca().set_ylabel("Distance")
         display(fig)
     display(dend_out)
Пример #7
0
def _plot_degree_distribution(g: ig.Graph, path_prefix: Path) -> None:
    file_path = path_prefix.joinpath("degrees.png")

    # Count degrees
    degrees = g.vs.degree()
    degree_distr = Counter(degrees)

    log_deg = np.zeros(len(degree_distr), dtype=np.float32)
    log_cnt = np.zeros(len(degree_distr), dtype=np.float32)

    for i, kv in enumerate(degree_distr.items()):
        log_deg[i] = np.log(kv[0]) if kv[0] > 0 else 0
        log_cnt[i] = np.log(kv[1])

    # Fit linear regression
    solution = np.polyfit(log_deg[log_cnt > 1.5],
                          log_cnt[log_cnt > 1.5],
                          deg=1)

    # Plot distributions
    plt.style.use("ggplot")
    f: plt.Figure = plt.Figure(figsize=(8, 5), dpi=150)
    ax: plt.Axes = f.add_subplot()
    ax.plot(log_deg, log_cnt, ".", label="Real Degrees")
    ax.plot(
        log_deg,
        log_deg * solution[0] + solution[1],
        "-",
        label="Linear fit: {:.4f}x + {:.2f}".format(solution[0], solution[1]),
    )
    ax.legend()
    ax.set_xlabel("Log degree")
    ax.set_ylabel("Log count degrees")
    ax.set_ylim(bottom=np.min(log_cnt) - 1e-5)

    f.savefig(str(file_path.absolute()))
    plt.close(f)
Пример #8
0
def _plot_clustering_coeff(g: ig.Graph, path_prefix: Path) -> None:
    file_path = path_prefix.joinpath("clustcoeff.png")
    g = g.copy().simplify()

    # Get clustering coefficient based on 50% of vertices
    subset = [vidx for vidx in g.vs.indices if random() <= 0.5]
    lcc = g.transitivity_local_undirected(vertices=subset, mode="zero")
    degrees = g.degree(vertices=subset)
    avg_clustering_coeff = np.mean(lcc)

    # Plot
    plt.style.use("ggplot")
    f: plt.Figure = plt.Figure(figsize=(8, 5), dpi=150)
    ax: plt.Axes = f.add_subplot()
    ax.plot(degrees,
            lcc,
            ".",
            label="ClustCoeff. Avg = {:.2e}".format(avg_clustering_coeff))
    ax.legend()
    ax.set_xlabel("Degree")
    ax.set_ylabel("Avg Clustering of Degree")

    f.savefig(str(file_path.absolute()))
    plt.close(f)
Пример #9
0
 def _default_figure(self):
     return pl.Figure()
Пример #10
0
i = 0
while True:
    currentX = x[i]
    gr = gradient(currentX[0], currentX[1])
    sd = searchDirection(gr)
    alpha = stepSize(currentX)
    newX = makeStep(currentX, alpha, sd)
    if checkTolerance(newX[0], newX[1]):
        break
    else:
        x.append(newX)
        i += 1

points = np.array(x)

fig = plt.Figure()
fig, ax = plt.subplots()
ax.set_aspect(1)
x1, x2, y1, y2 = plt.axis()
plt.axis((-8, 8, -2, 2))
ax.plot(points[:, 0], points[:, 1], "bo-", label=r"gradient descent")

xc = np.linspace(-10, 10, 100)
yc = np.linspace(-5, 5, 100)
XC, YC = np.meshgrid(xc, yc)
levels = np.arange(-40, 40, 4)
plt.contour(XC, YC, F(XC, YC), levels)
ax.legend(loc=1)

plt.show()
Пример #11
0
    def create_main_window(self):
        """
		This function creates the main window of the program. 
		"""
        self.main_frame = QWidget()
        self.main_frame.setMinimumSize(QSize(700, 700))

        self.dpi = 100
        self.fig = plt.Figure((6, 6),
                              dpi=self.dpi,
                              facecolor='w',
                              edgecolor='w')
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        self.preview_frame = QWidget()
        self.preview_fig = plt.Figure((3, 1.6),
                                      dpi=self.dpi,
                                      facecolor='w',
                                      edgecolor='w')
        self.preview = FigureCanvas(self.preview_fig)
        self.preview.setParent(self.preview_frame)
        self.preview_axes = self.preview_fig.add_subplot(111)

        self.preview_fig.canvas.mpl_connect('button_press_event', self.onclick)
        self.preview_fig.subplots_adjust(top=1, bottom=0, left=0, right=1)

        # Since we have only one plot, we can use add_axes
        # instead of add_subplot, but then the subplot
        # configuration tool in the navigation toolbar wouldn't
        # work.
        #
        self.axes = self.fig.add_subplot(111)
        # Turning off the axes ticks to maximize space. Also the labels were meaningless
        # anyway because they were not representing the actual lat/lons.
        self.axes.get_xaxis().set_visible(False)
        self.axes.get_yaxis().set_visible(False)

        # Other GUI controls
        # Information section
        font = QFont("SansSerif", 14)

        # STATISTICS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        self.statdisplay = QLabel("Statistics:")
        self.statgrid = QGridLayout()
        self.statgrid.setSpacing(5)
        w = QLabel("Local")
        w.setFont(font)
        self.statgrid.addWidget(w, 1, 1, Qt.AlignCenter)
        w = QLabel("Global")
        w.setFont(font)
        self.statgrid.addWidget(w, 1, 2, Qt.AlignCenter)

        for i, name in enumerate(["Minimum", "Maximum", "Mean"]):
            w = QLabel(name)
            w.setFont(font)
            self.statgrid.addWidget(w, i + 2, 0, Qt.AlignLeft)

        self.statsarray = []
        for i in range(6):
            self.statsarray.append(QLabel(''))

        self.statsarray[3].setText("{0:5.2f}".format(self.dc.data.min()))
        self.statsarray[4].setText("{0:5.2f}".format(self.dc.data.max()))
        self.statsarray[5].setText("{0:5.2f}".format(self.dc.data.mean()))

        for i in range(3):
            self.statgrid.addWidget(self.statsarray[i], i + 2, 1,
                                    Qt.AlignCenter)
            self.statgrid.addWidget(self.statsarray[i + 3], i + 2, 2,
                                    Qt.AlignCenter)
            self.statsarray[i].setFont(font)
            self.statsarray[i + 3].setFont(font)

        # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

        # PIXEL INFO >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

        self.infodisplay = QLabel("Pixel Information:")
        self.infogrid = QGridLayout()
        self.infogrid.setSpacing(5)

        for i, name in enumerate(["Latitude", "Longitude", "Value"]):
            w = QLabel(name)
            w.setFont(font)
            self.infogrid.addWidget(w, i + 1, 0, Qt.AlignLeft)

        self.latdisplay = QLabel("")
        self.londisplay = QLabel("")
        self.valdisplay = QLabel("")
        for i, w in enumerate(
            [self.latdisplay, self.londisplay, self.valdisplay]):
            self.infogrid.addWidget(w, i + 1, 1, Qt.AlignLeft)
        # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

        # Colorscheme selector
        cmap_label = QLabel('Colorscheme:')
        self.colormaps = QComboBox(self)
        self.colormaps.addItems(self.maps)
        self.colormaps.setCurrentIndex(self.maps.index('Spectral'))
        self.colormaps.currentIndexChanged.connect(self.render_view)

        # New value editor
        hbox = QHBoxLayout()
        w = QLabel("Enter new value: ")
        w.setFont(font)
        hbox.addWidget(w)
        self.inputbox = QLineEdit()
        self.inputbox.returnPressed.connect(self.update_value)
        hbox.addWidget(self.inputbox)

        for item in [
                self.statdisplay, self.infodisplay, self.latdisplay,
                self.londisplay, self.valdisplay, cmap_label
        ]:
            item.setFont(font)

        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)

        vbox2 = QVBoxLayout()
        vbox2.addWidget(self.preview)

        vbox2.addWidget(self.statdisplay)
        vbox2.setAlignment(self.statdisplay, Qt.AlignTop)
        vbox2.addLayout(self.statgrid)

        vbox2.addWidget(self.infodisplay)
        vbox2.setAlignment(self.infodisplay, Qt.AlignTop)
        vbox2.addLayout(self.infogrid)

        # vbox2.addWidget(self.inputbox, Qt.AlignTop)
        vbox2.addLayout(hbox, Qt.AlignTop)

        vbox2.addStretch(1)
        vbox2.addWidget(cmap_label)
        vbox2.addWidget(self.colormaps)
        vbox2.addStretch(1)

        hbox = QHBoxLayout()
        hbox.addLayout(vbox)
        hbox.addLayout(vbox2)

        self.main_frame.setLayout(hbox)
        self.setCentralWidget(self.main_frame)
        self.main_frame.setFocus()
Пример #12
0
import matplotlib

# matplotlib.rcParams['backend.qt4'] = 'PySide'
# matplotlib.use('Qt4Agg')

import numpy as np
# import matplotlib.pyplot as plt
import matplotlib.pylab as pl
# import pylab as pl

# from PyQt import QtGui
# from matplotlib.backends.backend_qt4agg \
#     import FigureCanvasQTAgg as FigureCanvas
# from PySide.QtGui import QApplication
# from PySide.QtGui import QMainWindow
# from PySide.QtCore import Qt

pl.Figure()
ax = pl.subplot(111)
pl.show()
Пример #13
0
    def create_main_window(self):
        """
        This function creates the main window of the program.
        """
        self.main_frame = QWidget()
        self.main_frame.setMinimumSize(QSize(700, 700))

        self.dpi = 100
        self.fig = plt.Figure((6, 6),
                              dpi=self.dpi,
                              facecolor='w',
                              edgecolor='w')
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        # Stuff for the preview map >>>>>>>>>>>>>>>>>>>>>>>>>
        self.preview_frame = QWidget()
        self.preview_fig = plt.Figure((3, 1.6),
                                      dpi=self.dpi,
                                      facecolor='w',
                                      edgecolor='w')
        self.preview = FigureCanvas(self.preview_fig)
        self.preview.setParent(self.preview_frame)
        self.preview_axes = self.preview_fig.add_subplot(111)

        self.preview_fig.canvas.mpl_connect('button_press_event', self.onclick)
        self.preview_fig.subplots_adjust(top=1, bottom=0, left=0, right=1)
        # Stuff for the preview map <<<<<<<<<<<<<<<<<<<<<<<<<

        # Stuff for the colorbar >>>>>>>>>>>>>>>>>>>>>>>>>
        self.colorbar_frame = QWidget()
        self.colorbar_fig = plt.Figure((3, 0.4),
                                       dpi=self.dpi,
                                       facecolor='w',
                                       edgecolor='w')
        self.colorbar = FigureCanvas(self.colorbar_fig)
        self.colorbar.setParent(self.colorbar_frame)
        self.colorbar_axes = self.colorbar_fig.add_subplot(111)
        self.colorbar_fig.subplots_adjust(
            top=1.0, bottom=0.35, left=0.02,
            right=0.97)  #Tightening the area around the subplot
        self.colorbar_fig.patch.set_facecolor(
            'none')  # Making the figure background transparent

        self.colorbar_axes.get_xaxis().set_visible(False)
        self.colorbar_axes.get_yaxis().set_visible(False)
        # Stuff for the colorbar <<<<<<<<<<<<<<<<<<<<<<<<<

        # Since we have only one plot, we can use add_axes
        # instead of add_subplot, but then the subplot
        # configuration tool in the navigation toolbar wouldn't
        # work.
        #
        self.axes = self.fig.add_subplot(111)
        # Turning off the axes ticks to maximize space. Also the labels were meaningless
        # anyway because they were not representing the actual lat/lons.
        self.axes.get_xaxis().set_visible(False)
        self.axes.get_yaxis().set_visible(False)

        # Other GUI controls
        # Information section
        font = QFont("SansSerif", 14)

        # STATISTICS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        self.statdisplay = QLabel("Statistics:")
        self.statgrid = QGridLayout()
        self.statgrid.setSpacing(5)
        w = QLabel("View")
        w.setFont(font)
        self.statgrid.addWidget(w, 1, 1, Qt.AlignCenter)
        w = QLabel("Global")
        w.setFont(font)
        self.statgrid.addWidget(w, 1, 2, Qt.AlignCenter)

        for i, name in enumerate(["Minimum", "Maximum", "Mean"]):
            w = QLabel(name)
            w.setFont(font)
            self.statgrid.addWidget(w, i + 2, 0, Qt.AlignLeft)

        self.statsarray = []
        for i in range(6):
            self.statsarray.append(QLabel(''))

        self.statsarray[3].setText("{0:3d}".format(int(self.dc.data.min())))
        self.statsarray[4].setText("{0:3d}".format(int(self.dc.data.max())))
        self.statsarray[5].setText("{0:3d}".format(int(self.dc.data.mean())))

        for i in range(3):
            self.statgrid.addWidget(self.statsarray[i], i + 2, 1,
                                    Qt.AlignCenter)
            self.statgrid.addWidget(self.statsarray[i + 3], i + 2, 2,
                                    Qt.AlignCenter)
            self.statsarray[i].setFont(font)
            self.statsarray[i + 3].setFont(font)

        # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

        # PIXEL INFO >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

        self.infodisplay = QLabel("Pixel Information:")
        self.infogrid = QGridLayout()
        self.infogrid.setSpacing(5)

        for i, name in enumerate(["Lat", "Lon", "KMT", "I, J"]):
            w = QLabel(name)
            w.setFont(font)
            # w.setLineWidth(1)
            # w.setFrameShape(QFrame.Box)
            self.infogrid.addWidget(w, i + 2, 0, Qt.AlignLeft)

        self.latdisplay = QLabel("")
        self.londisplay = QLabel("")
        self.valdisplay = QLabel("")
        self.idxdisplay = QLabel("")
        for i, w in enumerate([
                self.latdisplay, self.londisplay, self.valdisplay,
                self.idxdisplay
        ]):
            self.infogrid.addWidget(w, i + 2, 1, Qt.AlignLeft)
            w.setFont(font)
        # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

        # Colorscheme selector
        cmap_label = QLabel('Colorscheme:')
        self.colormaps = QComboBox(self)
        self.colormaps.addItems(self.maps)
        self.colormaps.setCurrentIndex(self.maps.index('Set1'))
        self.colormaps.currentIndexChanged.connect(self.render_view)

        # New value editor
        valhbox = QHBoxLayout()
        w = QLabel("Enter new value: ")
        w.setFont(font)
        valhbox.addWidget(w)
        self.inputbox = QLineEdit()
        self.inputbox.returnPressed.connect(self.update_value)
        valhbox.addWidget(self.inputbox)

        for item in [
                self.statdisplay, self.infodisplay, self.latdisplay,
                self.londisplay, self.valdisplay, self.idxdisplay, cmap_label
        ]:
            item.setFont(font)

        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)

        vbox2 = QVBoxLayout()
        vbox2.addWidget(self.preview)  # Adding preview window

        # Horizontal line
        fr = QFrame()
        fr.setLineWidth(0.5)
        fr.setFrameShape(QFrame.HLine)
        vbox2.addWidget(fr)
        vbox2.setAlignment(fr, Qt.AlignTop)

        # databox is a horizontal box for the displayed "information"
        databox = QHBoxLayout()
        statvbox = QVBoxLayout()  # This is the sub-box for the statistics
        statvbox.addWidget(self.statdisplay)
        statvbox.setAlignment(self.statdisplay, Qt.AlignTop)
        statvbox.addLayout(self.statgrid)
        databox.addLayout(statvbox)

        fr = QFrame()
        fr.setLineWidth(0.5)
        fr.setFrameShape(QFrame.VLine)
        databox.addWidget(fr)

        pixelvbox = QVBoxLayout(
        )  # This is another sub-box of databox for the pixel info
        pixelvbox.addWidget(self.infodisplay)
        pixelvbox.setAlignment(self.infodisplay, Qt.AlignTop)
        pixelvbox.addLayout(self.infogrid)
        databox.addLayout(pixelvbox)

        vbox2.addLayout(databox)

        # Horizontal line
        fr = QFrame()
        fr.setLineWidth(0.5)
        fr.setFrameShape(QFrame.HLine)
        vbox2.addWidget(fr)
        vbox2.setAlignment(fr, Qt.AlignTop)

        vbox2.addLayout(valhbox, Qt.AlignTop)

        vbox2.addStretch(1)
        vbox2.addWidget(cmap_label)  # Adding the colormap label
        vbox2.addWidget(self.colormaps)  # Adidng the colormap selector
        vbox2.addWidget(self.colorbar)
        vbox2.setAlignment(self.colorbar, Qt.AlignCenter)
        vbox2.addStretch(1)

        helpbox = QVBoxLayout()

        help_title = QLabel("Help")
        font = QFont("SansSerif", 14)
        font.setBold(True)
        help_title.setFont(font)

        helpbox.addWidget(help_title)
        helpbox.setAlignment(help_title, Qt.AlignTop)

        helpgrid = QGridLayout()
        helpgrid.setSpacing(5)

        helpgrid.addWidget(QLabel("Key"), 0, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("Action"), 0, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("up, down,left,right"), 1, 0, 1, 1,
                           Qt.AlignLeft)
        helpgrid.addWidget(QLabel("move cursor"), 1, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("h,j,k,l"), 2, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("move view"), 2, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("a"), 3, 0, 1, 1, Qt.AlignLeft)
        # helpgrid.addWidget(QLabel("replace cell value with 9 point average"),         3, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("replace cell value with 9\npoint average"),
                           3, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("="), 4, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("enter new value for cell"), 4, 1, 1, 1,
                           Qt.AlignLeft)
        helpgrid.addWidget(QLabel("c"), 5, 0, 1, 1, Qt.AlignLeft)
        # helpgrid.addWidget(QLabel("copy value under cursor into buffer"),         5, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("copy value under cursor\ninto buffer"), 5,
                           1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("v"), 6, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("paste value in buffer"), 6, 1, 1, 1,
                           Qt.AlignLeft)
        helpgrid.addWidget(QLabel("m"), 7, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("move focus to color selector"), 7, 1, 1, 1,
                           Qt.AlignLeft)
        helpgrid.addWidget(QLabel("Escape"), 8, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("move focus to main view"), 8, 1, 1, 1,
                           Qt.AlignLeft)

        helpbox.addLayout(helpgrid)
        helpbox.setAlignment(helpgrid, Qt.AlignTop)

        vbox2.addLayout(helpbox)
        vbox2.setAlignment(helpbox, Qt.AlignBottom)

        hbox = QHBoxLayout()
        hbox.addLayout(vbox)
        hbox.addLayout(vbox2)

        self.main_frame.setLayout(hbox)
        self.setCentralWidget(self.main_frame)
        self.main_frame.setFocus()
Пример #14
0
    yy = np.array([1, 45])
    xx = np.array([1, 99])
    means = [xx.mean(), yy.mean()]
    stds = [xx.std() / density, yy.std() / density]
    corr = 0.99  # correlation
    covs = [[stds[0]**2, stds[0] * stds[1] * corr],
            [stds[0] * stds[1] * corr, stds[1]**2]]

    m = np.random.multivariate_normal(means, covs, item_count).T

    m = np.round(m).astype(int)
    capacity = 400
    return m[0], m[1], capacity


if __name__ == '__main__':
    np.random.seed(42)
    profits, weights, _ = create_knapsack_data(item_count=20)

    plt.Figure()
    plt.scatter(weights, profits)
    plt.xlabel("weights")
    plt.ylabel("profits")

    np.random.seed(42)
    profits, weights, _ = create_knapsack_correlated(item_count=20)

    plt.scatter(weights, profits, marker='x')
    plt.legend(['random', 'correlated'])
    plt.show()