Sunday, November 3, 2024

Installing xAct (Mac)

Download from http : www.xact.es .
Before unpack the tar/tgz file, remove attributes with
xattr -c xAct_1.x.x.tgz
then place the unpacked folder to

~/Library/Wolfram/Applications

Sunday, December 25, 2022

Quick note on installing FORM

Quick note on installing FORM

Install WSL

Manual installation steps for older versions of WSL | Microsoft Learn
Open PowerShell with administrator permission, enable windows subsystem:

dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

Enable VM feature:

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

Download WSL2: https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi
Then install Ubuntu: https://www.microsoft.com/store/apps/9PN20MSR04DW

Install FORM by Homebrew

Installation · vermaseren/form Wiki (github.com)
Open Ubuntu terminal, install Homebrew:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Install FORM:

brew install tueda/form/form

Tuesday, July 7, 2020

Python Notes

PythonNotes

Output

In [2]:
print(123)
123

printf syntax

In [12]:
print("%s" % ("Hello"))
print("%d , %03d" % (1,1))
print("%f, %.3f " % (0.2,0.2))
print("%e, %E" % (300000000,300000000))
print("%.1e, %.0E" % (300000000,300000000))
Hello
1 , 001
0.200000, 0.200 
3.000000e+08, 3.000000E+08
3.0e+08, 3E+08

Format string syntax

In [13]:
print("{x:.2f}" .format(x=64.89999)) #{[name a variable]:[assigns a format]}
64.90

Type Conversion

In [16]:
a = 1
b = 1.0
c = "c"
print(type(a))
print(type(b))
print(type(c))
<class 'int'>
<class 'float'>
<class 'str'>
In [23]:
print(type( str(a) ))
print(type( int(b) ))

print(round(1.89))
print(int(round(1.45)))
<class 'str'>
<class 'int'>
2
1

Complex Number

In [24]:
u = 24 + 2j
In [26]:
u.real
Out[26]:
24.0
In [27]:
u.imag
Out[27]:
2.0
In [28]:
u.conjugate()
Out[28]:
(24-2j)

Differentiation and Integration

In [7]:
# displacement = u*t + 1/2*a*t^2; velocity = u + a*t; acceleration = a
from sympy import *
t,a,u=symbols("t a u") # to make python treat those alphabet as symbolic variables
s = u*t+Rational(1,2)*a*t**2
ds= diff(s,t) #1st deriative
print("v = %s" % (ds))
dds = diff(s,t,t) #2nd derivative
print("a = %s" % (dds))
v = a*t + u
a = a
In [8]:
s_ = integrate(ds, t)
print("s = %s" % (s_))
s = a*t**2/2 + t*u
In [9]:
#insert numbers in symbolic expression
v = lambdify([t,u,a], ds)
v(t=1,u=1,a=9.81)
Out[9]:
10.81

Solving Equations

In [15]:
from sympy import solve
y,k,x = symbols("y k x")
y = x+1 
solve(y,x) # solve for x on x+1=0
Out[15]:
[-1]
In [16]:
solve(y<3) # solve for x on x+1<3
Out[16]:
$\displaystyle -\infty < x \wedge x < 2$
In [19]:
#do substitution by expression.subs([term], [variable])
print("x+1 = %s when x = 1" % (y.subs(x, 1)))
x+1 = 2 when x = 1

Input

In [183]:
#Reading Keyboard Input
u = input("enter u=...") # use raw_input() for python 2.x
print("I just received %s" % u)
enter u=...hello
I just received hello
In [191]:
#assigning object with user input
p = eval(input("type what you what: "))
print(p)
print(type(p))

q = eval(input("type what you what: "))
print(q)
print(type(q))
type what you what: 1+5
6
<class 'int'>
type what you what: [1,2,3]
[1, 2, 3]
<class 'list'>
In [194]:
#Reading user input as part of code
string = input("type you code: ")
exec(string)
type you code: for i in range(0,5):print(i)
0
1
2
3
4
In [ ]:
#Reading files
data = open('path/fileName.fileType', 'r') #reading line by line
for line in data:
    #operations for data

#or
line = data.readlines() 
'''
which is the same as 
line = []
for l in data:
    line.append(l)
    
and 

line = [l for l in data]
'''
In [ ]:
#Other ways to read a file
#1.
data = open('file.txt', 'r')
for line in data:
    #do something
