Simple Tuned Mass Damper

mainan ini beres juga.. disudahi saja..
intinya tentang prinsip TMD yang biasa digunakan di gedung-gedung tinggi, jembatan, dan bangunan anti gempa.. mungkin anak sipil yang lebih tahu.. hehe
sebenarnya saya juga gak terlalu paham dengan tugasnya.. tapi dikerjakan saja sebisanya.. hahahaha.. ya sudahlah ya (-___-”)

Model Ngawuuur:
modelTMD_1

modelTMD_2

modelTMD_3

Hasilnya dibawah ini:

simple TMD

damper

Model: Bridge + TMD + ‘earthquake’

Hasil untuk “Gempa Arah-Z”:
bridge_gempa_z_1

bridge_gempa_z_2

bridge_gempa_z_3

bridge_gempa_z_4

bridge_gempa_z_5

bridge_gempa_z_6

gak jelas thooo… wkwkwkwk
seng nggawe tugas lebih gak jelas.. wkwk

-__-

Grobak, Putih Telor, dan rata-rata yang berlari

akhirnya beres juga ngerjain tugas ini (2 hari sambil nontn dorama).. wkwkwk, semoga masih lulus mata kuliah itu.. he. Tugasnya sederhana, nyobain tutorial penggunaan software molecular dynamic bernama Gromacs.. wkwk, lalu setelah mencari, akhirnya terpilih yang paling gampang, simulasi putih telor dimasukkan dalam air.. huahaha -__-” … kalo mau lebih seru sebenarnya dipanasin dikit sistemnya biar kliatan terjadi protein folding yang menjadikan putih telor berwarna putih beneran.. alias mateng maknyus.. (kayaknya sie gitu.. wkwk)

Plot .pdb file dengan PyMOL:
1AKI

Hasil laporan seadanya:

density

Program sangat sederhana untuk running average menggunakan python (di tutorial python bahkan mungkin ada keknya):

#!/usr/bin/python -tt
# Copyleft (c) 2013. Ridlo W. Wibowo
import numpy as np
import matplotlib.pyplot as plt

# fungsi baca file (data dua kolom saja dulu hahaha..)
def read_file(filename, headernum):
    ifile = open(filename, 'r')
    for i in xrange(headernum):
        ifile.readline() # read header line

    t = []; x = []
    for line in ifile:
        line = line.strip()
        line = line.split()
        t.append(float(line[0]))
        x.append(float(line[1]))

    return [t,x]

# fungsi running average dengan data dua kolom sebagai input dan
# lebar celah (window) berupa jumlah data yang digunakan setiap kali 
# melakukan rata-rata ( yi = average(y_{i-r}, y_{i+r} )
def run_mean(data, r):
    if (r < 1):
        print "Error: lebar celah harus integer lebih dari 0"
        exit(1)
    
    r = int(r) # langsung dibuat pasti saja, integer, ngahaha
    n = len(data[1])
    t = []
    x = []
    average = np.average(data[1])
    start = r; end = n-r-1
    for i in xrange(start, end, 1):
       t.append(data[0][i])
       x.append(np.average(data[1][i-r:i+r+1]))
   
    return [t, x, average]

    
if __name__ == '__main__':
    # pressure
    filename = 'pressure.xvg'
    data = read_file(filename, 19)
    r_average = run_mean(data, 10)
    print r_average[2]
    plt.plot(data[0], data[1], 'r-')
    plt.plot(r_average[0], r_average[1], 'b-')
    plt.xlabel("Time (ps)")
    plt.ylabel("Pressure (bar)")
    plt.title("Pressure")
    plt.grid(True)
    plt.show()

    # density
    filename = 'density.xvg'
    data = read_file(filename, 19)
    r_average = run_mean(data, 10)
    print r_average[2]
    plt.plot(data[0], data[1], 'r-')
    plt.plot(r_average[0], r_average[1], 'b-')
    plt.xlabel("Time (ps)")
    plt.ylabel("Density (kg/m^3)")
    plt.title("Density")
    plt.grid(True)
    plt.show()

