Awesome  Rust

Awesome Rust

1655961000

Femtovg: Antialiased 2D Vector Drawing Library for Miniquad

femtovg

Work in progress!

Antialiased 2D vector drawing library written in Rust. Ported from https://github.com/memononen/nanovg

Most of the implementation is the same as the original C code with some bug fixes, some features added and several parts have been made more Rust-y. Rendering is done via one OpenGl (ES) 3.0+ backend.

Screenshots

Demo

demo Run with cargo run --example demo

Breakout

breakout Run with cargo run --example breakout

SVG

svg Run with cargo run --example svg

Text

text Run with cargo run --example text

Features

  •  Anti-aliasing
  •  Bézier paths filling and stroking
  •  Solid color and image pattern fills and strokes
  •  Gradients - box, linear and radial
  •  Stroke width and miterlimit
  •  Stroke caps: butt, round and square
  •  Stroke joins: miter, round and bevel
  •  Fill rules - EvenOdd/NonZero
  •  Rectangle scissoring
  •  Composition modes (SourceOver, SourceIn, SourceOut, Atop, etc..)
  •  Global alpha
  •  Text filling and stroking
  •  Text shaping
  •  Text alignment: (left center right), (top, middle, alphabetic, bottom)
  •  Nearest font matching
  •  Path hit testing

In progress

Not supported

  •  Stroke dashing
  •  Path scissoring
  •  Custom shaders
  •  3D transforms
  •  OpenGl ES2 backend
  •  Color fonts

Download Details:
Author: smokku
Source Code: https://github.com/smokku/femtovg
License: Unknown, MIT licenses found

#rust #rustlang #game

What is GEEK

Buddha Community

Femtovg: Antialiased 2D Vector Drawing Library for Miniquad
Trevor  Russel

Trevor Russel

1617161400

Realtime Face Emotion Recognition using Transfer Learning in TensorFlow

The dataset which we’ll use is fer2013 which was published in International Conference on Machine Learning in 2013.
Let’s dive into the project, first open a new project using Jupyter Notebook or any other environment you like. First and foremost, importing the libraries

import tensorflow as tf 
import cv2 
import os
import matplotlib.pyplot as plt 
import pandas as pd
import numpy as np

OpenCV-Python is a library of Python bindings designed to solve computer vision problems.cv2.imread() method loads an image from the specified file. If the image cannot be read (because of the missing file, improper permissions, unsupported or invalid format) then this method returns an empty matrix. We can read the image through the following line of code:

img_array = cv2.imread(‘train/0/Training_3908.jpg’)

To check the size of the image, we use:

img_array.shape

The matplotlib function imshow() creates an image from a 2-dimensional numpy array. The image will have one square for each element of the array. The color of each square is determined by the value of the corresponding array element and the color map used by imshow().

plt.imshow(img_array)

Now we’ll create a variable containing the directory name and a list which will contain the names of the folders inside that directory. In my case, I have renamed the folder according to the emotion labels.

Datadirectory = "Training/"
Classes = ["0","1","2","3","4","5","6"]

The ImageNet dataset contains images of fixed size of 224*224 and have RGB channels but as fer2013 has images of size 48*48 so we’ll have to resize the images. To resize an image, OpenCV provides cv2.resize() function. cv2.cvtColor() method is used to convert an image from one color space to another.

img_size = 224 
new_array = cv2.resize(img_array, (img_size, img_size))
plt.imshow(cv2.cvtColor(new_array, cv2.COLOR_BGR2RGB))
plt.show()

The reason behind executing the above code is that we’re using transfer learning so for transfer learning if we want to use any deep learning classifier then these dimensions must be same. Now we’ll read all the images and will convert them to array.

training_Data = []
def create_training_Data():
  for category in Classes:
    path = os.path.join(Datadirectory, category)
    class_num = Classes.index(category)
    for img in os.listdir(path):
      try:
        img_array = cv2.imread(os.path.join(path, img))
        new_array = cv2.resize(img_array, (img_size, img_size))
        training_Data.append([new_array, class_num])
      except Exception as e:
        pass

Let’s call the function:

create_training_Data()

To make our deep learning architecture dynamic and robust, let’s shuffle the sequence:

import random
random.shuffle(training_Data)