data.close()
#2.
with open('file.txt', 'r') as data:
    for line in data:
        #do something; no need to close the file
#3.
data = open('file.txt', 'r')
while True:
    line = data.readline()
    if not line:
        break
    #do something
In [ ]:
# Writing data to a file
data = open('file.txt', 'w')
data.write("your data")
data.close()

Operations

While Loop

In [28]:
a = 0
b = 10
while a <= 7 and b != 0:
    print("a = %d, b = %d" % (a,b))
    a += 1
    b -= 1
    if a == 7:
        b == 0
a = 0, b = 10
a = 1, b = 9
a = 2, b = 8
a = 3, b = 7
a = 4, b = 6
a = 5, b = 5
a = 6, b = 4
a = 7, b = 3

For Loop

In [55]:
whatever = [1,2,3,4,5,6]
for itemsInWhatever in whatever:
    print(itemsInWhatever)
1
2
3
4
5
6
In [61]:
listForEx = [0]*3 #create a list with 3 zeros. i.e. [0,0,0]
for i in range(-10, 20, 5): #range(start, stop, step)
    listForEx.append(i)
print(listForEx)
[0, 0, 0, -10, -5, 0, 5, 10, 15]

String Opeation

In [201]:
#splitting a string
string = "1 2 3 4 5"
words = string.split()
print(words)
['1', '2', '3', '4', '5']

Error Exception

In [202]:
try:
    #do something that may have errors. e.g. opening a file
    file = open('IAmNotExists.txt','r')
except:
    print("It doesn't exist")
It doesn't exist
In [203]:
#if weren't use exception...
file = open('IAmNotExists.txt','r')
print("It really doesn't exit")
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-203-9b3c8838629f> in <module>
      1 #if weren't use exception...
----> 2 file = open('IAmNotExists.txt','r')
      3 print("It really doesn't exit")

FileNotFoundError: [Errno 2] No such file or directory: 'IAmNotExists.txt'
In [207]:
#Exeption for specific errors
try:
    #do something
    list = [1,2]
    print(list[int(input())])
except IndexError:
    print("Don't have such value")
except ValueError:
    print("Please input number")

print("--------------------------------")
try:
    #do something
    list = [1,2]
    print(list[int(input())])
except IndexError:
    print("Don't have such value")
except ValueError:
    print("Please input number")
    
print("--------------------------------")
try:
    #do something
    list = [1,2]
    print(list[int(input())])
except IndexError:
    print("Don't have such value")
except ValueError:
    print("Please input number")
3
Don't have such value
--------------------------------
a
Please input number
--------------------------------
0
1
In [215]:
#Raising Exception
try:
    l = [1,2]
    a = input()
    print(l[int(a)])
          
except IndexError:
    raise IndexError\
        ("Don't have such value")
if int(a) < 0:
    raise ValueError("Don't do that")
-1
2
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-215-d0dcdeb9390a> in <module>
      9         ("Don't have such value")
     10 if int(a) < 0:
---> 11     raise ValueError("Don't do that")

ValueError: Don't do that
In [216]:
#more firendly way
try:
    l = [1,2]
    a = input()
    print(l[int(a)])
          
except IndexError as e:
    print(e)
3
list index out of range

Data Structures

List

In [44]:
C = [1,2,3,4,5,6,7] #position: [0,1,2,3,4,and so on]
print(C)
for items in C:
    print(items)
[1, 2, 3, 4, 5, 6, 7]
1
2
3
4
5
6
7
In [45]:
#add an element in the end of the list
C.append(8)
C
Out[45]:
[1, 2, 3, 4, 5, 6, 7, 8]
In [41]:
#adding two lists
C += [1,2,3] # same as C = C + [1,2,3]
C
Out[41]:
[1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3]
In [46]:
#insert an element by assign a position for it
C.insert(2, 100) #assign 100 to position 2
C
Out[46]:
[1, 2, 100, 3, 4, 5, 6, 7, 8]
In [47]:
#delete an element such at position 2
del C[2]
C
Out[47]:
[1, 2, 3, 4, 5, 6, 7, 8]
In [48]:
#get the length of the list
len(C)
Out[48]:
8
In [49]:
#get the index of an element
C.index(7) #element 7 locates at position 6
Out[49]:
6
In [51]:
#Is 9 in the list?
print(9 in C)
#Is 1 in the list?
print(1 in C)
False
True
In [52]:
''' PYTHON ALLOWS NEGATIVE INDEX! '''
#negative index = index starting from the right
C[-1] == C[len(C)-1]
Out[52]:
True
In [53]:
#nameing elements of the list
a,b,c,d,e,f,g,h = C
print("%d,%d,%d,%d,%d,%d,%d,%d" % (a,b,c,d,e,f,g,h))
1,2,3,4,5,6,7,8
In [62]:
#another way to create a list
D = [1+i for i in range(3)]
D
Out[62]:
[1, 2, 3]
In [63]:
#operating two lists at the same time
list1 = [1,2,3,4]
list2 = [7,8,9]
for elementFrom1, elementFrom2 in zip(list1, list2):
    print("%d, %d" % (elementFrom1, elementFrom2))
1, 7
2, 8
3, 9
In [107]:
#nested list (aka. a table)
'''
1 2 3 
4 5 6
'''
R = [1,2,3]
C = [4,5,6]
table1 = [R,C]
for r, c in zip(R,C):
    print("%d %d"%(r,c))

print("------------------------------------")
    
for r in range(0, 3):
    for c in range (0, 3):
        if c == 2:
            print(table1[r-1][c-1], end="\n")
        else:
            print(table1[r-1][c-1], end="")
        
1 4
2 5
3 6
------------------------------------
645
312
645
In [115]:
table2=[[row, column] for row, column in zip(R, C)]
import pprint
pprint.pprint(table2)
[[1, 4], [2, 5], [3, 6]]
In [143]:
#example 
L = []
L.append([1,2,3])
L.append([4])
L.append([5,6,7,8,9])

#method 1
for i in range(len(L)):
    for j in range(len(L[i])):
        print(L[i][j])
print("-----------------")
#method 2
for l in L:
    for LElement in l:
        print(LElement)
1
2
3
4
5
6
7
8
9
-----------------
1
2
3
4
5
6
7
8
9
for sublist1 in somelist: for sublist2 in sublist1: for sublist3 in sublist2: ...so on
In [126]:
#reading sublists
P = [0,1,2,3,4,5,6,7,8]
print(P[2:]) #print sublist such start at position 2 to the end of the list
print(P[2:4])#print sublist such start at position 2 and end up with position 4-1 (i.e. position 3)
print(P[:4])#print sublist such start at the begining of the list and end up with position 4-1
print(P[:])#the whole lsit
print(P[1:-2])#allow negative index
[2, 3, 4, 5, 6, 7, 8]
[2, 3]
[0, 1, 2, 3]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6]

Tuples

In [149]:
t = (1, 2, 3, "a", "b", "c")
for element in t:
    print(element)
1
2
3
a
b
c
In [150]:
#adding tuples
t += (-1,-2)
print(t)
(1, 2, 3, 'a', 'b', 'c', -1, -2)
In [220]:
#indexing
print(t[0])
print(t[2:])
1
(3, 'a', 'b', 'c', -1, -2)

Functions

In [162]:
#define a function
def function(data):
    return "I received "+str(data)

print(function("a apple"))
print(function(100))
I received a apple
I received 100
In [ ]:
#Global Variable and Local Variable
In [165]:
imAGlobalVariable = 10
def abc():
    imALocalVariable = 100
    print("I can read global variable %d" % imAGlobalVariable)
abc()
print("I can read global variable %d but I cannot read loval variable in function abc" % (imAGlobalVariable))
I can read global variable 10
I can read global variable 10 but I cannot read loval variable in function abc
In [173]:
f = 0
def plusOne():
    f = 1 #this is a 'new' local variable
    print("f = %d inside function plusOne" % f)

plusOne()
print("f = %d outside function plusOne" % f)
f = 1 inside function plusOne
f = 0 outside function plusOne
In [175]:
f = 0
def plusOne():
    global f
    f = 1 #this is the global variable
    print("f = %d inside function plusOne" % f)

plusOne()
print("f = %d outside function plusOne" % f)
f = 1 inside function plusOne
f = 1 outside function plusOne
In [177]:
#defaulting parameters of function
def summation(input1, input2, input3 = 100):
    return input1 + input2 + input3