Why is the qibla pointed to North-West in Kanazawa?

When I search the direction of qibla from Kanazawa, I got a little surprise because the direction is North-West not South-West, ho.. but then in a second, i understand.. wkwk, cos i’m from astronomy.. :D

qibla direction from kanazawa

If I bought a globe and tried to look from Kanazawa, I see that Makkah is still down somewhere in South-West side, why the direction is North-West?

world map

the answer is because what we see in that map is the flattened of Earth. The Earth is spheris, in spherical coordinate system there are two kind of circle, small and great circle.

Small circle have radius less than radius of sphere,

small circle

Great circle is the circle that cut the sphere into two same pieces, have radius equal to the radius of sphere,

great circle

and if we want to connect two point in spherical surface, the shortest path is through the great circle which pass that two point. If we want to go to Mecca from Kanazawa, the shortest path is through the great circle which connect these two city (and the direction of qibla).

qibla

in spherical surface there is “Spherical trigonometry” to describe the relation between length and angles. We can derive the formula/relation:
spherical trigonometry

Source:
Astronomy: Principles and Practice
A.E. Roy, D. Clarke

triangle in this case is formed by 3 great circle:
segitiga bola

Cosine formula:
\cos a = \cos b \cos c + \sin b \sin c \cos A

Sinus formula:
\frac{\sin a}{\sin A} = \frac{\sin b}{\sin B} = \frac{\sin c}{\sin C}

we can use these formula to calculate shortest distance between Kanazawa and Mecca, then the direction of Mecca seen from Kanazawa.

—————————————————————-
Kanazawa coordinate:
36°34′ N 136°39′ E

Mecca coordinate:
21°25′ N 39°49′ E

—————————————————————-
distance between Kanazawa and Mecca:
cos(d) = cos(68°35′) cos(53°26′) + sin(68°35′) sin(53°26′) cos(96°50′)

d = 82.612665089° = 4956.76 nautical mile = 9179.92 km

—————————————————————-
the direction of Ka’bah seen from Kanazawa:
sin(96°50′)/sin(82.612665089°) = sin(x)/sin(68°35′)

x = 68.76° from North to West, or 291.24 from North to East (exactly same with http://www.qiblalocator.com/, see first image)

so the direction of Ka’bah seen from Kanazawa is 68.76° from North to West

qibla in kanazawa

NB: Sorry my english is bad..

Spring Motion in 3D – OpenGL

preliminary study for tuned mass damper, :v
sial ngerjain gini saja semalaman -_-

Code (still learn how to use OOP):

/*****************************************/
/* Spring 3D in OpenGL                   */
/* Copyleft (c) 2013 - Ridlo W. Wibowo   */
/*****************************************/
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define nball 2
#define dt 0.01
#define G 9.8
using namespace std;

double unirand(){ return (double)rand()/(double)RAND_MAX;}
bool fullscreen = false;
bool mouseDown = false;
float x_rot = 0.0f; float y_rot = 0.0f;
float x_diff = 0.0f; float y_diff = 0.0f;
bool f = false;
int tpm = dt*1000;

class particles{
    public:
        double x, y, z, vx, vy, vz, ax, ay, az, mass;
        void set_value(double, double, double, double, double, double, 
                       double, double, double, double);
        void mlaku();
};

void particles::set_value(double a, double b, double c, double d, double e, 
                double f, double g, double h, double i, double j){
    x = a; y = b; z = c; vx = d; vy = e; vz = f; 
    ax = g; ay = h; az = i; mass = j; 
}

void particles::mlaku(){
    x = x + vx*dt; y = y + vy*dt; z = z + vz*dt;
    vx = vx + ax*dt; vy = vy + ay*dt; vz = vz + az*dt;
}

particles balls[nball];

void inisiasi(){
    balls[0].set_value(0., 0., 0., 0., 0., 0., 0., 0., 0., 1.0);
    balls[1].set_value(1.5, 1.0, -0.5, 3., 0., 3., 0., 0., 0., 2.0);
}

void force(){
    double length = 1.0;
    double ks = 100.;
    double cd = 2.;
    double dx = balls[1].x - balls[0].x;
    double dy = balls[1].y - balls[0].y;
    double dz = balls[1].z - balls[0].z;
    double newl = sqrt(dx*dx + dy*dy + dz*dz);
    double gp = -ks*(newl - length);
    balls[1].ax = (gp*dx/newl - cd*balls[1].vx)/balls[1].mass;
    balls[1].ay = -G + (gp*dy/newl - cd*balls[1].vy)/balls[1].mass; 
    balls[1].az = (gp*dz/newl - cd*balls[1].vz)/balls[1].mass;
}

void move(){
    force();
    for (int i=0;i&lt;nball;i++){
        balls[i].mlaku();
    }
}

void myIdleFunc(int a) {
    move();
    glutPostRedisplay();
    if(f) glutTimerFunc(tpm, myIdleFunc, 0);
}

/* inisiasi warna dan pencahayaan */
void init(){
    GLfloat mat_specular[] = {1., 1., 1., 1.};
    GLfloat mat_shininess[] = {50.0};
    GLfloat light_pos[] = {1., 1., 1., 0.};
    
    glClearColor(1., 1., 1., 1.);
    glShadeModel(GL_SMOOTH);

    glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
    glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);
    glLightfv(GL_LIGHT0, GL_POSITION, light_pos);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_DEPTH_TEST);
	glEnable(GL_COLOR_MATERIAL);
	glEnable(GL_NORMALIZE);
	glShadeModel(GL_SMOOTH);
	glLoadIdentity();
}

/* menampilkan */
void display(){
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);  
    glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
    glLoadIdentity();
    gluLookAt(0.0f, 0.0f, 10.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f);
 
    glRotatef(x_rot, 1.0f, 0.0f, 0.0f);
    glRotatef(y_rot, 0.0f, 1.0f, 0.0f);
   
    // draw cube 
    glColor3f(0.0, 0.0, 1.0);
    glutWireCube(4.0);

    // draw balls
    for (int i=0;i&lt;nball;i++){
        glPushMatrix();
        glTranslatef(balls[i].x, balls[i].y, balls[i].z);
        //glColor3f(0.5, 0.5, 0.5);
        glColor3f((i+1)/(float)nball, 0., 0.);
        glutSolidSphere(0.25, 20, 18);
        glPopMatrix();
    }
    
    /* draw line */
    /*
    glColor3f(0., 0., 1.);
    glBegin(GL_LINES);
        glVertex3f(balls[0].x, balls[0].y, balls[0].z);
        glVertex3f(balls[1].x, balls[1].y, balls[1].z);
    glEnd();
    */

    double dx = balls[1].x - balls[0].x;
    double dy = balls[1].y - balls[0].y;
    double dz = balls[1].z - balls[0].z;
    double newl = sqrt(dx*dx + dy*dy + dz*dz);
    glPushMatrix();
    GLUquadricObj *quadratic;
    quadratic = gluNewQuadric();
    glRotatef(atan2(dy,dx)*180./M_PI, 0.0f, 0.0f, 1.0f);
    glRotatef(acos(dz/newl)*180./M_PI, 0.0f, 1.0f, 0.0f);
    glColor3f(0., 0., 0.5);
    gluCylinder(quadratic, 0.1f, 0.1f, newl, 32, 32);
    glPopMatrix();

    glFlush();
    glutSwapBuffers();
}