Let’s separate the features and labels. We’ll use deep learning architecture MobileNet which takes 4 dimensions, so we’ll reshape the features list.

X = []
y = []
for features, label in training_Data:
  X.append(features)
  y.append(label)
X = np.array(X).reshape(-1, img_size, img_size, 3) 
# 3 is the channel for RGB

Among the best practices for training a Neural Network is to normalize your data to obtain a mean close to 0. Normalizing the data generally speeds up learning and leads to faster convergence. Let’s normalize the data before training

X =X/255.0

Now we’ll train our deep learning model using transfer learning

from tensorflow import keras
from tensorflow.keras import layers

Keras Applications are deep learning models that are made available alongside pre-trained weights. These models can be used for prediction, feature extraction, and fine-tuning. Here is a chart of some available models.

Now we’ll use MobileNetV2

model = tf.keras.applications.MobileNetV2()

Let’s change the base input

base_input = model.layers[0].input

As we want seven classes, so let’s cut down output

base_output = model.layers[-2].output

The dense layer is a neural network layer that is connected deeply, which means each neuron in the dense layer receives input from all neurons of its previous layer. The activation function is a mathematical “gate” in between the input feeding the current neuron and its output going to the next layer. It can be as simple as a step function that turns the neuron output on and off, depending on a rule or threshold. Here we’re using relu as activation function.

final_output = layers.Dense(128)(base_output) 
final_output = layers.Activation(‘relu’)(final_output) 
final_output = layers.Dense(64)(final_output)
final_output = layers.Activation(‘relu’)(final_output)
final_output = layers.Dense(7, activation=’softmax’)(final_output) 

Let’s create our new model.

new_model = keras.Model(inputs = base_input, outputs = final_output)

Compile defines the loss function, the optimizer, and the metrics. That’s all. It has nothing to do with the weights and you can compile a model as many times as you want without causing any problem to pre-trained weights. You need a compiled model to train (because training uses the loss function and the optimizer).

new_model.compile(loss=”sparse_categorical_crossentropy”, optimizer = “adam”, metrics = [“accuracy”])

Trains the model for 25 number of epochs.

new_model.fit(X, Y, epochs = 25)

Here is the code to save the model.

new_model.save(‘Final_model_95p07.h5’)

The below code is to test it using a live webcam.

import cv2 # pip install opencv-python
#pip install opencv-contrib-python full package
#from deepface import DeepFace #pip install deepface
path = "haarcascade_frontalface_default.xml"
font_scale = 1.5
font = cv2.FONT_HERSHEY_PLAIN
#set the rectangle background to white
rectangle_bgr = (255, 255, 255)
#make a black image
img = np.zeros((500, 500))
#set some text
text = "Some text in a box!"
# get the width and height of the text box
(text_width, text_height) = cv2.getTextSize(text, font, fontScale=font_scale, thickness=1)[0]
# set the text start position
text_offset_x = 10
text_offset_y = img.shape[0] - 25
#make the coords of the box with a small padding of two pixels
box_coords = ((text_offset_x, text_offset_y), (text_offset_x + text_width + 2, text_offset_y - text_height - 2))
cv2.rectangle(img, box_coords[0], box_coords[1], rectangle_bgr, cv2.FILLED)
cv2.putText(img, text, (text_offset_x, text_offset_y), font, fontScale=font_scale, color=(0, 0, 0), thickness=1)
cap = cv2.VideoCapture(1)
# Check if the webcam is opened correctly
if not cap.isOpened():
  cap = cv2.VideoCapture(0)
if not cap.isOpened():
  raise IOError("Cannot open webcam")
while True:
  ret, frame = cap.read()
  #eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
  faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
  gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  #print(faceCascade.empty())
  faces = faceCascade.detectMultiScale(gray,1.1,4)
  for x,y,w,h in faces:
    roi_gray = gray[y:y+h, x:x+w]
    roi_color = frame[y:y+h, x:x+w]
    cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
    facess = faceCascade.detectMultiScale(roi_gray)
    if len(facess) == 0:
      print("Face not detected")
    else:
      for (ex,ey,ew,eh) in facess:
        face_roi = roi_color[ey: ey+eh, ex:ex + ew] ## cropping the face
    
    final_image = cv2.resize(face_roi, (224,224))
    final_image = np.expand_dims(final_image,axis=0) ## need fourth dimension
    final_image = final_image/255.0