print(summation(1,2)) #1+2+100
print(summation(1,2,3)) #1+2+3
103
6
In [179]:
#Lambda Function
f = lambda x: x+1
'''
which is the same as 
def f(x):
    return x+1
'''
print(f(1))
2

Modules

In [217]:
#import xxx, where xxx is a module
#e.g.
import math
print(math.factorial(3))
'''
same as
from math import factorial
print(factorial(3))

'''
6
In [ ]:
#supposed there is a module named "IAmAFile" with functions named "abc" and "efg"
import IAmAFile #import both functions "abc" and "efg"
from IAmAFile import * #import both functions "abc" and "efg"
from IAmAFile import abc #import function "abc"
In [219]:
#Test Block

def f1():
    return "I am a function in a module"

if __name__ == "__main__":
    #do anything
    print("Testing Testing...")
    print(f1())
Testing Testing...
I am a function in a module

Plotting

Vector

In [ ]:
 

Arrays

In [236]:
#numberical arrays
import numpy as np
ls = [1,2,3,4,5] # a list
n = np.array(ls) # convert a list to an array
print(n)
zn = np.zeros(3) # create an array with length of three and filled with zeros: [0 0 0]
print(zn)
z = np.linspace(1, 5, 10) # create an array with length of 10 and filled with x in [1,5] (uniformly distributed)
print(z)
[1 2 3 4 5]
[0. 0. 0.]
[1.         1.44444444 1.88888889 2.33333333 2.77777778 3.22222222
 3.66666667 4.11111111 4.55555556 5.        ]

Curve Plotting

In [269]:
#Matlab-style plotting
import numpy as np
import matplotlib.pyplot as plt
from past.builtins import xrange #for python3

def function(x):
    return x**2+1

x = np.linspace(0, 5, 100) # 100 points lay on [0, 5]
y = np.zeros(len(x)) # setting y-axis  
for i in xrange(len(x)):
    y[i] = function(x[i])
#same as y=function(X)
plt.plot(x, y)
plt.xlabel("x")
plt.ylabel("y")
plt.legend(["x^2+1"])
plt.title("Demo")
plt.axis([0, 5, 0, 50]) #[x min, x max, y min, y max]
plt.savefig("picture.png") #generate PNG
plt.show()
In [284]:
#plotting multiple curves
def function1(x):
    return x**2
def function2(x):
    return x+1

x = np.linspace(0, 5, 100)
y1 = function1(x)
y2 = function2(x)

plt.plot(x, y1, "r-") # 'r' = red, '-' = line
plt.plot(x, y2, "bo")
plt.show()
In [287]:
#putting multiple plots in one figure
plt.figure()
plt.subplot(1, 2, 1) # (rows, cloumns, row-wise counter)
x = np.linspace(0, 5, 100)
y1 = function1(x)
y2 = function2(x)
plt.plot(x, y1, "r-") # 'r' = red, '-' = line
plt.plot(x, y2, "bo")

plt.subplot(1, 2, 2)
x = np.linspace(0, 5, 100) # 100 points lay on [0, 5]
y = np.zeros(len(x)) # setting y-axis  
y = function(x)
plt.plot(x, y)

plt.show()
In [9]:
#Plotting with SciTools and Easyviz
from scitools.std import *
import numpy as np

def f(x):
    return x*2+x+2
x = np.linspace(0, 5, 100)
y = f(x)
plot(x,y, '-')
#fine
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-9-e9033a3d685a> in <module>
      1 #Plotting with SciTools and Easyviz
----> 2 from scitools.std import *
      3 import numpy as np
      4 
      5 def f(x):

ModuleNotFoundError: No module named 'scitools.std'
In [3]:
#Making Animation

Dictionaries

In [4]:
#Making Dictionaries 
dic = {"tom": 100, "jerry": 200}
print(dic["tom"])
#or
dic2 = dict(Tom=100, Jerry=200)
print(dic2["Jerry"])

print(dic)
100
200
{'tom': 100, 'jerry': 200}
In [ ]:
#Operation 

Class

In [25]:
#define a class
class IamAClass:
    def __init__(self, a):#__init__ will be called when writing A = IamAClass(3)
        self.a = a
    def output(self):
        print(self.a)

A = IamAClass(3)
A.output()
print(A.a)
3
3
In [31]:
#The Call Special Method
class JustAClass:
    def __call__(self, a):
        return a+1
In [ ]: