# 5.3 Matrix

This folder contains examples of matrix manipulation, calculation and graphing with originpro package.
For matrix related functions in originpro, see matrixsheet.
For project related functions, see project.

## 3D Parametric Plot From Matrix

'''This sample shows how to plot parametric 3D surface from a matrix sheet.'''
import originpro as op
import numpy as np

# Generate torus mesh
angle = np.linspace(0, 2*np.pi, 32)
theta, phi = np.meshgrid(angle, angle)
r, R = .25, 1.
X = (R + r * np.cos(phi)) * np.cos(theta)
Y = (R + r * np.cos(phi)) * np.sin(theta)
Z = r * np.sin(phi)
arr_3D = np.stack([Z,X,Y], axis=0) # Stack X,Y,Z to get a 3D array

# Pass the data to a matrix sheet and plot
ms = op.new_sheet('m')
ms.from_np(arr_3D)

gp = op.new_graph(template='GLparafunc')
gp.rescale('z')

## Import NetCDF with Partial Settings

'''
This example shows importing from the web and to specify from Jan of each year
as well as doing proper longitude and latitude corrections.
'''
import originpro as op
mat = op.new_sheet('m')
#you can actually use URL in from_file
url = 'https://www.unidata.ucar.edu/software/netcdf/examples/tos_O1_2001-2002.nc'
#keep the connector so after the import, you can click on the icon to
#choose Options... to see open the dialog to see the details indicated by the sel string
mat.from_file(url, True, dctype='NetCDF', sel='NetCDF/tos[1:0|1-11][y#][x/2]')

## Matrix Dot Product using numpy

'''
This sample shows basic data transfer between Origin matrix and a NumPy array.
Make sure you've installed pandas before trying the following sample.
So to check for and install if needed, open the Script Window (Shift+Alt+3),
type the following and press Enter:
pip -chk pandas
'''
import numpy as np
import originpro as op

#integer matrix data
aa = np.array([	[1, 2, 3], [4, 5, 6] ])
bb = np.array([	[10,11], [20,21], [30,31] ])

#create a new hidden matrix book, and get the matrix sheet
ma=op.new_sheet('m')

#matrix sheet can hold a 3D array, shape and data type is automatically set
ma.from_np(aa)

#another sheet in same book
mb.from_np(bb)

#put result into 3rd sheet

#do the actual calculation using numpy
#here each sheet has only one matrix object, so we get it as 2d array
cc = np.dot(ma.to_np2d(), mb.to_np2d())
mc.from_np(cc)

## Use OpenCV to Load TIFF Images into Matrix Sheet

'''
This example shows how to import tif images into a 3d numpy array and then pass into Origin matrix book.
To install openCV (cv2), do the following from Script Window
pip install opencv-python
'''
import originpro as op
import numpy as np
import cv2

# import tifs into array
# Assume all images share the same dimesion
ImArray = np.array([])
for idx in range(7):
fname = op.path('e') + f'Samples\\Image Processing and Analysis\\myocyte{idx+1}.tif'
ms.show_image(True)