Python Code in Java Code

iltisjan

Mitglied
Hi,

ich habe ein (für mich) recht komplexes Java Projekt geschrieben, was soweit auch gut funktioniert. Nun möchte ich aber ein paar schöne Grafiken erzeugen, was mit python in diesem Fall sehr gut funktioniert. Ich möchte also mein bestehendes Java-Projekt mit Python Code erweitern und dann kompilieren, damit jeder es verwenden kann, auch ohne, dass er python installiert hat.
Nun habe ich von Jython gelesen, aber ich tue mich schwer mit der Implementierung.
Wie genau muss ich vorgehen? Ich habe Jython 2.7 runtergeladen und installiert, aber was passiert dann? Ich stelle mir das so vor, dass man irgendwelche python libraries in seienr java Klasse importiert und dann einfach python code und java code mischen kann.
Ist das richtig so?
Funktioniert mein Vorhaben überhaupt?

Falls es wichtig ist:
Ich verwende eclipse

Ich hoffe meine Fragestellung ist einigermaßen klar, ich bin noch neu in der Java Programmierung, also seht es mir bitte nach, wenn ich noch ein paar mehr Fragen stellen muss.
In der Suchfunktion hat auch schonmal jemand was ähnliches gefragt, aber ich wurde nicht wirklich schlau draus.
 
Ich frage mich eher wo das Problem liegt die Grafiken in Java zu erzeugen. Das hat doch auch alles notwendigen Bibliotheken dafür
 
Ich frage mich eher wo das Problem liegt die Grafiken in Java zu erzeugen. Das hat doch auch alles notwendigen Bibliotheken dafür

Ich möchte insgesamt 3 Grafiken erzeugen.
Heatmap
Boxplot
Barplot

Boxplot und Barplot bekomme ich ganz gut hin, aber die heatmap sieht einfach in python viel viel besser aus. Ich habe jetzt echt einiges ausprobiert, aber in pyhton ist man was das angeht viel flexibler und zudem auch sehr viel einfacher.
Ich möchte die einzelnen Datenpunkte in der Heatmap beschriften und die Punkte sollen gut abgegrenzt voneinander sein, sodas man schnell sieht welcher Datenpunkt wohin gehört.
Kurz gesagt, ich mag die heatmap Funktionen in python lieber, weil sie einfacher zu benutzen sind und das Ergebnis schöner aussieht. Entweder liegt es daran, dass ich das mit Java einfach nicht hinbekomme, weil ich es nicht kann (wahrscheinlich), oder weil es mit Java einfach nicht so gut geht (unwahrscheinlich).
 
Nicht direkt eine Antwort zu deiner Frage aber hier noch eine andere Idee: portier doch einfach alles nach python. Sollte ja sicherlich auch machbar sein.
 
Nicht direkt eine Antwort zu deiner Frage aber hier noch eine andere Idee: portier doch einfach alles nach python. Sollte ja sicherlich auch machbar sein.

Ja, das habe ich auch überlegt. Allerdings kann ich das Programm dann nur in eine .exe kompilieren.
Das macht das Programm dann nur auf Windows ausführbar. Der Vorteil des jar files ist halt die Flexibilität für Windows und Linux.
Kompilieren muss ich es in jedem Fall, da der Benutzer kein python installiert hat...Java schon.
 
Schau dir mal GraalVM an.
Sieht ziemlich interessant aus auf den ersten Blick. Kennst du dich damit aus?
Sieht ja so aus, als könnte man damit einfach den Code vermischen. Die Frage ist, wie sieht das ganze aus, wenn ich nicht nur einen Hello World Befehl sondern etwas komplexes in etwas komplexen laufen lassen will.
Zum Beispiel eine python Klasse in einer Java Klasse laufen lassen
 
Sieht ziemlich interessant aus auf den ersten Blick. Kennst du dich damit aus?
Sieht ja so aus, als könnte man damit einfach den Code vermischen. Die Frage ist, wie sieht das ganze aus, wenn ich nicht nur einen Hello World Befehl sondern etwas komplexes in etwas komplexen laufen lassen will.
Zum Beispiel eine python Klasse in einer Java Klasse laufen lassen

Ja. Ich kenne mich damit aus. Alles kein Problem.
 
Ja. Ich kenne mich damit aus. Alles kein Problem.
Dann kannst du mir vielleicht weiterhelfen..
Ich habe GraalVM jetzt installiert und kleine Beispiele getestet. So weit, so gut.

Wenn ich nun aber den folgenden python Code (einfach nur eine Heatmap) in meine Java Klasse einbinden möchte, wie muss ich dann vorgehen? Wie gesagt, für einzelne Befehlszeilen verstehe ich das Vorgehen, aber mit dem import von librarys und so weiter wird es etwas komplizierter...

Python:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# sphinx_gallery_thumbnail_number = 2

rows = ["A", "B", "C", "D", "E", "F", "G", "H"]
columns = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]

                   
values = np.array([[0.0474, 0.0475, 0.047, 0.999, 0.0468, 0.0468, 0.0468, 0.047, 0.0471, 0.0467, 0.0472, 0.0481],
                    [0.0333, 0.1808, 0.3116, 1.114, 0.2361, 0.4748, 0.1035, 0.1822, 0.0885, 0.0898, 0.0954, 0.047],
                    [0.0968, 0.2463, 0.1723, 0.877, 0.2801, 0.5383, 0.1014, 0.0774, 0.1286, 0.0869, 0.0888, 0.0468],
                    [0.0984, 0.2303, 0.2679, 0.887, 0.2249, 0.2569, 0.0751, 0.0752, 0.0775, 0.0985, 0.0876, 0.0466],
                    [0.1367, 0.0805, 0.409, 1.002, 0.3857, 0.5032, 0.0951, 0.0839, 0.0861, 0.1636, 0.0923, 0.047],
                    [0.1517, 0.389,  0.1696, 0.987, 0.1472, 0.6806, 0.157, 0.0834, 0.5197, 0.143, 0.1894, 0.0467],
                    [0.0356, 0.4484, 0.3521, 0.956, 0.5312, 0.5037, 0.4991, 0.5523, 0.0966, 0.146, 0.0889, 0.047],
                    [0.0459, 0.0467, 0.0468, 0.899, 0.0465, 0.0469, 0.0465, 0.046, 0.047, 0.0466, 0.0467, 0.0464]])

                   

def heatmap(data, row_labels, col_labels, ax=None,
            cbar_kw={}, cbarlabel="", **kwargs):
    """
    Create a heatmap from a numpy array and two lists of labels.

    Arguments:
        data       : A 2D numpy array of shape (N,M)
        row_labels : A list or array of length N with the labels
                     for the rows
        col_labels : A list or array of length M with the labels
                     for the columns
    Optional arguments:
        ax         : A matplotlib.axes.Axes instance to which the heatmap
                     is plotted. If not provided, use current axes or
                     create a new one.
        cbar_kw    : A dictionary with arguments to
                     :meth:`matplotlib.Figure.colorbar`.
        cbarlabel  : The label for the colorbar
    All other arguments are directly passed on to the imshow call.
    """

    if not ax:
        ax = plt.gca()

    # Plot the heatmap
    im = ax.imshow(data, **kwargs)

    # Create colorbar
    cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw)
    cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom")

    # We want to show all ticks...
    ax.set_xticks(np.arange(data.shape[1]))
    ax.set_yticks(np.arange(data.shape[0]))
    # ... and label them with the respective list entries.
    ax.set_xticklabels(col_labels)
    ax.set_yticklabels(row_labels)

    # Let the horizontal axes labeling appear on top.
    ax.tick_params(top=True, bottom=False,
                   labeltop=True, labelbottom=False)

    # Rotate the tick labels and set their alignment.
    plt.setp(ax.get_xticklabels(), rotation=-30, ha="right",
             rotation_mode="anchor")

    # Turn spines off and create white grid.
    for edge, spine in ax.spines.items():
        spine.set_visible(False)

    ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True)
    ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True)
    ax.grid(which="minor", color="w", linestyle='-', linewidth=3)
    ax.tick_params(which="minor", bottom=False, left=False)

    return im, cbar


def annotate_heatmap(im, data=None, valfmt="$ {x:.2f}",
                     textcolors=["black", "white"],
                     threshold=None, **textkw):
    """
    A function to annotate a heatmap.

    Arguments:
        im         : The AxesImage to be labeled.
    Optional arguments:
        data       : Data used to annotate. If None, the image's data is used.
        valfmt     : The format of the annotations inside the heatmap.
                     This should either use the string format method, e.g.
                     "$ {x:.2f}", or be a :class:`matplotlib.ticker.Formatter`.
        textcolors : A list or array of two color specifications. The first is
                     used for values below a threshold, the second for those
                     above.
        threshold  : Value in data units according to which the colors from
                     textcolors are applied. If None (the default) uses the
                     middle of the colormap as separation.

    Further arguments are passed on to the created text labels.
    """

    if not isinstance(data, (list, np.ndarray)):
        data = im.get_array()

    # Normalize the threshold to the images color range.
    if threshold is not None:
        threshold = im.norm(threshold)
    else:
        threshold = im.norm(data.max())/2.

    # Set default alignment to center, but allow it to be
    # overwritten by textkw.
    kw = dict(horizontalalignment="center",
              verticalalignment="center")
    kw.update(textkw)

    # Get the formatter in case a string is supplied
    if isinstance(valfmt, str):
        valfmt = matplotlib.ticker.StrMethodFormatter(valfmt)

    # Loop over the data and create a `Text` for each "pixel".
    # Change the text's color depending on the data.
    texts = []
    for i in range(data.shape[0]):
        for j in range(data.shape[1]):
            kw.update(color=textcolors[im.norm(data[i, j]) > threshold])
            text = im.axes.text(j, i, valfmt(data[i, j], None), **kw)
            texts.append(text)

    return texts
   

fig, ax = plt.subplots()

im, cbar = heatmap(values, rows, columns, ax=ax,
                   cmap="Reds", cbarlabel="values")
texts = annotate_heatmap(im, valfmt="{x:.1f} t")

fig.tight_layout()
plt.show()
 

Zurück
Oben