font = cv2.FONT_HERSHEY_SIMPLEX
Predictions = new_model.predict(final_image)
font_scale = 1.5
    font = cv2.FONT_HERSHEY_PLAIN
if(np.argmax(Predictions)==0):
      status = "Angry"
x1,y1,w1,h1 = 0,0,175,75
      #Draw black background rectangle
      cv2.rectangle(frame, (x1, x1), (x1 + w1, y1 + h1), (0,0,0), -1)
      #Addd text
      cv2.putText(frame, status, (x1 + int(w1/10), y1 + int(h1/2)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)
cv2.putText(frame, status,(100,150),font, 3,(0, 0, 255),2,cv2.LINE_4)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 0, 255))
elif (np.argmax(Predictions)==1):
      status = "Disgust"
x1,y1,w1,h1 = 0,0,175,75
      #Draw black background rectangle
      cv2.rectangle(frame, (x1, x1), (x1 + w1, y1 + h1), (0,0,0), -1)
      #Addd text
      cv2.putText(frame, status, (x1 + int(w1/10), y1 + int(h1/2)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)
cv2.putText(frame, status,(100,150),font, 3,(0, 0, 255),2,cv2.LINE_4)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 0, 255))
elif (np.argmax(Predictions)==2):
      status = "Fear"
x1,y1,w1,h1 = 0,0,175,75
      #Draw black background rectangle
      cv2.rectangle(frame, (x1, x1), (x1 + w1, y1 + h1), (0,0,0), -1)
      #Addd text
      cv2.putText(frame, status, (x1 + int(w1/10), y1 + int(h1/2)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)
cv2.putText(frame, status,(100,150),font, 3,(0, 0, 255),2,cv2.LINE_4)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 0, 255))
    
    elif (np.argmax(Predictions)==3):
      status = "Happy"
x1,y1,w1,h1 = 0,0,175,75
      #Draw black background rectangle
      cv2.rectangle(frame, (x1, x1), (x1 + w1, y1 + h1), (0,0,0), -1)
      #Addd text
      cv2.putText(frame, status, (x1 + int(w1/10), y1 + int(h1/2)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)
cv2.putText(frame, status,(100,150),font, 3,(0, 0, 255),2,cv2.LINE_4)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 0, 255))
elif (np.argmax(Predictions)==4):
      status = "Sad"
x1,y1,w1,h1 = 0,0,175,75
      #Draw black background rectangle
      cv2.rectangle(frame, (x1, x1), (x1 + w1, y1 + h1), (0,0,0), -1)
      #Addd text
      cv2.putText(frame, status, (x1 + int(w1/10), y1 + int(h1/2)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)
cv2.putText(frame, status,(100,150),font, 3,(0, 0, 255),2,cv2.LINE_4)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 0, 255))
elif (np.argmax(Predictions)==5):
      status = "Surprise"
x1,y1,w1,h1 = 0,0,175,75
      #Draw black background rectangle
      cv2.rectangle(frame, (x1, x1), (x1 + w1, y1 + h1), (0,0,0), -1)
      #Addd text
      cv2.putText(frame, status, (x1 + int(w1/10), y1 + int(h1/2)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)
cv2.putText(frame, status,(100,150),font, 3,(0, 0, 255),2,cv2.LINE_4)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 0, 255))
else:
      status = "Neutral"
x1,y1,w1,h1 = 0,0,175,75
      #Draw black background rectangle
      cv2.rectangle(frame, (x1, x1), (x1 + w1, y1 + h1), (0,0,0), -1)
      #Addd text
      cv2.putText(frame, status, (x1 + int(w1/10), y1 + int(h1/2)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,255), 2)
cv2.putText(frame, status,(100,150),font, 3,(0, 0, 255),2,cv2.LINE_4)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 0, 255))
cv2.imshow('Face Emotion Recognition', frame)
if cv2.waitKey(2) & 0xFF == ord('q'):
    break
cap.release()
cv2.destroyAllWindows()

Originally published by MUHAMMAD AZEEM RAO at Medium

