Skip to content

Instantly share code, notes, and snippets.

@NP-chaonay
Last active September 10, 2020 13:51
Show Gist options
  • Save NP-chaonay/62f4186910a8891b2a5f8878aef85133 to your computer and use it in GitHub Desktop.
Save NP-chaonay/62f4186910a8891b2a5f8878aef85133 to your computer and use it in GitHub Desktop.
Python Initialization for Academic Usage
#!/usr/bin/env python3
# Name: Python Initialization for Academic Usage
# Description: Python Initialization for Academic Usage
# Author: NP-chaonay (Nuttapong Punpipat)
# Version: Unversioned
# Version Note: N/A
# Revised Date: 2020-09-10 13:51 (UTC)
# License: MIT License
# Programming Language: Python
# CUI/GUI Language: English
# Development Stage : Not Implemented
from math import *
# If any builtins variables are substituted by "*"-method importing, undo them
from builtins import *
from _sitebuiltins import _Printer
import math
import statistics as stat
import np_chaonay.main as npc_m
import np_chaonay.math as npc_math
import numpy as np
import pandas as pd
import sympy
sym=sympy
from sympy import symbols, Eq
def reset_sympy_variable():
global a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,_a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x,_y,_z,_A,_B,_C,_D,_E,_F,_G,_H,_I,_J,_K,_L,_M,_N,_O,_P,_Q,_R,_S,_T,_U,_V,_W,_X,_Y,_Z
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z=map(symbols,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
_a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u,_v,_w,_x,_y,_z,_A,_B,_C,_D,_E,_F,_G,_H,_I,_J,_K,_L,_M,_N,_O,_P,_Q,_R,_S,_T,_U,_V,_W,_X,_Y,_Z=a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z
reset_sympy_variable()
sqrt=lambda x: x**0.5
def np_apply(func,arr):
return pd.Series(arr).agg(func).values
def apply_gen_round(func,x):
return round(func(x),12)
def m_apply_gen_round(func,xx):
return np_apply(lambda x: apply_gen_round(func,x),xx)
def apply_deg(func,x):
return apply_gen_round(func,radians(x))
def m_apply_deg(func,xx):
return np_apply(lambda x: apply_deg(func,x),xx)
## Use this snippest if using deg instead of rad
sin=lambda x: math.sin(radians(x))
cos=lambda x: math.cos(radians(x))
tan=lambda x: math.tan(radians(x))
##
def vector_to_xy(mag,angle):
return [mag*math.cos(radians(angle)),mag*math.sin(radians(angle))]
def zip_apply(func,*iterables):
results=[]
objs=zip(*iterables)
for obj in objs: results+=[func(*obj)]
return results
def sqrt_square_sum(iterables):
return sqrt(sum(tuple(map(lambda x: x**2,iterables))))
class Vector():
# QualityCheckTags: COMPLETED
''' Vector implementation
# Object Creation
Vector(*dimensions)
Optional Arguments:
- *dimensions (int,float): Value of each dimensions
# Object Representation
>>> Vector(-1,0,1)
Vector((-1,0,1)
# Object Iteration
>>> list(Vector(-1,0,1)
[-1,0,1]
# Negative Unary
>>> -Vector(-1,0,1)
Vector(1,0,-1)
# Adding/Subtracting
## With same type
>>> Vector(-1,0,1)+Vector(-1,0,1)
Vector(-2,0,2)
>>> Vector(-1,0,1)-Vector(-1,0,1)
Vector(0,0,0)
## With int-alike/float-alike
>>> Vector(-1,0,1)+1
Vector(0,1,2)
>>> Vector(-1,0,1)-1
Vector(-2,-1,0)
# Multiplying
## With int-alike/float-alike
>>> Vector(-1,0,1)*10
Vector(-10,0,10)
# Methods
- magnitude()
Returns: Magnitude of vector
# Variables
- dimensions (list) : consists of dimensions' values
'''
dimensions=[]
def __init__(self,*dimensions):
# Type Checking
for dimension in dimensions: npc_m.alternative_isinstance('*dimensions',(int,float),dimension)
self.dimensions=list(dimensions)
def __repr__(self):
return 'Vector('+repr(self.dimensions)[1:-1]+')'
def __iter__(self):
return (dimension for dimension in self.dimensions)
def __neg__(self):
new_dimensions=[]
for i in range(len(self.dimensions)):
new_dimensions+=[-self.dimensions[i]]
return type(self)(*new_dimensions)
def __add__(self,another):
if type(self)==type(another):
if len(self.dimensions)==len(another.dimensions):
new_dimensions=[]
for i in range(len(self.dimensions)):
new_dimensions+=[self.dimensions[i]+another.dimensions[i]]
return type(self)(*new_dimensions)
else:
raise ValueError('Adding vectors with different dimensions.')
else:
# Type Checking (Adding type(self) for exception displaying
npc_m.alternative_isinstance('adding value',(int,float,type(self)),another)
new_dimensions=[]
for i in range(len(self.dimensions)):
new_dimensions+=[self.dimensions[i]+another]
return type(self)(*new_dimensions)
def __sub__(self,another):
if type(self)==type(another):
if len(self.dimensions)==len(another.dimensions):
new_dimensions=[]
for i in range(len(self.dimensions)):
new_dimensions+=[self.dimensions[i]-another.dimensions[i]]
return type(self)(*new_dimensions)
else:
raise ValueError('Subtracting vectors with different dimensions.')
else:
# Type Checking (Adding type(self) for exception displaying
npc_m.alternative_isinstance('adding value',(int,float,type(self)),another)
new_dimensions=[]
for i in range(len(self.dimensions)):
new_dimensions+=[self.dimensions[i]-another]
return type(self)(*new_dimensions)
def __mul__(self,another):
if type(self)==type(another):
raise ValueError('Muliplying vectors is not implemented yet.')
else:
# Type Checking
npc_m.alternative_isinstance('adding value',(int,float),another)
new_dimensions=[]
for i in range(len(self.dimensions)):
new_dimensions+=[self.dimensions[i]*another]
return type(self)(*new_dimensions)
def magnitude(self):
return (sum(tuple(map(lambda x: x**2,self.dimensions))))**0.5
one_mag=sqrt_square_sum
def solve_eq(L_Eq,R_Eq,symbol=None):
if symbol: return sympy.solve(Eq(L_Eq,R_Eq),symbol)
else: return sympy.solve(Eq(L_Eq,R_Eq))
def solve_eqs(L_Eq_s,R_Eq_s,symbols=None):
answers=[]
if symbols:
eqs=zip(L_Eq_s,R_Eq_s,symbols)
return [solve_eq(L_Eq,R_Eq,symbol) for L_Eq,R_Eq,symbol in eqs]
else:
eqs=zip(L_Eq_s,R_Eq_s)
return [solve_eq(L_Eq,R_Eq) for L_Eq,R_Eq in eqs]
def solve_eq_with_one_param_iterable(L_Eq_s,R_Eq_s,symbols=None):
answers=[]
L_Eq=L_Eq_s
R_Eq=R_Eq_s
symbol=symbols
if npc_m.is_iterable(L_Eq_s):
if npc_m.is_iterable(R_Eq_s) or npc_m.is_iterable(symbols): raise TypeError('Only 1 parameter can be iterable object.')
if symbols:
return [solve_eq(L_Eq,R_Eq,symbol) for L_Eq in L_Eq_s]
else:
return [solve_eq(L_Eq,R_Eq,None) for L_Eq in L_Eq_s]
elif npc_m.is_iterable(R_Eq_s):
if npc_m.is_iterable(L_Eq_s) or npc_m.is_iterable(symbols): raise TypeError('Only 1 parameter can be iterable object.')
if symbols:
return [solve_eq(L_Eq,R_Eq,symbol) for R_Eq in R_Eq_s]
else:
return [solve_eq(L_Eq,R_Eq,None) for R_Eq in R_Eq_s]
elif npc_m.is_iterable(symbols):
if npc_m.is_iterable(L_Eq_s) or npc_m.is_iterable(R_Eq_s): raise TypeError('Only 1 parameter can be iterable object.')
return [solve_eq(L_Eq,R_Eq,symbol) for symbol in symbols]
else: raise TypeError('At least 1 parameter must be iterable object.')
def InsSumIns(*iterable):
return sum(
map(
lambda x: x**-1,
iterable,
)
)**-1
def polymonial_long_division(num_ce,den_ce):
'''Long division a polymonial coefficient
Arguments:
- num_ce,den_ce (non-empty iterable object, length of 'num_ce' should be higher or equal to 'den_ce'): coefficient of each degrees from the numerator and denominator respectively.
Return value:
Tuple, contains:
- result coefficient array
- remainder array
Example:
- array with [1,-2,3] means x^2-2x+3
Notes:
- For the shape of returned arrays, depends on maximum possible amount of coefficient which depends on inputted arrays. See the source for how this function calulates.
'''
try: import numpy as np
except: raise ImportError('Cannot import necessary \'numpy\' package. Origin exception should be shown above.')
try:
if len(num_ce)==0 or len(den_ce)==0: raise ValueError('\'num_ce\' and \'den_ce\' should not be empty.')
if len(num_ce)<len(den_ce): raise ValueError('Amount of number in \'num_ce\' must be equal or more than its of \'den_ce\'')
except: raise ValueError('Cannot find the length of both \'num_ce\' and \'den_ce\', both of them should be iterable.')
try:
num_ce=np.array(num_ce)
den_ce=np.array(den_ce)
except:
raise ValueError('Cannot convert inputted iterable objects to numpy array. Make sure that \'num_ce\' and \'den_ce\' are iterable. Origin exception should be shown above.')
num_highest_deg=len(num_ce)-1
den_highest_deg=len(den_ce)-1
round_num=num_highest_deg-den_highest_deg+1
result_ce=np.zeros(round_num)
rmd_ce=num_ce[0:len(den_ce)]
for i in range(round_num):
tmp=rmd_ce[0]/den_ce[0]
result_ce[i]=tmp
sub_ce=(tmp)*den_ce
rmd_ce=rmd_ce-sub_ce
if i+1==round_num: break
else: rmd_ce=np.concatenate((rmd_ce[1:],(num_ce[i+len(rmd_ce)],)))
return result_ce,rmd_ce[1:]
def mode(iterable,ReturnCount=False):
stat.StatisticsError
mode=None
count=0
NoMode=False
for i in set(iterable):
tmp=iterable.count(i)
if tmp>count:
NoMode=False
count=tmp
mode=i
elif tmp==count:
NoMode=True
if NoMode: raise stat.StatisticsError('No mode due to more than 1 category with the same count.')
elif ReturnCount: return mode,count
else: return mode
def mean(iterable):
return sum(iterable)/len(iterable)
def level_mode(ll_mode_level,mode_level_width,lower_freq_diff,upper_freq_diff):
return ll_mode_level+mode_level_width*(lower_freq_diff/(lower_freq_diff+upper_freq_diff))
def eq_sub(eq,sub,symbol=x):
return eq.subs(symbol,sub)
def eq_msub(eq,subs):
for symbol,sub in subs.items():
eq=eq.subs(symbol,sub)
return eq
example1=_Printer('example_1','\
## Example #####################################################################\n\
# Vector to XY for multiple F,angles and sum it to 1 vector (finding net vector)\n\
np.array(zip_apply(vector_to_xy,F,angles)).sum(0)\n\
\n\
## F=kQ1Q2/R^2: Force between two charges ######################################\n\
k=9*10**9v\
F=np.array([1e0])\n\
q1=np.array([1e0])\n\
q2=np.array([1e0])\n\
r=np.array([1e0])\n\
################################################################################\n\
MEq(F,k*abs(q1)*abs(q2)/(r**2))\
')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment