Python Bridge Examples

From ZCubes Wiki
Jump to navigation Jump to search

Python Examples

Provide these examples in the Z Code Window. Connect to Language Kernal with Jupyter (for example: http://localhost:8888 (as well as a token for the session) into the Z Config Panel. In ZAP, CTRL+SHIFT+CLICK on any language (server) automatically connects to an instance of Kernal, and no token is required.

Example 1:

def prime(x, y):
    prime_list = []
    for i in range(x, y):
        if i == 0 or i == 1:
            continue
        else:
            for j in range(2, int(i/2)+1):
                if i % j == 0:
                    break
            else:
                prime_list.append(i)
    return prime_list


# Driver program
starting_range = 2
ending_range = 7
lst = prime(starting_range, ending_range)
if len(lst) == 0:
    print("There are no prime numbers in this range")
else:
    print("The prime numbers in this range are: ", lst)

prime(2,40)

print(prime(2,40))

print(prime(2,400))

Example 2:

Demonstrates how to include a python library.

import math
print(34+435)
math.sin(34)

Exmaple 3:

// draw graph with python
// trying to draw a graph

# importing the required module
import matplotlib.pyplot as plt

# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]

# plotting the points 
plt.plot(x, y)

# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')

# giving a title to my graph
plt.title('My first graph!')

# function to show the plot
plt.show()

Example 4:

From [[1]]

Install python libraries using pip on the server machine (or local desktop as relevant).

Such as:

pip install pillow

pip install numpy

pip install matplotlib

import matplotlib.pyplot as plt

def draw_fractal(ax, levels=4, x=0, y=0, size=1):
    if levels == 0:
        ax.add_patch(plt.Rectangle((x, y), size, size, color='navy'))
    else:
        size3 = size / 3
        for i in range(3):
            for j in range(3):
                if (i + j) % 2 == 0:
                    draw_fractal(ax, levels - 1, x + i * size3, y + j * size3, size3)

fig, ax = plt.subplots()
ax.set_aspect(1)
ax.axis('off')
draw_fractal(ax)
plt.show()

More Python Examples

Below examples show basic examples to more advanced ones with data transfer etc.

In Kernel Bridge Coding, the following two syntax are used to do prepile (before sending to execution) and postpile (after transpiling (for client languages) (or) server execution of the code (for server languages))

[= =] // prepile

{= =} // postpile


Example 1:

# This program adds two numbers

num1 = 1.5
num2 = 6.3

# Add two numbers
sum = num1 + num2

# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

The following may give errors if libraries are not installed, like numpy etc.

import numpy as np
import matplotlib.pyplot as plt
 
# setting parameters (these values can be changed)
xDomain, yDomain = np.linspace(-2,1.5,500), np.linspace(-2,2,500)
bound = 2
power = 2             # any positive floating point value (n)
max_iterations = 50   # any positive integer value
colormap = 'magma'    # set to any matplotlib valid colormap
 
 
# computing 2-d array to represent the mandelbrot-set
iterationArray = []
for y in yDomain:
    row = []
    for x in xDomain:
        c = complex(x,y)
        z = 0
        for iterationNumber in range(max_iterations):
            if(abs(z) >= bound):
                row.append(iterationNumber)
                break
            else: z = z**power + c
        else:
            row.append(0)
 
    iterationArray.append(row)
 
# plotting the data
ax = plt.axes()
plt.rc('text', usetex = True)   # adding this line so that tex can be used
ax.set_aspect('equal')
graph = ax.pcolormesh(xDomain, yDomain, iterationArray, cmap = colormap)
plt.colorbar(graph)
plt.xlabel("Real-Axis")
plt.ylabel("Imaginary-Axis")
plt.title('Multibrot set for $z_{{new}} = z^{{{}}} + c$'.format(power))
plt.gcf().set_size_inches(5,4)
plt.show()
		

--

print(num1-num2)

Example 2: Postpile Execution

This examples shows postpile computation of print("{= s1="+SIN(sum)+"=}"), which prints out the string

{= s1=SIN(sum) =}

and this results in the code between {= and =} to execute in Z to achieve postpile execution.

# This program adds two numbers

num1 = 1.5
num2 = 6.3

# Add two numbers
sum = num1 + num2
print("{= s1="+SIN(sum)+"=}")


// Shows post processing of python into Z.
# This program adds two numbers

num1 = 1.5
num2 = 6.3

# Add two numbers
sum = num1 + num2
print("{= s1=SIN(" + str(sum) + ")=}")


#gives ansi


# importing the modules
from bokeh.sampledata.iris import flowers
from bokeh.plotting import figure, show, output_file

# file to save the model
output_file("gfg.html")

# instantiating the figure object
graph = figure(title="Iris Visualization")

# labeling the x-axis and the y-axis
graph.xaxis.axis_label = "Length (in cm)"
graph.yaxis.axis_label = "Width (in cm)"

# plotting for setosa petals
x = flowers[flowers["species"] == "setosa"]["petal_length"]
y = flowers[flowers["species"] == "setosa"]["petal_width"]
marker = "circle_cross"
line_color = "blue"
fill_color = "lightblue"
fill_alpha = 0.4
size = 10
legend_label = "setosa petals"
graph.scatter(x, y,
			marker=marker,
			line_color=line_color,
			fill_color=fill_color,
			fill_alpha=fill_alpha,
			size=size,
			legend_label=legend_label)

# plotting for setosa sepals
x = flowers[flowers["species"] == "setosa"]["sepal_length"]
y = flowers[flowers["species"] == "setosa"]["sepal_width"]
marker = "square_cross"
line_color = "blue"
fill_color = "lightblue"
fill_alpha = 0.4
size = 10
legend_label = "setosa sepals"
graph.scatter(x, y,
			marker=marker,
			line_color=line_color,
			fill_color=fill_color,
			fill_alpha=fill_alpha,
			size=size,
			legend_label=legend_label)

# plotting for versicolor petals
x = flowers[flowers["species"] == "versicolor"]["petal_length"]
y = flowers[flowers["species"] == "versicolor"]["petal_width"]
marker = "circle_cross"
line_color = "yellow"
fill_color = "lightyellow"
fill_alpha = 0.4
size = 10
legend_label = "versicolor petals"
graph.scatter(x, y,
			marker=marker,
			line_color=line_color,
			fill_color=fill_color,
			fill_alpha=fill_alpha,
			size=size,
			legend_label=legend_label)

# plotting for versicolor sepals
x = flowers[flowers["species"] == "versicolor"]["sepal_length"]
y = flowers[flowers["species"] == "versicolor"]["sepal_width"]
marker = "square_cross"
line_color = "yellow"
fill_color = "lightyellow"
fill_alpha = 0.4
size = 10
legend_label = "versicolor sepals"
graph.scatter(x, y,
			marker=marker,
			line_color=line_color,
			fill_color=fill_color,
			fill_alpha=fill_alpha,
			size=size,
			legend_label=legend_label)

# plotting for virginica petals
x = flowers[flowers["species"] == "virginica"]["petal_length"]
y = flowers[flowers["species"] == "virginica"]["petal_width"]
marker = "circle_cross"
line_color = "red"
fill_color = "lightcoral"
fill_alpha = 0.4
size = 10
legend_label = "virginica petals"
graph.scatter(x, y,
			marker=marker,
			line_color=line_color,
			fill_color=fill_color,
			fill_alpha=fill_alpha,
			size=size,
			legend_label=legend_label)

# plotting for virginica sepals
x = flowers[flowers["species"] == "virginica"]["sepal_length"]
y = flowers[flowers["species"] == "virginica"]["sepal_width"]
marker = "square_cross"
line_color = "red"
fill_color = "lightcoral"
fill_alpha = 0.4
size = 10
legend_label = "virginica sepals"
graph.scatter(x, y,
			marker=marker,
			line_color=line_color,
			fill_color=fill_color,
			fill_alpha=fill_alpha,
			size=size,
			legend_label=legend_label)

# relocating the legend table to
# avoid abstruction of the graph
graph.legend.location = "top_left"

# displaying the model
show(graph)