#deep-learning #tensorflow #neural-networks #artificial-intelligence #facial-expressions

Dylan  Iqbal

Dylan Iqbal

1561523460

Matplotlib Cheat Sheet: Plotting in Python

This Matplotlib cheat sheet introduces you to the basics that you need to plot your data with Python and includes code samples.

Data visualization and storytelling with your data are essential skills that every data scientist needs to communicate insights gained from analyses effectively to any audience out there. 

For most beginners, the first package that they use to get in touch with data visualization and storytelling is, naturally, Matplotlib: it is a Python 2D plotting library that enables users to make publication-quality figures. But, what might be even more convincing is the fact that other packages, such as Pandas, intend to build more plotting integration with Matplotlib as time goes on.

However, what might slow down beginners is the fact that this package is pretty extensive. There is so much that you can do with it and it might be hard to still keep a structure when you're learning how to work with Matplotlib.   

DataCamp has created a Matplotlib cheat sheet for those who might already know how to use the package to their advantage to make beautiful plots in Python, but that still want to keep a one-page reference handy. Of course, for those who don't know how to work with Matplotlib, this might be the extra push be convinced and to finally get started with data visualization in Python. 

You'll see that this cheat sheet presents you with the six basic steps that you can go through to make beautiful plots. 

Check out the infographic by clicking on the button below:

Python Matplotlib cheat sheet

With this handy reference, you'll familiarize yourself in no time with the basics of Matplotlib: you'll learn how you can prepare your data, create a new plot, use some basic plotting routines to your advantage, add customizations to your plots, and save, show and close the plots that you make.

What might have looked difficult before will definitely be more clear once you start using this cheat sheet! Use it in combination with the Matplotlib Gallery, the documentation.

Matplotlib 

Matplotlib is a Python 2D plotting library which produces publication-quality figures in a variety of hardcopy formats and interactive environments across platforms.

Prepare the Data 

1D Data 

>>> import numpy as np
>>> x = np.linspace(0, 10, 100)
>>> y = np.cos(x)
>>> z = np.sin(x)

2D Data or Images 

>>> data = 2 * np.random.random((10, 10))
>>> data2 = 3 * np.random.random((10, 10))
>>> Y, X = np.mgrid[-3:3:100j, -3:3:100j]
>>> U = 1 X** 2 + Y
>>> V = 1 + X Y**2
>>> from matplotlib.cbook import get_sample_data
>>> img = np.load(get_sample_data('axes_grid/bivariate_normal.npy'))

Create Plot

>>> import matplotlib.pyplot as plt

Figure 

>>> fig = plt.figure()
>>> fig2 = plt.figure(figsize=plt.figaspect(2.0))

Axes 

>>> fig.add_axes()
>>> ax1 = fig.add_subplot(221) #row-col-num
>>> ax3 = fig.add_subplot(212)
>>> fig3, axes = plt.subplots(nrows=2,ncols=2)
>>> fig4, axes2 = plt.subplots(ncols=3)

Save Plot 

>>> plt.savefig('foo.png') #Save figures
>>> plt.savefig('foo.png',  transparent=True) #Save transparent figures

Show Plot

>>> plt.show()

Plotting Routines 

1D Data 

>>> fig, ax = plt.subplots()
>>> lines = ax.plot(x,y) #Draw points with lines or markers connecting them
>>> ax.scatter(x,y) #Draw unconnected points, scaled or colored
>>> axes[0,0].bar([1,2,3],[3,4,5]) #Plot vertical rectangles (constant width)
>>> axes[1,0].barh([0.5,1,2.5],[0,1,2]) #Plot horiontal rectangles (constant height)
>>> axes[1,1].axhline(0.45) #Draw a horizontal line across axes
>>> axes[0,1].axvline(0.65) #Draw a vertical line across axes
>>> ax.fill(x,y,color='blue') #Draw filled polygons
>>> ax.fill_between(x,y,color='yellow') #Fill between y values and 0

2D Data 

>>> fig, ax = plt.subplots()
>>> im = ax.imshow(img, #Colormapped or RGB arrays
      cmap= 'gist_earth', 
      interpolation= 'nearest',
      vmin=-2,
      vmax=2)