/* agar smooth kalau layar di resize */
void resize(int w, int h){
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glViewport(0, 0, w, h);
    gluPerspective(45.0f, 1.0f * w / h, 1.0f, 100.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}
 
void keyboard(unsigned char key, int x, int y){
    if (key == 27){ 
        exit(1);	
	}else if((char)key == 'a'){
		if(!f) glutTimerFunc(tpm, myIdleFunc, 0);
		f = true;
	}else if((char)key == 's'){
		move();
		glutPostRedisplay();
	}else if((char)key == 'd'){
		f = false;
	}else if((char)key == 'f'){
		inisiasi();
        f = false;
		glutPostRedisplay();
    }
}
 
void specialKeyboard(int key, int x, int y){
    if (key == GLUT_KEY_F1){
        fullscreen = !fullscreen;
 
        if (fullscreen)
            glutFullScreen();
        else{
            glutPositionWindow(25, 25);
            glutReshapeWindow(700, 700);
        }
    }
}

/* rotate using mouse */
void mouse(int button, int state, int x, int y){
    if (button == GLUT_LEFT_BUTTON &amp;&amp; state == GLUT_DOWN){
        mouseDown = true;
        x_diff = x - y_rot;
        y_diff = -y + x_rot;
    } 
    else
        mouseDown = false;
}
 
void mouseMotion(int x, int y){
    if (mouseDown){
        y_rot = x - x_diff;
        x_rot = y + y_diff;
        glutPostRedisplay();
    }
}

/* main program */
int main(int argc, char *argv[]){
    glutInit(&amp;argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowPosition(25, 25);
    glutInitWindowSize(700, 700);    
    glutCreateWindow(&quot;Spring Motion&quot;);
    init();
    srand(time(NULL));
    inisiasi();
    glutReshapeFunc(resize);
    glutTimerFunc(tpm, myIdleFunc, 0);
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutSpecialFunc(specialKeyboard);
    glutMouseFunc(mouse);
    glutMotionFunc(mouseMotion);
    glutMainLoop();
    return 0;
}

Sequence Alignment and Dynamic Programming

Who is your mom?

Local Alignment: Smith-Waterman Algorithm
http://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm

Program:

#!/usr/bin/python -tt
#
# Local Alignment - Smith Waterman Algorithm  
# Copyleft (c) 2013. Ridlo W. Wibowo
#
import sys, math

def local_align():
    #### error message
    usage = """
    MANUAL
    Usage   : python localAlign.py [option] [input]
    Option  :   
        -i      input two sequence in command line argument
        -p      print Matrix, True = 1, default False
        -g      gap value, default 0
        -gp     gap penalty, default -1
        -m      match score, default +1
        -mm     mismatch score, default -1
        -f      input file [under construction]
                status: disable
                
                Example: python localAlign.py -i ACACACTA AGCACACA -m 2
    END
    """

    #### default gap value
    gap = 0.
    match = 1.
    mismatch = -1.
    gapPenalty = -1.
    printM = 0
            
    #### input from command line argument
    if len(sys.argv) == 1:
        print usage
        sys.exit(1)

    while len(sys.argv) > 1:
        option = sys.argv[1]; del sys.argv[1]
        if option == '-i':
            seq1 = sys.argv[1]; del sys.argv[1]
            seq2 = sys.argv[1]; del sys.argv[1]
        elif option == '-g':
            gap = float(sys.argv[1]); del sys.argv[1]
        elif option == '-gp':
            gapPenalty = float(sys.argv[1]); del sys.argv[1]
        elif option == '-m':
            match = float(sys.argv[1]); del sys.argv[1]
        elif option == '-mm':
            mismatch = float(sys.argv[1]); del sys.argv[1]
        elif option == '-p':
            printM = int(sys.argv[1]); del sys.argv[1]
        else:
            print "\n", sys.argv[0], ': invalid option', option, usage
            sys.exit(1)

    #### print input
    print "Local Alignment - Smith Waterman Algorithm"
    print "SEQUENCE 1:", seq1; print "SEQUENCE 2:", seq2; 
    print "gap           : ", gap
    print "gap penalty   : ", gapPenalty
    print "match score   : ", match
    print "mismatch score: ", mismatch 

    #### initiate and calculate value
    lseq1 = len(seq1); lseq2 = len(seq2)
    row = lseq2+1; col = lseq1+1

    val = []
    for i in range(row):
        val.append([i*gap]) # gap value in first column
    
    for j in range(1,col):
        val[0].append(j*gap) # gap value in first row
    
    for i in range(1,row):
        for j in range(1,col):
            four = [0.]
            if (seq2[i-1] == seq1[j-1]): 
                four.append(val[i-1][j-1] + match)
            else: 
                four.append(val[i-1][j-1] + mismatch) # match or mismatch
            four.append(val[i-1][j] + gapPenalty)
            four.append(val[i][j-1] + gapPenalty)
            val[i].append(max(four))

    #### print value
    if (printM):
        for i in range(row):
            for j in range(col):
                print val[i][j], '\t',
            print ''
    
    #### search value and position of maxima
    maks = max([max(l) for l in val])
    print "Maximum Value : ", maks
    
    maxIdx = []
    for i in range(row):
        for j in range(col):
            if (val[i][j] == maks):
                maxIdx.append([i,j])
    print "Maximum Position :", maxIdx
    
    #### traceback
    for idx in maxIdx:
        sequ1 = ''; sequ2 = ''
        i = idx[0]; j = idx[1]
        while (val[i][j] > 0.):
            if (val[i][j] == val[i-1][j-1] + (match if seq2[i-1] == seq1[j-1] else mismatch)):
                sequ1 += seq1[j-1]
                sequ2 += seq2[i-1]
                i -= 1; j -= 1
            elif (val[i][j] == val[i-1][j] + gapPenalty):
                sequ1 += '_'
                sequ2 += seq2[i-1]
                i -= 1
            elif (val[i][j] == val[i][j-1] + gapPenalty):
                sequ1 += seq1[j-1]
                sequ2 += '_'
                j -= 1
        
        sequ1r = ' '.join([sequ1[j] for j in range(-1, -(len(sequ1) + 1), -1)])
        sequ2r = ' '.join([sequ2[j] for j in range(-1, -(len(sequ2) + 1), -1)])
        
        score = 0.
        for j in range(len(sequ1)):
            if (sequ1[j] == sequ2[j]):
                score += match
            else: 
                score += mismatch
        
        #### print result of local alignment
        print "Track " 
        print "\tSequence 1 : ", sequ1r
        print "\tSequence 2 : ", sequ2r
        print "\tScore      : ", score

if __name__ == "__main__":
    local_align()

running (using example from wiki):

python localAlign.py -i ACACACTA AGCACACA -m 2 -p 1

Result:

Local Alignment - Smith Waterman Algorithm
SEQUENCE 1: ACACACTA
SEQUENCE 2: AGCACACA
gap           :  0.0
gap penalty   :  -1.0
match score   :  2.0
mismatch score:  -1.0
0.0 	0.0 	0.0 	0.0 	0.0 	0.0 	0.0 	0.0 	0.0 	
0.0 	2.0 	1.0 	2.0 	1.0 	2.0 	1.0 	0.0 	2.0 	
0.0 	1.0 	1.0 	1.0 	1.0 	1.0 	1.0 	0.0 	1.0 	
0.0 	0.0 	3.0 	2.0 	3.0 	2.0 	3.0 	2.0 	1.0 	
0.0 	2.0 	2.0 	5.0 	4.0 	5.0 	4.0 	3.0 	4.0 	
0.0 	1.0 	4.0 	4.0 	7.0 	6.0 	7.0 	6.0 	5.0 	
0.0 	2.0 	3.0 	6.0 	6.0 	9.0 	8.0 	7.0 	8.0 	
0.0 	1.0 	4.0 	5.0 	8.0 	8.0 	11.0 	10.0 	9.0 	
0.0 	2.0 	3.0 	6.0 	7.0 	10.0 	10.0 	10.0 	12.0 	
Maximum Value :  12.0
Maximum Position : [[8, 8]]
Track 
	Sequence 1 :  A _ C A C A C T A
	Sequence 2 :  A G C A C A C _ A
	Score      :  12.0

Run:

python localAlign.py -i ATGC ATGG -m 2 -p 1

Result:

Local Alignment - Smith Waterman Algorithm
SEQUENCE 1: ATGC
SEQUENCE 2: ATGG
gap           :  0.0
gap penalty   :  -1.0
match score   :  2.0
mismatch score:  -1.0
0.0 	0.0 	0.0 	0.0 	0.0 	
0.0 	2.0 	1.0 	0.0 	0.0 	
0.0 	1.0 	4.0 	3.0 	2.0 	
0.0 	0.0 	3.0 	6.0 	5.0 	
0.0 	0.0 	2.0 	5.0 	5.0 	
Maximum Value :  6.0
Maximum Position : [[3, 3]]
Track 
	Sequence 1 :  A T G
	Sequence 2 :  A T G
	Score      :  6.0

you can improve it by yourself.. :D

———————————————————————————————-**

General Gap Penalty — Global Alignment: Needleman-Wunsch Algorithm
http://en.wikipedia.org/wiki/Needleman%E2%80%93Wunsch_algorithm

Program

#!/usr/bin/python -tt
#
# General Gap Penalty, Needleman-Wunch Algorithm
# Copyleft (c) 2013. Ridlo W. Wibowo
#
import sys, math

def global_gap():
    #### error message
    usage = """
    MANUAL
    Usage   : python generalGap.py [option] [input]
    Option  :   
        -i      input two sequence in command line argument
        -g      gap value, default -1
        -gp     gap penalty, default -1
        -m      match score, default +1
        -mm     mismatch score, default -1
        -f      input file [under construction]
                status: disable
                
                Example: python generalGap.py -i ATTGTC AGTGTAC -g -1
    END
    """

    #### default gap value
    gap = -1.
    match = 1.
    mismatch = -1.
    gapPenalty = -1.
            
    #### input from command line argument
    if len(sys.argv) == 1:
        print usage
        sys.exit(1)

    while len(sys.argv) > 1:
        option = sys.argv[1]; del sys.argv[1]
        if option == '-i':
            seq1 = sys.argv[1]; del sys.argv[1]
            seq2 = sys.argv[1]; del sys.argv[1]
        elif option == '-g':
            gap = float(sys.argv[1]); del sys.argv[1]
        elif option == '-gp':
            gapPenalty = float(sys.argv[1]); del sys.argv[1]
        elif option == '-m':
            match = float(sys.argv[1]); del sys.argv[1]
        elif option == '-mm':
            mismatch = float(sys.argv[1]); del sys.argv[1]
        else:
            print "\n", sys.argv[0], ': invalid option', option, usage
            sys.exit(1)

    #### print input
    print "General Gap Penalty, Needleman-Wunch Algorithm"
    print "SEQUENCE 1:", seq1; print "SEQUENCE 2:", seq2
    print "gap           : ", gap
    print "gap penalty   : ", gapPenalty
    print "match score   : ", match
    print "mismacth score: ", mismatch

    #### initiate and calculate value
    lseq1 = len(seq1); lseq2 = len(seq2)
    row = lseq2+1; col = lseq1+1

    val = []
    for i in range(row):
        val.append([i*gap]) # gap value in first column
    
    for j in range(1,col):
        val[0].append(j*gap) # gap value in first row
    
    for i in range(1,row):
        for j in range(1,col):
            three = []
            if (seq2[i-1] == seq1[j-1]): 
                three.append(val[i-1][j-1] + match)
            else: 
                three.append(val[i-1][j-1] + mismatch) # match or mismatch
            three.append(val[i-1][j] + gapPenalty) # Delete
            three.append(val[i][j-1] + gapPenalty) # Insert
            val[i].append(max(three))

    #### print value
    for i in range(row):
        for j in range(col):
            print val[i][j], '\t',
        print ''
    
    #### trace back
    sequ1 = ''
    sequ2 = ''
    i = lseq2
    j = lseq1
    while (i > 0 or j > 0):
        if (i>0 and j>0 and val[i][j] == val[i-1][j-1] + (match if seq2[i-1]==seq1[j-1] else mismatch)):
            sequ1 += seq1[j-1]
            sequ2 += seq2[i-1]
            i -= 1; j -= 1
        elif (i>0 and val[i][j] == val[i-1][j] + gapPenalty):
            sequ1 += '_'
            sequ2 += seq2[i-1]
            i -= 1
        elif (j>0 and val[i][j] == val[i][j-1] + gapPenalty):
            sequ1 += seq1[j-1]
            sequ2 += '_'
            j -= 1
    
    sequ1r = ' '.join([sequ1[j] for j in range(-1, -(len(sequ1)+1), -1)])
    sequ2r = ' '.join([sequ2[j] for j in range(-1, -(len(sequ2)+1), -1)])
    
    score = 0.
    for j in range(len(sequ1)):
        if (sequ1[j] == sequ2[j]):
            score += match
        else:
            score += mismatch

    print "Sequence 1: ", sequ1r
    print "Sequence 2: ", sequ2r
    print "Score     : ", score

if __name__ == "__main__":
    global_gap()
    

Run:

python generalGap.py -i ACACACTA AGCACACA

Result:

General Gap Penalty, Needleman-Wunch Algorithm
SEQUENCE 1: ACACACTA
SEQUENCE 2: AGCACACA
gap           :  -1.0
gap penalty   :  -1.0
match score   :  1.0
mismacth score:  -1.0
-0.0 	-1.0 	-2.0 	-3.0 	-4.0 	-5.0 	-6.0 	-7.0 	-8.0 	
-1.0 	1.0 	0.0 	-1.0 	-2.0 	-3.0 	-4.0 	-5.0 	-6.0 	
-2.0 	0.0 	0.0 	-1.0 	-2.0 	-3.0 	-4.0 	-5.0 	-6.0 	
-3.0 	-1.0 	1.0 	0.0 	0.0 	-1.0 	-2.0 	-3.0 	-4.0 	
-4.0 	-2.0 	0.0 	2.0 	1.0 	1.0 	0.0 	-1.0 	-2.0 	
-5.0 	-3.0 	-1.0 	1.0 	3.0 	2.0 	2.0 	1.0 	0.0 	
-6.0 	-4.0 	-2.0 	0.0 	2.0 	4.0 	3.0 	2.0 	2.0 	
-7.0 	-5.0 	-3.0 	-1.0 	1.0 	3.0 	5.0 	4.0 	3.0 	
-8.0 	-6.0 	-4.0 	-2.0 	0.0 	2.0 	4.0 	4.0 	5.0 	
Sequence 1:  A _ C A C A C T A
Sequence 2:  A G C A C A C _ A
Score     :  5.0

——————————————————————————————————–**

Affine Gap Penalty — Global Alignment: Gotoh Algorithm
Recursion:
sequence alignment - gotoh algorithm

I’m not sure for this program.. wkwkwk

#!/usr/bin/python -tt
#
# Affine Gap Penalty
# Gotoh algorithm
# Copyleft (c) 2013. Ridlo W. Wibowo
#
import sys, math

def affine_gap():
    #### error message
    usage = """
    MANUAL
    Usage   : python affineGap.py [option] [input]
    Option  :   
        -i      input two sequence in command line argument
        -d      gap open value, default -1
        -e      gap extend value, default -0.1
        -m      match score, default +1
        -mm     mismatch score, default -1
        -f      input file [under construction]
                status: disable
                
                Example: python affineGap.py -i ATTGTC AGTC
    END
    """

    #### default gap value
    gap_open = -1.
    gap_extend = -0.1
    match = 1.
    mismatch = -1.
            
    #### input from command line argument
    if len(sys.argv) == 1:
        print usage
        sys.exit(1)

    while len(sys.argv) > 1:
        option = sys.argv[1]; del sys.argv[1]
        if option == '-i':
            seq1 = sys.argv[1]; del sys.argv[1]
            seq2 = sys.argv[1]; del sys.argv[1]
        elif option == '-d':
            gap_open = float(sys.argv[1]); del sys.argv[1]
        elif option == '-e':
            gap_extend = float(sys.argv[1]); del sys.argv[1]
        elif option == '-m':
            match = float(sys.argv[1]); del sys.argv[1]
        elif option == '-mm':
            mismatch = float(sys.argv[1]); del sys.argv[1]
        else:
            print "\n", sys.argv[0], ': invalid option', option, usage
            sys.exit(1)

    #### print input
    print "Affine Gap Penalty, Gotoh Algorithm"
    print "SEQUENCE 1:", seq1; print "SEQUENCE 2:", seq2
    print "gap open      : ", gap_open
    print "gap extend    : ", gap_extend
    print "match score   : ", match
    print "mismacth score: ", mismatch

    #### initiate and calculate value
    lseq1 = len(seq1); lseq2 = len(seq2)
    row = lseq2+1; col = lseq1+1

    xval = [[0. for j in range(col)] for i in range(row)]
    yval = [[0. for j in range(col)] for i in range(row)]
    val = [[0. for j in range(col)] for i in range(row)]
    
    for i in range(row):
        val[i][0] = gap_open + i*gap_extend
        yval[i][0] = -10000. 
    
    for j in range(col):
        val[0][j] = gap_open + j*gap_extend
        xval[0][j] = -10000.  # assign -INF
    
    val[0][0] = 0.
     
    for i in range(1,row):
        for j in range(1,col):
            xval[i][j] = max(xval[i-1][j] + gap_extend, val[i-1][j] + gap_open + gap_extend)
            yval[i][j] = max(yval[i][j-1] + gap_extend, val[i][j-1] + gap_open + gap_extend)
            cople = 0.
            if (seq1[j-1] == seq2[i-1]):
                cople = val[i-1][j-1] + match
            else:
                cople = val[i-1][j-1] + mismatch
            
            val[i][j] = max(cople, xval[i][j], yval[i][j])


    #### print value
    for i in range(row):
        for j in range(col):
            print val[i][j], '\t',
        print ''
    
    #### traceback
    sequ1 = ''
    sequ2 = ''
    i = lseq2
    j = lseq1
    while (i>0 or j>0):
        if (i>0 and j>0 and val[i][j] == val[i-1][j-1] + (match if seq2[i-1] == seq1[j-1] else mismatch)):
            sequ1 += seq1[j-1]
            sequ2 += seq2[i-1]
            i -= 1; j -= 1
        elif (i>0 and val[i][j] == xval[i][j]):
            sequ1 += '_'
            sequ2 += seq2[i-1]
            i -= 1
        elif (j>0 and val[i][j] == yval[i][j]):
            sequ1 += seq1[j-1]
            sequ2 += '_'
            j -= 1
     
    sequ1r = ' '.join([sequ1[j] for j in range(-1, -(len(sequ1)+1), -1)])
    sequ2r = ' '.join([sequ2[j] for j in range(-1, -(len(sequ2)+1), -1)])
     
    score = 0.
    for j in range(len(sequ1)):
        if (sequ1[j] == sequ2[j]):
            score += match
        else:
            score += mismatch
 
    print "Sequence 1: ", sequ1r
    print "Sequence 2: ", sequ2r
    print "Score     : ", score

if __name__ == "__main__":
    affine_gap()
    

Run:

python affineGap.py -i AGCATC AGTC

Result:

Affine Gap Penalty, Gotoh Algorithm
SEQUENCE 1: AGCATC
SEQUENCE 2: AGTC
gap open      :  -1.0
gap extend    :  -0.1
gap penalty   :  -1.0
match score   :  1.0
mismacth score:  -1.0
0.0 	-1.1 	-1.2 	-1.3 	-1.4 	-1.5 	-1.6 	
-1.1 	1.0 	-0.1 	-0.2 	-0.3 	-0.4 	-0.5 	
-1.2 	-0.1 	2.0 	0.9 	0.8 	0.7 	0.6 	
-1.3 	-0.2 	0.9 	1.0 	-0.1 	1.8 	0.7 	
-1.4 	-0.3 	0.8 	1.9 	0.8 	0.7 	2.8 	
Sequence 1:  A G C A T C
Sequence 2:  A G _ _ T C
Score     :  2.0
Follow

Get every new post delivered to your Inbox.

Join 1,328 other followers