>>> axes2[0].pcolor(data2) #Pseudocolor plot of 2D array
>>> axes2[0].pcolormesh(data) #Pseudocolor plot of 2D array
>>> CS = plt.contour(Y,X,U) #Plot contours
>>> axes2[2].contourf(data1) #Plot filled contours
>>> axes2[2]= ax.clabel(CS) #Label a contour plot

Vector Fields 

>>> axes[0,1].arrow(0,0,0.5,0.5) #Add an arrow to the axes
>>> axes[1,1].quiver(y,z) #Plot a 2D field of arrows
>>> axes[0,1].streamplot(X,Y,U,V) #Plot a 2D field of arrows

Data Distributions 

>>> ax1.hist(y) #Plot a histogram
>>> ax3.boxplot(y) #Make a box and whisker plot
>>> ax3.violinplot(z)  #Make a violin plot

Plot Anatomy & Workflow 

Plot Anatomy 

 y-axis      

                           x-axis 

Workflow 

The basic steps to creating plots with matplotlib are:

1 Prepare Data
2 Create Plot
3 Plot
4 Customized Plot
5 Save Plot
6 Show Plot

>>> import matplotlib.pyplot as plt
>>> x = [1,2,3,4]  #Step 1
>>> y = [10,20,25,30] 
>>> fig = plt.figure() #Step 2
>>> ax = fig.add_subplot(111) #Step 3
>>> ax.plot(x, y, color= 'lightblue', linewidth=3)  #Step 3, 4
>>> ax.scatter([2,4,6],
          [5,15,25],
          color= 'darkgreen',
          marker= '^' )
>>> ax.set_xlim(1, 6.5)
>>> plt.savefig('foo.png' ) #Step 5
>>> plt.show() #Step 6

Close and Clear 

>>> plt.cla()  #Clear an axis
>>> plt.clf(). #Clear the entire figure
>>> plt.close(). #Close a window

Plotting Customize Plot 

Colors, Color Bars & Color Maps 

>>> plt.plot(x, x, x, x**2, x, x** 3)
>>> ax.plot(x, y, alpha = 0.4)
>>> ax.plot(x, y, c= 'k')
>>> fig.colorbar(im, orientation= 'horizontal')
>>> im = ax.imshow(img,
            cmap= 'seismic' )

Markers 

>>> fig, ax = plt.subplots()
>>> ax.scatter(x,y,marker= ".")
>>> ax.plot(x,y,marker= "o")

Linestyles 

>>> plt.plot(x,y,linewidth=4.0)
>>> plt.plot(x,y,ls= 'solid') 
>>> plt.plot(x,y,ls= '--') 
>>> plt.plot(x,y,'--' ,x**2,y**2,'-.' ) 
>>> plt.setp(lines,color= 'r',linewidth=4.0)

Text & Annotations 

>>> ax.text(1,
           -2.1, 
           'Example Graph', 
            style= 'italic' )
>>> ax.annotate("Sine", 
xy=(8, 0),
xycoords= 'data', 
xytext=(10.5, 0),
textcoords= 'data', 
arrowprops=dict(arrowstyle= "->", 
connectionstyle="arc3"),)

Mathtext 

>>> plt.title(r '$sigma_i=15$', fontsize=20)

Limits, Legends and Layouts 

Limits & Autoscaling 

>>> ax.margins(x=0.0,y=0.1) #Add padding to a plot
>>> ax.axis('equal')  #Set the aspect ratio of the plot to 1
>>> ax.set(xlim=[0,10.5],ylim=[-1.5,1.5])  #Set limits for x-and y-axis
>>> ax.set_xlim(0,10.5) #Set limits for x-axis

Legends 

>>> ax.set(title= 'An Example Axes',  #Set a title and x-and y-axis labels
            ylabel= 'Y-Axis', 
            xlabel= 'X-Axis')
>>> ax.legend(loc= 'best')  #No overlapping plot elements

Ticks 

>>> ax.xaxis.set(ticks=range(1,5),  #Manually set x-ticks
             ticklabels=[3,100, 12,"foo" ])
>>> ax.tick_params(axis= 'y', #Make y-ticks longer and go in and out
             direction= 'inout', 
              length=10)

Subplot Spacing 

>>> fig3.subplots_adjust(wspace=0.5,   #Adjust the spacing between subplots
             hspace=0.3,
             left=0.125,
             right=0.9,
             top=0.9,
             bottom=0.1)
>>> fig.tight_layout() #Fit subplot(s) in to the figure area

Axis Spines 

>>> ax1.spines[ 'top'].set_visible(False) #Make the top axis line for a plot invisible
>>> ax1.spines['bottom' ].set_position(( 'outward',10))  #Move the bottom axis line outward

Have this Cheat Sheet at your fingertips

Original article source at https://www.datacamp.com

#matplotlib #cheatsheet #python

Awesome  Rust

Awesome Rust

1655961000

Femtovg: Antialiased 2D Vector Drawing Library for Miniquad

femtovg

Work in progress!

Antialiased 2D vector drawing library written in Rust. Ported from https://github.com/memononen/nanovg

Most of the implementation is the same as the original C code with some bug fixes, some features added and several parts have been made more Rust-y. Rendering is done via one OpenGl (ES) 3.0+ backend.

Screenshots

Demo

demo Run with cargo run --example demo

Breakout

breakout Run with cargo run --example breakout

SVG

svg Run with cargo run --example svg

Text

text Run with cargo run --example text

Features

  •  Anti-aliasing
  •  Bézier paths filling and stroking
  •  Solid color and image pattern fills and strokes
  •  Gradients - box, linear and radial
  •  Stroke width and miterlimit
  •  Stroke caps: butt, round and square
  •  Stroke joins: miter, round and bevel
  •  Fill rules - EvenOdd/NonZero
  •  Rectangle scissoring
  •  Composition modes (SourceOver, SourceIn, SourceOut, Atop, etc..)
  •  Global alpha
  •  Text filling and stroking
  •  Text shaping
  •  Text alignment: (left center right), (top, middle, alphabetic, bottom)
  •  Nearest font matching
  •  Path hit testing

In progress

Not supported

  •  Stroke dashing
  •  Path scissoring
  •  Custom shaders
  •  3D transforms
  •  OpenGl ES2 backend
  •  Color fonts

Download Details:
Author: smokku
Source Code: https://github.com/smokku/femtovg
License: Unknown, MIT licenses found

#rust #rustlang #game

NetworkViz.jl: Julia Interface to visualize Graphs

NetworkViz

A Julia module to render graphs in 3D using ThreeJS tightly coupled with LightGraphs.

Install

In a Julia REPL, run:

Pkg.add("NetworkViz")

Graph Algorithms Used

Graph Primitives

NodeProperty

The NodeProperty type stores the properties of each node in the graph. It stores the following properties :

  • color : It is a Colors array that stores the colors of all the nodes in the graph.
  • size : Size of the node. eg : 0.2.
  • shape : Shape of the node. Can be 0 or 1. 0 - Square, 1 - Circle.

EdgeProperty

The EdgeProperty type stores the properties of each edge in the graph. It stores the following properties :

  • color : It is a hex string that stores the color of the edges.
  • width : Thickness of the edges. eg : 1.5.

Visualizing Graphs

The drawGraph function can be used to draw the graphs in 2D or 3D with nodes having different colors. It can accept LightGraphs.Graph and LightGraphs.Digraph types. drawGraph can be used to draw graphs from adjacency matrices also. The function accepts an additional kwargs node::NodeProperty, edge::EdgeProperty, and z. If z=1, it draws a 3D graph. If z=0, a 2D visualization of the graph is drawn. node and edge determines the properties of nodes and edges respectively.

Usage :

g = CompleteGraph(10)
c = Color[parse(Colorant,"#00004d") for i in 1:nv(g)]
n = NodeProperty(c,0.2,0)
e = EdgeProperty("#ff3333",1)
drawGraph(g,node=n,edge=e,z=1) #Draw using a Graph object (3D).

am = full(adjacency_matrix(g))
drawGraph(am,node=n,edge=e,z=0) #Draw using an adjacency matrix (2D).

dgraph = bfs_tree(g,1)
drawGraph(dgraph,z=1) #Draw a Digraph.

Utility Functions

  • addEdge(g::Graph,node1::Int,node2::Int,z=1) - Add a new edge node1-node2 and redraws the graph. z toggles 2D-3D conversion. Fails silently if an already existing node is added again.
  • removeEdge(g::Graph,node1::Int,node2::Int,z=1) - Removes the edge node1-node2 if it exists and redraws the graph. z toggles 2D-3D conversion.
  • addNode(g::Graph,z=1) - Adds a new node to the graph. z toggles 2D-3D conversion.
  • removeNode(g::Graph,node::Int,z=1) - Removes node if it exists and redraws the graph. z toggles 2D-3D conversion.

Examples

#Run this code in Escher
using NetworkViz
using LightGraphs
main(window) = begin
  push!(window.assets, "widgets")
  push!(window.assets,("ThreeJS","threejs"))
  g = CompleteGraph(10)
  drawGraph(g)
end

The above code produces the following output :

alt tag

Here is another example with a code-mirror where functions can be typed in. Depending on the LightGraphs function used, 2D as well as 3D graphs are drawn. You can see the working demo here.

You can find many other examples in the examples/ folder.

Acknowledgement

IainNZ for the original Spring-Embedder code. (Taken from GraphLayout.jl).

Download Details:

Author: Abhijithanilkumar
Source Code: https://github.com/abhijithanilkumar/NetworkViz.jl 
License: View license

#julia #graphs #interface 

Brandon  Adams

Brandon Adams

1625629740

What is a Library? Using Libraries in Code Tutorial | C Library Examples

In this tutorial, we’ll be talking about what a library is and how they are useful. We will be looking at some examples in C, including the C Standard I/O Library and the C Standard Math Library, but these concepts can be applied to many different languages. Thank you for watching and happy coding!

Need some new tech gadgets or a new charger? Buy from my Amazon Storefront https://www.amazon.com/shop/blondiebytes

Also check out…
What is a Framework? https://youtu.be/HXqBlAywTjU
What is a JSON Object? https://youtu.be/nlYiOcMNzyQ
What is an API? https://youtu.be/T74OdSCBJfw
What are API Keys? https://youtu.be/1yFggyk--Zo
Using APIs with Postman https://youtu.be/0LFKxiATLNQ

Check out my courses on LinkedIn Learning!
REFERRAL CODE: https://linkedin-learning.pxf.io/blondiebytes
https://www.linkedin.com/learning/instructors/kathryn-hodge

Support me on Patreon!
https://www.patreon.com/blondiebytes

Check out my Python Basics course on Highbrow!
https://gohighbrow.com/portfolio/python-basics/

Check out behind-the-scenes and more tech tips on my Instagram!
https://instagram.com/blondiebytes/

Free HACKATHON MODE playlist:
https://open.spotify.com/user/12124758083/playlist/6cuse5033woPHT2wf9NdDa?si=VFe9mYuGSP6SUoj8JBYuwg

MY FAVORITE THINGS:
Stitch Fix Invite Code: https://www.stitchfix.com/referral/10013108?sod=w&som=c
FabFitFun Invite Code: http://xo.fff.me/h9-GH
Uber Invite Code: kathrynh1277ue
Postmates Invite Code: 7373F
SoulCycle Invite Code: https://www.soul-cycle.com/r/WY3DlxF0/
Rent The Runway: https://rtr.app.link/e/rfHlXRUZuO

Want to BINGE?? Check out these playlists…

Quick Code Tutorials: https://www.youtube.com/watch?v=4K4QhIAfGKY&index=1&list=PLcLMSci1ZoPu9ryGJvDDuunVMjwKhDpkB

Command Line: https://www.youtube.com/watch?v=Jm8-UFf8IMg&index=1&list=PLcLMSci1ZoPvbvAIn_tuSzMgF1c7VVJ6e

30 Days of Code: https://www.youtube.com/watch?v=K5WxmFfIWbo&index=2&list=PLcLMSci1ZoPs6jV0O3LBJwChjRon3lE1F

Intermediate Web Dev Tutorials: https://www.youtube.com/watch?v=LFa9fnQGb3g&index=1&list=PLcLMSci1ZoPubx8doMzttR2ROIl4uzQbK

GitHub | https://github.com/blondiebytes

Twitter | https://twitter.com/blondiebytes

LinkedIn | https://www.linkedin.com/in/blondiebytes

#blondiebytes #c library #code tutorial #library