Example #1
0
def read_geometry(input_file="wannier.win"):
  """Reads the geometry of the wannier calculation"""
  ll = read_between("begin unit_cell_cart","end unit_cell_cart",input_file)
  a1 = ll[1].split()
  a2 = ll[2].split()
  a3 = ll[3].split()
  # read the unit vectors
  a1 = np.array([float(a1[0]),float(a1[1]),float(a1[2])]) # first vector
  a2 = np.array([float(a2[0]),float(a2[1]),float(a2[2])]) # second vector
  a3 = np.array([float(a3[0]),float(a3[1]),float(a3[2])]) # second vector
  g = geometry.geometry()
  g.dimensionality = 2
  g.has_spin = False
  g.has_sublattice = False
  g.a1 = a1  # store vector
  g.a2 = a2  # store vector
  g.a3 = a3  # store vector
  # read the coordinates 
  ll = read_between("begin projections","end projections",input_file)
  rs = [] # empty list for positions
  g.atoms_have_names = True # Atoms have names
  g.atoms_names = [] # initalize
  for l in ll:
    name = l.split(":")[0] # get name of the atom
    r = get_positions(name,input_file) # get positins of the atoms
    g.atoms_names += [name]*len(r) # append this names
    for i in range(len(r)): # to real coordinates
      r[i] = r[i][0]*a1 + r[i][1]*a2 + r[i][2]*a3
    rs += r # store positions
  g.r = np.array(rs) # store in the class
  g.r2xyz() # store also in xyz atributes
  g.get_fractional() # fractional coordinates
  return g
Example #2
0
def read_geometry(input_file="wannier.win"):
    """Reads the geometry of the wannier calculation"""
    ll = read_between("begin unit_cell_cart", "end unit_cell_cart", input_file)
    a1 = ll[1].split()
    a2 = ll[2].split()
    a3 = ll[3].split()
    # read the unit vectors
    a1 = np.array([float(a1[0]), float(a1[1]), float(a1[2])])  # first vector
    a2 = np.array([float(a2[0]), float(a2[1]), float(a2[2])])  # second vector
    a3 = np.array([float(a3[0]), float(a3[1]), float(a3[2])])  # second vector
    g = geometry.geometry()
    g.dimensionality = 2
    g.has_spin = False
    g.has_sublattice = False
    g.a1 = a1  # store vector
    g.a2 = a2  # store vector
    g.a3 = a3  # store vector
    # read the coordinates
    ll = read_between("begin projections", "end projections", input_file)
    rs = []  # empty list for positions
    g.atoms_have_names = True  # Atoms have names
    g.atoms_names = []  # initalize
    for l in ll:
        name = l.split(":")[0]  # get name of the atom
        r = get_positions(name, input_file)  # get positins of the atoms
        g.atoms_names += [name] * len(r)  # append this names
        for i in range(len(r)):  # to real coordinates
            r[i] = r[i][0] * a1 + r[i][1] * a2 + r[i][2] * a3
        rs += r  # store positions
    g.r = np.array(rs)  # store in the class
    g.r2xyz()  # store also in xyz atributes
    g.get_fractional()  # fractional coordinates
    return g
def get_transformation_matrix(
    d_mmCIF_apo, l_coords_alpha_apo,
    d_mmCIF_holo, l_coords_alpha_holo,
    ):

    ## structural alignment
    ## solution that works in all cases
    ## also for 2d59 and 2d5a, which have residues missing at the Nterm and Cterm, respectively
    ## first non-?
    index1_seq_apo = next((i for i,v in enumerate(d_mmCIF_apo['_pdbx_poly_seq_scheme.pdb_mon_id']) if v != '?'))
    index1_seq_holo = next((i for i,v in enumerate(d_mmCIF_holo['_pdbx_poly_seq_scheme.pdb_mon_id']) if v != '?'))
    ## last non-?
    index2_seq_apo = len(d_mmCIF_apo['_pdbx_poly_seq_scheme.pdb_mon_id'])-next((i for i,v in enumerate(reversed(d_mmCIF_apo['_pdbx_poly_seq_scheme.pdb_mon_id'])) if v != '?'))
    index2_seq_holo = len(d_mmCIF_holo['_pdbx_poly_seq_scheme.pdb_mon_id'])-next((i for i,v in enumerate(reversed(d_mmCIF_holo['_pdbx_poly_seq_scheme.pdb_mon_id'])) if v != '?'))
    ## first common non-?
    index1_coord_apo = max(0,index1_seq_holo-index1_seq_apo)
    index1_coord_holo = max(0,index1_seq_apo-index1_seq_holo)
    ## last common non-?
    index2_coord_apo = len(l_coords_alpha_apo)+min(0,index2_seq_holo-index2_seq_apo)
    index2_coord_holo = len(l_coords_alpha_holo)+min(0,index2_seq_apo-index2_seq_holo)
    l_coords_alpha_apo = l_coords_alpha_apo[index1_coord_apo:index2_coord_apo]
    l_coords_alpha_holo = l_coords_alpha_holo[index1_coord_holo:index2_coord_holo]

    instance_geometry = geometry.geometry()
    rmsd = instance_geometry.superpose(l_coords_alpha_apo,l_coords_alpha_holo,)
    tv1 = instance_geometry.fitcenter
    rm = instance_geometry.rotation
    tv2 = instance_geometry.refcenter

    return tv1, rm, tv2, l_coords_alpha_apo, l_coords_alpha_holo
Example #4
0
    def createBilinear(self):
        wk = self.workGroup
        list_P = wk.viewer.MarkerPoints
        if len(list_P) != 4:
            print("You have to specify 4 markers.")
            return

        A = list_P[0]
        B = list_P[1]
        C = list_P[2]
        D = list_P[3]

        points = np.zeros((2, 2, 3))

        points[0, 0, :] = A[:3]
        points[1, 0, :] = B[:3]
        points[0, 1, :] = C[:3]
        points[1, 1, :] = D[:3]

        #        weights[0,0] = A[3]
        #        weights[1,0] = B[3]
        #        weights[0,1] = C[3]
        #        weights[1,1] = D[3]

        from caid.cad_geometry import bilinear
        nrb = bilinear(points=points)[0]

        wk.viewer.CleanMarkerPoints()
        geo = cad_geometry()
        geo.append(nrb)
        wk.add_geometry(geometry(geo))
        wk.Refresh()
Example #5
0
    def createBilinear(self):
        wk = self.workGroup
        list_P = wk.viewer.MarkerPoints
        if len(list_P) != 4 :
            print("You have to specify 4 markers.")
            return

        A = list_P[0]
        B = list_P[1]
        C = list_P[2]
        D = list_P[3]

        points = np.zeros((2,2,3))

        points[0,0,:] = A[:3]
        points[1,0,:] = B[:3]
        points[0,1,:] = C[:3]
        points[1,1,:] = D[:3]

#        weights[0,0] = A[3]
#        weights[1,0] = B[3]
#        weights[0,1] = C[3]
#        weights[1,1] = D[3]

        from caid.cad_geometry import bilinear
        nrb = bilinear(points=points)[0]

        wk.viewer.CleanMarkerPoints()
        geo = cad_geometry()
        geo.append(nrb)
        wk.add_geometry(geometry(geo))
        wk.Refresh()
Example #6
0
def squid_square(width=4,inner_radius=6,arm_length=8,arm_width=2,fill=False):
  nt = width + inner_radius # half side of the big square
  import geometry
  g = geometry.geometry() # create the geometry of the system
  xc = [] # empty list
  yc = [] # empty list
  shift_y = float(arm_width-1)/2.0
  for i in range(-nt,nt+1): 
    for j in range(-nt,nt+arm_width):
      # if in the ring
      yy = float(j)-shift_y  # temporal y
      if abs(i)>inner_radius or abs(yy)>(inner_radius+shift_y) or fill: 
        xc.append(float(i))  # add x coordinate
        yc.append(yy)  # add y coordinate
  # now add right and left parts
  xr = [] # empty list
  yr = [] # empty list
  xl = [] # empty list
  yl = [] # empty list
  shift_y = float(arm_width-1)/2.0
  min_x = min(xc) - 1.0
  max_x = max(xc) + 1.0
  for i in range(arm_length):
    for j in range(arm_width): # double width of the arms
      xr.append(float(i)+max_x)
      xl.append(-float(i)+min_x)
      yr.append(float(j)-shift_y)
      yl.append(float(j)-shift_y)
  x = np.array(xr+xc+xl)  # all the x positions
  y = np.array(yr+yc+yl)  # all the y positions
  g.x = x  # add positions in x
  g.y = y  # add positions in y
  g.celldis = max(x) - min(x) +1.0 # distance to neighbor +1.0
  g.dimensionality = 1 # 0 dimensional system
  return g
Example #7
0
def make_random(k):
    vtx = random_vertex()
    theta, phi = random_direction()
    direct = unit_vector(theta, phi)
    pts, deps = track_points(vtx, direct)
    print(len(deps))
    x, y, z = unzip(pts)
    scatter3d_module(x, y, z, deps, k)

    zero = geo.point_3d(0., 0., 0.)
    #box = geo.box(714*cm, 300*cm, 510*cm, zero, "ar_cube")
    module_box = geo.box(100.0 * cm, 300.0 * cm, 100 * cm, zero,
                         "rand" + str(k) + "_box")
    geometry = geo.geometry([module_box], zero)
    simul = sim.simulator(geometry)
    simul.supervisor._outfile = OUT_DIR + "rand_event" + str(k) + ".root"

    geom = simul.project_event(pts, deps, vtx)
    simul.set_minimal()
    simul.supervisor._truth.SetBinContent(1, vtx[0])
    simul.supervisor._truth.SetBinContent(2, vtx[1])
    simul.supervisor._truth.SetBinContent(3, vtx[2])
    simul.supervisor._truth.SetBinContent(4, theta)
    simul.supervisor._truth.SetBinContent(5, phi)
    simul.supervisor.write()
Example #8
0
 def initialize(self, empty=False):
     """
     create an empty geometry object
     """
     if not empty:
         from geometry import geometry
         geo = geometry()
         self.add_geometry(geo)
Example #9
0
 def initialize(self, empty=False):
     """
     create an empty geometry object
     """
     if not empty:
         from geometry import geometry
         geo = geometry()
         self.add_geometry(geo)
Example #10
0
    def open(self, filename=None):
        if filename is not None:
            self.filename = filename
        else:
            from global_vars import CAIDWorkGroupwildcard
            # Create an open file dialog
            dialog = wx.FileDialog(None\
                                   , style = wx.OPEN\
                                   , wildcard=CAIDWorkGroupwildcard)
            # Show the dialog and get user input
            if dialog.ShowModal() == wx.ID_OK:
                self.filename = dialog.GetPath()
            # The user did not select anything
            else:
                print('Nothing was selected.')
            # Destroy the dialog
            dialog.Destroy()

        from caid.cad_geometry import cad_geometry
        from caid.io import XML
        from geometry import geometry
        io = XML()

        from xml.dom.minidom import parse
        doc = parse(self.filename)
        rootElt = doc.documentElement

        # read attributs
        # get camera attributs
        eye = strtoArray(rootElt.getAttribute("eye"))
        self.viewer.lookAt.SetEye(eye)
        center = strtoArray(rootElt.getAttribute("center"))
        self.viewer.lookAt.SetCenter(center)
        up = strtoArray(rootElt.getAttribute("up"))
        self.viewer.lookAt.SetUp(up)
        # get colors attributs

        # ...
        try:
            self.viewer.theme.load(rootElt=rootElt)
        except:
            print("Theme can not be loaded. Dark theme will be used.")
            self.viewer.theme.set_theme("dark")
        # ...

        for geoElt in rootElt.getElementsByTagName("geometry"):
            geo = cad_geometry()
            io.xmltogeo(geo, doc, geoElt)
            _geo = geometry(geo)
            _geo.load_attributs()
            self.add_geometry(_geo)

        self.Refresh()

        # sets the temporary file for auto-save
        tmp = self.filename.split('/')[-1]
        basedir = self.filename.split(tmp)[0]
        self.tmp_filename = basedir+"~"+tmp
Example #11
0
    def open(self, filename=None):
        if filename is not None:
            self.filename = filename
        else:
            from global_vars import CAIDWorkGroupwildcard
            # Create an open file dialog
            dialog = wx.FileDialog(None\
                                   , style = wx.OPEN\
                                   , wildcard=CAIDWorkGroupwildcard)
            # Show the dialog and get user input
            if dialog.ShowModal() == wx.ID_OK:
                self.filename = dialog.GetPath()
            # The user did not select anything
            else:
                print('Nothing was selected.')
            # Destroy the dialog
            dialog.Destroy()

        from caid.cad_geometry import cad_geometry
        from caid.io import XML
        from geometry import geometry
        io = XML()

        from xml.dom.minidom import parse
        doc = parse(self.filename)
        rootElt = doc.documentElement

        # read attributs
        # get camera attributs
        eye = strtoArray(rootElt.getAttribute("eye"))
        self.viewer.lookAt.SetEye(eye)
        center = strtoArray(rootElt.getAttribute("center"))
        self.viewer.lookAt.SetCenter(center)
        up = strtoArray(rootElt.getAttribute("up"))
        self.viewer.lookAt.SetUp(up)
        # get colors attributs

        # ...
        try:
            self.viewer.theme.load(rootElt=rootElt)
        except:
            print("Theme can not be loaded. Dark theme will be used.")
            self.viewer.theme.set_theme("dark")
        # ...

        for geoElt in rootElt.getElementsByTagName("geometry"):
            geo = cad_geometry()
            io.xmltogeo(geo, doc, geoElt)
            _geo = geometry(geo)
            _geo.load_attributs()
            self.add_geometry(_geo)

        self.Refresh()

        # sets the temporary file for auto-save
        tmp = self.filename.split('/')[-1]
        basedir = self.filename.split(tmp)[0]
        self.tmp_filename = basedir + "~" + tmp
Example #12
0
def plot_dts(n, prefix='out/tireout', postfix='.dat', conf='DEFAULT'):
    configactual = config[conf]
    CFL = configactual.getfloat('CFL')
    Cth = configactual.getfloat('Cth')
    Cdiff = configactual.getfloat('Cdiff')
    rstar = configactual.getfloat('rstar')
    mu30 = configactual.getfloat('mu30')
    m1 = configactual.getfloat('m1')
    b12 = 2. * mu30 * (rstar * m1 / 6.8)**(-3)

    geofile = os.path.dirname(prefix) + "/geo.dat"
    print(geofile)
    r, theta, alpha, across, l, delta = geo.gread(geofile)
    g = geo.geometry()
    g.r = r
    g.theta = theta
    g.alpha = alpha
    g.l = l
    g.delta = delta
    g.across = across
    g.cth = cos(theta)
    dl = l[1:] - l[:-1]
    dl = concatenate([dl, [dl[-1]]])

    umag = b12**2 * 2.29e6 * m1
    umagtar = umag * ((1. + 3. * g.cth**2) / 4. * (rstar / g.r)**6)

    fname = prefix + entryname(n, ndig=5) + postfix
    print(fname)
    lines = loadtxt(fname, comments="#")
    print(shape(lines))
    r1 = lines[:, 0]
    rho = lines[:, 1]
    v = lines[:, 2]
    u = lines[:, 3] * umagtar
    print(shape(r1))
    print((r1 - r).std())
    csq = 4. / 3. * u / rho
    dt_CFL = CFL * dl / (sqrt(csq) + abs(v))

    qloss = qloss_separate(rho, v, u, g, configactual)

    dt_thermal = Cth * u * g.across / qloss

    dt_diff = Cdiff * dl**2 * rho * 3.
    someplots(r, [dl],
              ylog=True,
              ytitle='$\Delta l$',
              name='dl',
              formatsequence=['k-'])

    someplots(r, [dt_CFL, dt_thermal, dt_diff],
              ylog=True,
              ytitle='$\Delta t$',
              name='dts',
              formatsequence=['k-', 'b:', 'r--'])
Example #13
0
    def cutCurve(self):
        wk = self.workGroup
        try:
            list_patchs = []
            for item in wk.inspector.tree.selectionsItems:
                patch = wk.inspector.tree.GetItemData(item)
                if patch.dim > 1:
                    print("cut curves algorithm only works with curves")
                    return
                list_patchs.append(patch)
            if len(list_patchs) > 1:
                print(("cut curves algorithm needs 1 curve, but "\
                        , len(list_patchs), " curves were given"))
                return

            from caid.utils.intersect import intersect_crv
            c0 = list_patchs[0]
            geo0 = cad_geometry()
            geo0.append(c0)

            freq = wk.viewer.cutCurveFreq
            list_P = wk.viewer.CutCurvePoints[::freq]
            x, y, z = list(zip(*list_P))
            x = np.asarray(x)
            y = np.asarray(y)
            z = np.asarray(z)
            from scipy import interpolate
            smooth = 0.
            degree = 3
            tck, u = interpolate.splprep([x, y], s=smooth, k=degree)
            knots = tck[0]
            Px = tck[1][0]
            Py = tck[1][1]
            C = np.zeros((len(Px), 3))
            C[:, 0] = array(Px)
            C[:, 1] = array(Py)
            c1 = cad_nurbs([knots], C)
            geo1 = cad_geometry()
            geo1.append(c1)

            list_P, list_t, list_s, ierr = intersect_crv(c0, c1)

            list_t = np.asarray(list_t)
            list_t.sort()
            axis = 0
            for i, t in enumerate(list_t):
                geo0.split(i, t, axis)

            wk.add_geometry(geometry(geo0))
            wk.Refresh()
        except:
            self.statusbar.SetStatusText(
                'Cannot use cut Curve. Check that a patch is selected on the inspector'
            )
Example #14
0
    def cutCurve(self):
        wk = self.workGroup
        try:
            list_patchs = []
            for item in wk.inspector.tree.selectionsItems:
                patch = wk.inspector.tree.GetPyData(item)
                if patch.dim > 1:
                    print("cut curves algorithm only works with curves")
                    return
                list_patchs.append(patch)
            if len(list_patchs) > 1:
                print(("cut curves algorithm needs 1 curve, but ", len(list_patchs), " curves were given"))
                return

            from caid.utils.intersect import intersect_crv

            c0 = list_patchs[0]
            geo0 = cad_geometry()
            geo0.append(c0)

            freq = wk.viewer.cutCurveFreq
            list_P = wk.viewer.CutCurvePoints[::freq]
            x, y, z = list(zip(*list_P))
            x = np.asarray(x)
            y = np.asarray(y)
            z = np.asarray(z)
            from scipy import interpolate

            smooth = 0.0
            degree = 3
            tck, u = interpolate.splprep([x, y], s=smooth, k=degree)
            knots = tck[0]
            Px = tck[1][0]
            Py = tck[1][1]
            C = np.zeros((len(Px), 3))
            C[:, 0] = array(Px)
            C[:, 1] = array(Py)
            c1 = cad_nurbs([knots], C)
            geo1 = cad_geometry()
            geo1.append(c1)

            list_P, list_t, list_s, ierr = intersect_crv(c0, c1)

            list_t = np.asarray(list_t)
            list_t.sort()
            axis = 0
            for i, t in enumerate(list_t):
                geo0.split(i, t, axis)

            wk.add_geometry(geometry(geo0))
            wk.Refresh()
        except:
            self.statusbar.SetStatusText("Cannot use cut Curve. Check that a patch is selected on the inspector")
def get_transformation_matrix(
    d_mmCIF_apo,
    l_coords_alpha_apo,
    d_mmCIF_holo,
    l_coords_alpha_holo,
):

    ## structural alignment
    ## solution that works in all cases
    ## also for 2d59 and 2d5a, which have residues missing at the Nterm and Cterm, respectively
    ## first non-?
    index1_seq_apo = next(
        (i
         for i, v in enumerate(d_mmCIF_apo['_pdbx_poly_seq_scheme.pdb_mon_id'])
         if v != '?'))
    index1_seq_holo = next((
        i
        for i, v in enumerate(d_mmCIF_holo['_pdbx_poly_seq_scheme.pdb_mon_id'])
        if v != '?'))
    ## last non-?
    index2_seq_apo = len(
        d_mmCIF_apo['_pdbx_poly_seq_scheme.pdb_mon_id']) - next(
            (i for i, v in enumerate(
                reversed(d_mmCIF_apo['_pdbx_poly_seq_scheme.pdb_mon_id']))
             if v != '?'))
    index2_seq_holo = len(
        d_mmCIF_holo['_pdbx_poly_seq_scheme.pdb_mon_id']) - next(
            (i for i, v in enumerate(
                reversed(d_mmCIF_holo['_pdbx_poly_seq_scheme.pdb_mon_id']))
             if v != '?'))
    ## first common non-?
    index1_coord_apo = max(0, index1_seq_holo - index1_seq_apo)
    index1_coord_holo = max(0, index1_seq_apo - index1_seq_holo)
    ## last common non-?
    index2_coord_apo = len(l_coords_alpha_apo) + min(
        0, index2_seq_holo - index2_seq_apo)
    index2_coord_holo = len(l_coords_alpha_holo) + min(
        0, index2_seq_apo - index2_seq_holo)
    l_coords_alpha_apo = l_coords_alpha_apo[index1_coord_apo:index2_coord_apo]
    l_coords_alpha_holo = l_coords_alpha_holo[
        index1_coord_holo:index2_coord_holo]

    instance_geometry = geometry.geometry()
    rmsd = instance_geometry.superpose(
        l_coords_alpha_apo,
        l_coords_alpha_holo,
    )
    tv1 = instance_geometry.fitcenter
    rm = instance_geometry.rotation
    tv2 = instance_geometry.refcenter

    return tv1, rm, tv2, l_coords_alpha_apo, l_coords_alpha_holo
def get_transformation_matrix(
    l_coords_alpha_apo,
    l_coords_alpha_holo,
    ):

    instance_geometry = geometry.geometry()
    rmsd = instance_geometry.superpose(l_coords_alpha_apo,l_coords_alpha_holo,)
    print 'rmsd', rmsd
    tv1 = instance_geometry.fitcenter
    rm = instance_geometry.rotation
    tv2 = instance_geometry.refcenter

    return tv1, rm, tv2, l_coords_alpha_apo, l_coords_alpha_holo
Example #17
0
File: model.py Project: pf4d/issm
    def __init__(self):  #{{{

        # classtype=model.properties

        # for classe in dict.keys(classtype):
        # 	print classe
        # 	self.__dict__[classe] = classtype[str(classe)]

        self.mesh = mesh2d()
        self.mask = mask()
        self.geometry = geometry()
        self.constants = constants()
        self.smb = SMBforcing()
        self.basalforcings = basalforcings()
        self.materials = matice()
        self.damage = damage()
        self.friction = friction()
        self.flowequation = flowequation()
        self.timestepping = timestepping()
        self.initialization = initialization()
        self.rifts = rifts()
        self.slr = slr()

        self.debug = debug()
        self.verbose = verbose()
        self.settings = settings()
        self.toolkits = toolkits()
        self.cluster = generic()

        self.balancethickness = balancethickness()
        self.stressbalance = stressbalance()
        self.groundingline = groundingline()
        self.hydrology = hydrologyshreve()
        self.masstransport = masstransport()
        self.thermal = thermal()
        self.steadystate = steadystate()
        self.transient = transient()
        self.levelset = levelset()
        self.calving = calving()
        self.gia = giaivins()

        self.autodiff = autodiff()
        self.inversion = inversion()
        self.qmu = qmu()
        self.amr = amr()

        self.results = results()
        self.outputdefinition = outputdefinition()
        self.radaroverlay = radaroverlay()
        self.miscellaneous = miscellaneous()
        self.private = private()
Example #18
0
    def OnDrawSelectionRectangle(self, x1, y1, x2, y2):
#        glClear(GL_COLOR_BUFFER_BIT)
#        glBegin(GL_QUADS)
#        col = self.theme.color_viewer("selection") + [self.theme.alpha]
#        glColor4f(*col)
#        glVertex2f(x1, y1)
#        glVertex2f(x2, y1)
#        glVertex2f(x2, y2)
#        glVertex2f(x1, y2)
#        glEnd()

        points = np.asarray([[[x1,y1],[x1,y2]],[[x2,y1],[x2,y2]]])
        geo_selection = geometry(bilinear(points=points))
        col = self.theme.color_viewer("selection")
        geo_selection.Draw(alpha=self.beta, blend=self.enableBlend, NurbsColor=col)
Example #19
0
    def OnDrawSelectionRectangle(self, x1, y1, x2, y2):
#        glClear(GL_COLOR_BUFFER_BIT)
#        glBegin(GL_QUADS)
#        col = self.theme.color_viewer("selection") + [self.theme.alpha]
#        glColor4f(*col)
#        glVertex2f(x1, y1)
#        glVertex2f(x2, y1)
#        glVertex2f(x2, y2)
#        glVertex2f(x1, y2)
#        glEnd()

        points = np.asarray([[[x1,y1],[x1,y2]],[[x2,y1],[x2,y2]]])
        geo_selection = geometry(bilinear(points=points))
        col = self.theme.color_viewer("selection")
        geo_selection.Draw(alpha=self.beta, blend=self.enableBlend, NurbsColor=col)
Example #20
0
def get_transformation_matrix(
    l_coords_alpha_apo,
    l_coords_alpha_holo,
):

    instance_geometry = geometry.geometry()
    rmsd = instance_geometry.superpose(
        l_coords_alpha_apo,
        l_coords_alpha_holo,
    )
    print 'rmsd', rmsd
    tv1 = instance_geometry.fitcenter
    rm = instance_geometry.rotation
    tv2 = instance_geometry.refcenter

    return tv1, rm, tv2, l_coords_alpha_apo, l_coords_alpha_holo
Example #21
0
    def createLines(self):
        wk = self.workGroup
        list_P = wk.viewer.MarkerPoints
        list_crv = []
        for P,Q in zip(list_P[:-1], list_P[1:]):
            points = np.zeros((2,2))
            points[0,0] = P[0] ; points[0,1] = P[1]
            points[1,0] = Q[0] ; points[1,1] = Q[1]
            crv = linear(points = points)[0]
            list_crv.append(crv)
        nrb = list_crv[0]
        axis = 0
        for crv in list_crv[1:]:
            nrb = join(nrb, crv, axis)

        wk.viewer.CleanMarkerPoints()
        geo = cad_geometry()
        geo.append(nrb)
        wk.add_geometry(geometry(geo))
        wk.Refresh()
Example #22
0
    def __init__(self, renderer, size):
        self.geometry = geometry.geometry()

        self.renderer = renderer

        self.camera = camera.camera(size[0], size[1])

        self.player = player.player(self.geometry)

        self.mouse_screen_x = 0
        self.mouse_screen_y = 0

        self.mouse_x = 0
        self.mouse_y = 0

        self.ghost = player.player(self.geometry, True)
        self.ghost_data_store = []
        self.ghost_data_replay = []
        self.ghost_replay_index = 0
        
        self.font = sdl2hl.ttf.Font(resource_string(__name__, 'res/font/LiberationSans-Regular.ttf'), 24)
Example #23
0
def squid_square(width=4,
                 inner_radius=6,
                 arm_length=8,
                 arm_width=2,
                 fill=False):
    nt = width + inner_radius  # half side of the big square
    import geometry
    g = geometry.geometry()  # create the geometry of the system
    xc = []  # empty list
    yc = []  # empty list
    shift_y = float(arm_width - 1) / 2.0
    for i in range(-nt, nt + 1):
        for j in range(-nt, nt + arm_width):
            # if in the ring
            yy = float(j) - shift_y  # temporal y
            if abs(i) > inner_radius or abs(yy) > (inner_radius +
                                                   shift_y) or fill:
                xc.append(float(i))  # add x coordinate
                yc.append(yy)  # add y coordinate
    # now add right and left parts
    xr = []  # empty list
    yr = []  # empty list
    xl = []  # empty list
    yl = []  # empty list
    shift_y = float(arm_width - 1) / 2.0
    min_x = min(xc) - 1.0
    max_x = max(xc) + 1.0
    for i in range(arm_length):
        for j in range(arm_width):  # double width of the arms
            xr.append(float(i) + max_x)
            xl.append(-float(i) + min_x)
            yr.append(float(j) - shift_y)
            yl.append(float(j) - shift_y)
    x = np.array(xr + xc + xl)  # all the x positions
    y = np.array(yr + yc + yl)  # all the y positions
    g.x = x  # add positions in x
    g.y = y  # add positions in y
    g.celldis = max(x) - min(x) + 1.0  # distance to neighbor +1.0
    g.dimensionality = 1  # 0 dimensional system
    return g
Example #24
0
    def createLines(self):
        wk = self.workGroup
        list_P = wk.viewer.MarkerPoints
        list_crv = []
        for P, Q in zip(list_P[:-1], list_P[1:]):
            points = np.zeros((2, 2))
            points[0, 0] = P[0]
            points[0, 1] = P[1]
            points[1, 0] = Q[0]
            points[1, 1] = Q[1]
            crv = linear(points=points)[0]
            list_crv.append(crv)
        nrb = list_crv[0]
        axis = 0
        for crv in list_crv[1:]:
            nrb = join(nrb, crv, axis)

        wk.viewer.CleanMarkerPoints()
        geo = cad_geometry()
        geo.append(nrb)
        wk.add_geometry(geometry(geo))
        wk.Refresh()
Example #25
0
    def createArc(self):
        wk = self.workGroup
        list_P = wk.viewer.MarkerPoints
        if len(list_P) != 3 :
            print("You have to specify 3 markers.")
            return

        dlg = edtTxtDialog(None, title="Edit Angle")
        dlg.ShowModal()
        ls_text = dlg.getValue()
        try:
            lr_degree = float(ls_text)
        except:
            lr_degree = 0.0

        theta = lr_degree * pi / 180

        dlg.Destroy()

        A0 = list_P[0]
        A1 = list_P[1]
        A2 = list_P[2]

        knots       = [0.,0.,0.,1.,1.,1.]
        C           = np.zeros((3,3))
        C[0,:]      = A0[:3]
        C[1,:]      = A1[:3]
        C[2,:]      = A2[:3]
        weights     = [1.,cos(theta),1.]

        nrb = cad_nurbs([knots], C, weights=weights)

        wk.viewer.CleanMarkerPoints()
        geo = cad_geometry()
        geo.append(nrb)
        wk.add_geometry(geometry(geo))
        wk.Refresh()
Example #26
0
    def MenuSelectionCb(self, event):
        # do something
        operation = self.menu_title_by_id[event.GetId()]
        if operation == "New Geometry":
            from geometry import geometry
            geo = geometry()

            wk = self.currentWorkGroup
            wk.add_geometry(geo)
        if operation == "Save":
            self.currentWorkGroup.save()
        if operation == "New Scalar Field":
            F = field()
            wk = self.currentWorkGroup
            wk.add_field(F)
        if operation == "Import Scalar Field":
            filename = None
            from global_vars import CAIDFieldWildcard
            # Create an open file dialog
            dialog = wx.FileDialog(None\
                                   , style = wx.OPEN\
                                   , wildcard=CAIDFieldWildcard)
            # Show the dialog and get user input
            if dialog.ShowModal() == wx.ID_OK:
                filename = dialog.GetPath()
            # The user did not select anything
            else:
                print('Nothing was selected.')
            # Destroy the dialog
            dialog.Destroy()

            if filename is not None:
                U = field()
                U.open(filename)
                wk = self.currentWorkGroup
                wk.add_field(U)
                wk.Refresh()
Example #27
0
    def MenuSelectionCb( self, event ):
        # do something
        operation = self.menu_title_by_id[ event.GetId() ]
        if operation == "New Geometry":
            from geometry import geometry
            geo = geometry()

            wk = self.currentWorkGroup
            wk.add_geometry(geo)
        if operation == "Save":
            self.currentWorkGroup.save()
        if operation == "New Scalar Field":
            F = field()
            wk = self.currentWorkGroup
            wk.add_field(F)
        if operation == "Import Scalar Field":
            filename = None
            from global_vars import CAIDFieldWildcard
            # Create an open file dialog
            dialog = wx.FileDialog(None\
                                   , style = wx.OPEN\
                                   , wildcard=CAIDFieldWildcard)
            # Show the dialog and get user input
            if dialog.ShowModal() == wx.ID_OK:
                filename = dialog.GetPath()
            # The user did not select anything
            else:
                print('Nothing was selected.')
            # Destroy the dialog
            dialog.Destroy()

            if filename is not None:
                U = field()
                U.open(filename)
                wk = self.currentWorkGroup
                wk.add_field(U)
                wk.Refresh()
Example #28
0
    def createArc(self):
        wk = self.workGroup
        list_P = wk.viewer.MarkerPoints
        if len(list_P) != 3:
            print("You have to specify 3 markers.")
            return

        dlg = edtTxtDialog(None, title="Edit Angle")
        dlg.ShowModal()
        ls_text = dlg.getValue()
        try:
            lr_degree = float(ls_text)
        except:
            lr_degree = 0.0

        theta = lr_degree * pi / 180

        dlg.Destroy()

        A0 = list_P[0]
        A1 = list_P[1]
        A2 = list_P[2]

        knots = [0., 0., 0., 1., 1., 1.]
        C = np.zeros((3, 3))
        C[0, :] = A0[:3]
        C[1, :] = A1[:3]
        C[2, :] = A2[:3]
        weights = [1., cos(theta), 1.]

        nrb = cad_nurbs([knots], C, weights=weights)

        wk.viewer.CleanMarkerPoints()
        geo = cad_geometry()
        geo.append(nrb)
        wk.add_geometry(geometry(geo))
        wk.Refresh()
Example #29
0
    def OnClick(self, event):
        ID = event.GetId()
        if ID == self.BCK_ID:
            self.parent.ShowAction(self.parent.geometryActions)
        if ID == self.GO_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            geoItem = wk.inspector.currentGeometryItem
            _geo = cad_geometry()
            for nrb in geo:
                geo_t = cad_geometry()
                geo_t.append(nrb)

                # ... refinement
                list_t = None
                if self.n.sum() > 0:
                    list_t = []
                    for axis in range(0, nrb.dim):
                        ub = nrb.knots[axis][0]
                        ue = nrb.knots[axis][-1]
                        t = []
                        if self.n[axis] > 0:
                            t = np.linspace(ub, ue, self.n[axis] + 2)[1:-1]
                        list_t.append(t)

                list_p = None
                if self.p.sum() > 0:
                    list_p = []
                    for axis in range(0, nrb.dim):
                        list_p.append(
                            np.max(self.p[axis] - nrb.degree[axis], 0))

                list_m = None
                if self.m.sum() > 0:
                    list_m = []
                    for axis in range(0, nrb.dim):
                        list_m.append(self.m[axis])

                geo_t.refine(list_t=list_t, list_p=list_p, list_m=list_m)
                _geo.append(geo_t[0])

                # macro recording
                if wk.macroRecording:
                    macro_script = wk.macro_script
                    macro_script.new_line()
                    macro_script.append("# ... refine geometry")
                    macro_script.append("_geo = cad_geometry()")

                    geo_id = wk.list_geo.index(geo)
                    macro_script.append("geo_id = " + str(geo_id))
                    macro_script.append("geo = geometries[geo_id]")
                    macro_script.append("for nrb in geo:")
                    macro_script.append("\tgeo_t = cad_geometry()")
                    macro_script.append("\tgeo_t.append(nrb)")

                    str_list_t = [list(ts) for ts in list_t]
                    macro_script.append("\tlist_t = " + str(str_list_t))
                    macro_script.append("\tlist_p = " + str(list_p))
                    macro_script.append("\tlist_m = " + str(list_m))
                    macro_script.append(
                        "\tgeo_t.refine(list_t=list_t, list_p=list_p, list_m=list_m)"
                    )
                    macro_script.append("\t_geo.append(geo_t[0])")
                    macro_script.append("wk.add_geometry(geometry(_geo))")
                    macro_script.append("# ...")
            # ...

            _geo.set_internal_faces(geo.internal_faces)
            _geo.set_external_faces(geo.external_faces)
            _geo.set_connectivity(geo.connectivity)

            geo_new = geometry(_geo)
            geo_newItem = wk.add_geometry(geo_new)
def main():

    import os
    import sys
    sys.path.append('/home/people/tc/svn/Protool/trunk')
    import geometry
    instance_geometry = geometry.geometry()

    ##    fd = open('clusters95.txt','r')
    ##    lines = fd.readlines()
    ##    fd.close()
    ##    d_pdbs = {}
    ##    d_clusters = {}
    ##    for line in lines:
    ##        cluster = int(line.split()[0])
    ##        if cluster not in d_clusters.keys():
    ##            d_clusters[cluster] = []
    ##        pdb = line.split()[2]
    ##        d_clusters[cluster] += [pdb]
    ##    for cluster in d_clusters:
    ##        l_pdbs = d_clusters[cluster]
    ##        if '2LZM:A' in l_pdbs:
    ##            break

    pdb1 = '2lzt'

    ##    l_pdbs = ['189L:A', '1C69:A', '1C6A:A', '1C6B:A', '1D9W:A', '1DYA:A', '1DYB:A', '1DYC:A', '1DYD:A', '1DYE:A', '1DYF:A', '1DYG:A', '1L00:A', '1L02:A', '1L03:A', '1L04:A', '1L05:A', '1L06:A', '1L07:A', '1L08:A', '1L09:A', '1L10:A', '1L11:A', '1L12:A', '1L13:A', '1L14:A', '1L15:A', '1L16:A', '1L17:A', '1L18:A', '1L19:A', '1L20:A', '1L21:A', '1L22:A', '1L23:A', '1L24:A', '1L25:A', '1L26:A', '1L27:A', '1L28:A', '1L29:A', '1L30:A', '1L31:A', '1L32:A', '1L33:A', '1L34:A', '1L37:A', '1L38:A', '1L42:A', '1L43:A', '1L44:A', '1L45:A', '1L46:A', '1L47:A', '1L48:A', '1L52:A', '1L53:A', '1L56:A', '1L57:A', '1L58:A', '1L60:A', '1L69:A', '1L70:A', '1L71:A', '1L96:A', '1L97:A', '1L97:B', '1L98:A', '1L99:A', '1LYD:A', '1T6H:A', '223L:A', '225L:A', '226L:A', '256L:A', '2LZM:A', '3LZM:A', '4LZM:A', '5LZM:A', '6LZM:A', '7LZM:A']
    ##    l_pdbs.remove('%s:A' %(pdb1.upper()))
    ##    l_pdbs.sort()

    l_pdbs = [
        '1sfg:A',
        '1ja7:A',
        '1h6m:A',
    ]

    l_pdbs2 = [
        ## antibody
        ##        '2eiz','2eks','2yss','1a2y','1bql','1bvk','1c08','1fdl','1g7h','1g7i',
        ##        '1g7j','1g7l','1g7m',
        '1mel',
        '1nbz',
        '1yqv',
        '1zvh',
        ## MODRES
        '132l',
        '1at5',
        '1at6',
        ## inhibitor
        '1gpq',
        '1uuz',
        ## deletion
        '1uia',
        '1uib',
        ## glycosylated
        '2b5z',
        ## NMR
        '1e8l',
        ## multiple models
        '1hc0',
        '2d6b',
        ## different length
        '1lsg',
    ]

    l_pdbs_2lzm = [
        ## modified residue
        '1t6h',
        ## beta-mercapto-ethanol
        '1l97',
    ]

    d_coordinates = {}
    d_coordinates[pdb1], l_coordinates1 = parse_coordinates(pdb1, 'A')

    max_rmsd = [0, 0]
    for i in range(len(l_pdbs)):
        pdb = l_pdbs[i][:4].lower()
        chain = l_pdbs[i][-1]
        if pdb in l_pdbs_2lzm:
            continue


##        if i+1 < int(sys.argv[1]):
##            continue
        d_coordinates[pdb], l_coordinates2 = parse_coordinates(pdb, chain)
        if len(l_coordinates1) == 164 and len(l_coordinates2) in [
                162,
                163,
        ]:
            rmsd = instance_geometry.superpose(
                l_coordinates1[:len(l_coordinates2)], l_coordinates2)
        elif len(l_coordinates1) != len(l_coordinates2):
            print pdb, chain, len(l_coordinates1), len(l_coordinates2)
            stop
        else:
            rmsd = instance_geometry.superpose(l_coordinates1, l_coordinates2)
        tv1 = instance_geometry.fitcenter
        rm = instance_geometry.rotation
        tv2 = instance_geometry.refcenter
        print pdb, chain, i + 1, len(l_pdbs), rmsd
        if rmsd > max_rmsd[1]:
            max_rmsd = [pdb, rmsd]

    print max_rmsd

    return
Example #31
0
from geometry import geometry

nom, denom = map(int, input().split())
n = int(input())
prec = 3

print(round(geometry(n, nom / denom), prec))
Example #32
0
    def main(
        self, jobid, lines, atoms_hessian = ['CA'], frames = 51,
        cutoff_distance = 10.,
        path_html = None, path_python = None, verbose = False, paralleldir = '',
        biomolecule = None, chains = [], model = None,
        winsize = 1, stepsize = 1,
        ):

        '''
        Use first model if no model specified by user.
        chain(s): Y, biomolecule: Y; parse chains specified by user and apply transformation
        chain(s): Y, biomolecule: N; parse chains specified by user but don't apply transformation
        chain(s): N, biomolecule: Y; parse chains of biomolecule and apply transformation
        chain(s): N, biomolecule: N; parse chains of first biomolecule and apply transformation
        '''

        import os, Numeric, goodvibes_core

        if stepsize not in [1,winsize]:
            raise 'stepsize must be 1 or equal to winsize'

        results = []

        ## parse pdb
        (
            d_REMARK350,
            d_primary, ## i.e. SEQRES, MODRES
            d_secondary, ## i.e. HELIX, SHEET
            d_coordinates, ## i.e. ATOM, HETATM, TER, MODEL, ENDMDL
            ) = self.parse_pdb(lines, chains, model)

        ## assume multimeric biological unit if chains not specified by user
        if chains == []:
            chains = d_coordinates['chains'].keys()
            chains.sort()

        ##
        ## d_coordinates to l_coordinates
        ##
        l_coordinates = []
        for chain in chains:
            ## assuming sequential numbering of residues
            res_nos = d_coordinates['chains'][chain]['residues'].keys()
            res_nos.sort()
            for res_no in res_nos:
                for iCode in d_coordinates['chains'][chain]['residues'][res_no]['iCodes'].keys():
                    altloc = min(d_coordinates['chains'][chain]['residues'][res_no]['iCodes'][iCode]['altlocs'].keys())
                    for atom_name in d_coordinates['chains'][chain]['residues'][res_no]['iCodes'][iCode]['altlocs'][altloc]['atoms'].keys():
                        if atom_name in atoms_hessian:
                            coordinate = d_coordinates['chains'][chain]['residues'][res_no]['iCodes'][iCode]['altlocs'][altloc]['atoms'][atom_name]['coordinate']
                            d_coordinates['chains'][chain]['residues'][res_no]['iCodes'][iCode]['altlocs'][altloc]['atoms'][atom_name]['hessian'] = True
                            l_coordinates += [coordinate]

        ## cluster coordinates
        l_coordinates = [sum(l_coordinates[i:i+winsize])/winsize for i in range(0,len(l_coordinates),winsize)]
        N = len(l_coordinates)

        ## calculate intra-residue distances
        matrix_distance_residue_intra = self.distance_residue_intra(l_coordinates)

        ## for the non-disrupted structure: calculate and visualize eigenvectors
        matrix_hessian = self.hessian_calculation(l_coordinates, float(cutoff_distance), verbose)
        eigenvectors_nonperturbed, eigenvalues_nonperturbed, eigenvectors_combined_nonperturbed = self.eigenv_calccomb(matrix_hessian, jobid, verbose)
        import math
        d_energies = {}
        d_factors = {}


        ## read pdb2
        pdb2 = '2lzm'
        chains2 = ['A']
        fd = open('/oxygenase_local/data/pdb/%s/pdb%s.ent' %(pdb2[1:3],pdb2,),'r')
        lines2 = fd.readlines()
        fd.close()
        ## parse pdb2
        (
            d_REMARK350_2,
            d_primary2, ## i.e. SEQRES, MODRES
            d_secondary2, ## i.e. HELIX, SHEET
            d_coordinates2, ## i.e. ATOM, HETATM, TER, MODEL, ENDMDL
            d_ligands2,
            ) = goodvibes_core.parse_pdb(lines2, chains2)
        N2, d_hessian2, l_coordinates2 = goodvibes_core.parse_dictionary_of_coordinates(d_coordinates2, chains2, atoms_hessian)

        ## rotate coordinates2
        import sys, numpy
        sys.path.append('/home/people/tc/svn/Protool/')
        import geometry
        instance_geometry = geometry.geometry()
        rmsd = instance_geometry.superpose(l_coordinates[:-2],l_coordinates2)
        print 'rmsd', rmsd
        tv1 = instance_geometry.fitcenter
        rm = instance_geometry.rotation
        tv2 = instance_geometry.refcenter
        for i in range(len(l_coordinates2)):
            coord = l_coordinates2[i]
            tcoord = numpy.dot(coord-tv1,rm)+tv2
            l_coordinates2[i] = tcoord

        ## calculate coordinates2 energies
        V = 0
        E = 0
        l_E = []
        maxi = [0,'N/A',]
        mini = 9999
        lines_rasmol_colors = []
        for i in range(0,len(l_coordinates2)*3,3):

            res_index1 = i/3
            xa1 = l_coordinates[res_index1][0]
            ya1 = l_coordinates[res_index1][1]
            za1 = l_coordinates[res_index1][2]
            xa2 = l_coordinates2[res_index1][0]
            ya2 = l_coordinates2[res_index1][1]
            za2 = l_coordinates2[res_index1][2]

            E = 0

            for j in range(0,len(l_coordinates2)*3,3):

                if i == j:
                    continue

                res_index2 = j/3
                xb1 = l_coordinates[res_index2][0]
                yb1 = l_coordinates[res_index2][1]
                zb1 = l_coordinates[res_index2][2]
                xb2 = l_coordinates2[res_index2][0]
                yb2 = l_coordinates2[res_index2][1]
                zb2 = l_coordinates2[res_index2][2]

                kx = matrix_hessian[i+0][j+0]
                ky = matrix_hessian[i+1][j+1]
                kz = matrix_hessian[i+2][j+2]

##                        k = math.sqrt(kx**2+ky**2+kz**2)
##                        E = .5*kx*(vx**2)+.5*ky*(vy**2)+.5*kz*(vz**2)

##                        E -= .5*kx*((vxb-vxa)**2)+.5*ky*((vyb-vya)**2)+.5*kz*((vzb-vza)**2)
                E -= .5*kx*(((xb2-xa2)-(xb1-xa1))**2)+.5*ky*(((yb2-ya2)-(yb1-ya1))**2)+.5*kz*(((zb2-za2)-(zb1-za1))**2)

                if E < mini:
                    mini = E
                if E > maxi[0]:
                    maxi = [E,res_index1]

            l_E += [E/0.39]

            index = E/0.39

            h = 159.+80*index/100.
            s = 240.
            l = 120.+120.*(50-abs(index-50))/50.
            r,g,b = self.hsl2rgb(h,s,l,)

            lines_rasmol_colors += [
                'select %i\n' %(res_index1+1),
                'color [%i,%i,%i]\n' %(
                    r, g, b,
                    )
                ]


        lines_pdb2_rotated = []
        ## rotate pdb
        for line in lines2:
            record = line[:6].strip()
            if record == 'HETATM':
                continue
            elif record != 'ATOM':
                lines_pdb2_rotated += [line]
                continue
            if line[21] not in chains2:
                continue
            x = float(line[30:38])
            y = float(line[38:46])
            z = float(line[46:54])
            coordinate = numpy.array([x,y,z,])
            coordinate = numpy.dot(coordinate-tv1,rm)+tv2
            bfactor = float(line[60:66])
            line_rotated = '%s%8.3f%8.3f%8.3f%s%6.2f%s' %(
                line[:30],
                coordinate[0],coordinate[1],coordinate[2],
                line[54:60],bfactor,line[66:]
                )
            lines_pdb2_rotated += [line_rotated]
        fd = open('%s_rotated.pdb' %(pdb2),'w')
        fd.writelines(lines_pdb2_rotated)
        fd.close()
            
        ## write rasmol script
        lines = [
            'rasmol -nodisplay %s_rotated.pdb << EOF\n' %(pdb2),
            'cartoon\n',
            'wireframe 0\n',
##                    'ribbons\n',
##                    'color temperature\n',
            ]

        lines += lines_rasmol_colors

        lines += [
##                    'ribbons\n',
            'rotate x 100\n',
            'rotate z 30\n',
            'rotate x 100\n',
            'rotate z 90\n',
            'rotate x 40\n',
            'rotate y -20\n',
            'write 150l.ppm\n',
            'exit\n',
            ]
        ## write rasmol script to file
        fd = open('rasmol.src','w')
        fd.writelines(lines)
        fd.close()
        ## execute rasmol script
        os.system('source rasmol.src > rasmol.log')
        ## convert rasmol output
        os.system('convert 150l.ppm 150l.gif')
        ## clean up
        os.remove('150l.ppm')
        os.remove('rasmol.log')
##        os.remove('rasmol.src')

        print l_E
        print 'minmax', mini,maxi
            
##        self.morph(
##            eigenvectors_nonperturbed, frames, chains, d_coordinates, atoms_hessian, matrix_hessian, jobid,
##            d_energies,d_factors,
##            )

        return results
Example #33
0
def default_geo():
    module_box = geo.box(100.0 * cm, 300.0 * cm, 100 * cm)
    geometry = geo.geometry([module_box], zero)
    return geometry
def main():

    set_pdbs = exclude_include()
    l_pdbs_remove = [
        '4a3h','2wf5','1arl','1ee3', ## incorrect _struct_ref_seq.pdbx_db_accession
        '1uyd','1uye','1uyf','2byh','2byi', ## remediation _struct_ref_seq_dif
        '2xdu','3dn8','3dna','1ps3','1ouf','1l35','2eun','1rtc','1zon', ## _struct_ref_seq_dif missing
        '1pwl','1pwm','2fz8','2fz9', ## remediation incorrect _struct_ref.pdbx_seq_one_letter_code
        ]
    set_pdbs.remove('1f92') ## remediation _struct_ref_seq_dif incorrect residue number
    set_pdbs.remove('2f6f') ## remediation _pdbx_poly_seq_scheme.auth_mon_id wrong
    set_pdbs.remove('3a5j') ## remediation _struct_ref_seq_dif.db_mon_id is ? but should be MET
    set_pdbs.remove('2rhx') ## remediation _struct_ref_seq_dif.db_mon_id is ? but should be SER
    set_pdbs.remove('2fzb') ## remediation incorrect _struct_ref.pdbx_seq_one_letter_code
    set_pdbs.remove('2fzd') ## remediation incorrect _struct_ref.pdbx_seq_one_letter_code
    set_pdbs.remove('3dn5') ## remediation incorrect _struct_ref.pdbx_seq_one_letter_code
    set_pdbs.remove('1x96') ## remediation incorrect _struct_ref.pdbx_seq_one_letter_code
    set_pdbs.remove('1x97') ## remediation incorrect _struct_ref.pdbx_seq_one_letter_code
    set_pdbs.remove('1x98') ## remediation incorrect _struct_ref.pdbx_seq_one_letter_code
    set_pdbs.remove('1z3n') ## GenBank DBref - not an error...
    set_pdbs.remove('1z8a') ## GenBank DBref - not an error...
    set_pdbs.remove('1z89') ## GenBank DBref - not an error...
    set_pdbs.remove('2pf8') ## stupid use of alt_ids (C for highest occupancy and only altloc)
    set_pdbs.remove('2pyr') ## stupid use of alt_ids (G and R)
    set_pdbs.remove('3pdn') ## stupid use of alt_ids (B and C)
    set_pdbs.remove('2v4c') ## alt_id B used for 100% occupancy atoms
    set_pdbs.remove('1jxt') ## weird alt_id microheterogeneity...
    set_pdbs.remove('1jxu') ## weird alt_id microheterogeneity...
    set_pdbs.remove('1jxw') ## weird alt_id microheterogeneity...
    set_pdbs.remove('1jxx') ## weird alt_id microheterogeneity...
    set_pdbs.remove('1jxy') ## weird alt_id microheterogeneity...
##    set_pdbs.remove('1ac4') ## multiple strains and taxonomy ids but all same organism (S. cerevisiae)...
##    set_pdbs.remove('1ac8') ## multiple strains and taxonomy ids but all same organism (S. cerevisiae)...
##    set_pdbs.remove('1aeb') ## multiple strains and taxonomy ids but all same organism (S. cerevisiae)...
##    set_pdbs.remove('2rbt') ## multiple strains and taxonomy ids but all same organism (S. cerevisiae)... UNP A7A026, TAX 307796, STRAIN YJM789
##    set_pdbs.remove('2rbu') ## multiple strains and taxonomy ids but all same organism (S. cerevisiae)... UNP A7A026, TAX 307796, STRAIN YJM789
##    set_pdbs.remove('2rbv') ## multiple strains and taxonomy ids but all same organism (S. cerevisiae)... UNP A7A026, TAX 307796, STRAIN YJM789
    for pdb in l_pdbs_remove:
        set_pdbs.remove(pdb)

    fd = open('%s/bc-100.out' %(path_mmCIF),'r')
    lines = fd.readlines()
    fd.close()

    for i_line in range(len(lines)):
        cluster = i_line
        if cluster < 4816:
            continue
##        if cluster not in [5,]:
##            continue
        line = lines[i_line]
        l_pdbs = line.lower().split()
        l_pdbs.sort()
        for i_pdb in range(len(l_pdbs)):
            l_pdbs[i_pdb] = l_pdbs[i_pdb][:4]

        for i_pdb1 in range(0,len(l_pdbs)-1):

            pdb1 = l_pdbs[i_pdb1]

##            if pdb1 != '1t49': ## tmp!!!
##                continue

            if not pdb1 in set_pdbs:
                continue

            print pdb1
            stop

            d_mmCIF1 = parse_mmCIF.main(pdb1,)

            bool_monomeric = check_monomeric(d_mmCIF1)
            if bool_monomeric == False:
                if i_pdb1 == 0:
                    break
                else:
                    continue

            bool_remediation_modres = check_modres(d_mmCIF1,pdb1,)
            if bool_remediation_modres == True:
                continue

            if '_struct_ref_seq_dif.details' in d_mmCIF1.keys():
                if 'DELETION' in d_mmCIF1['_struct_ref_seq_dif.details']:
                    continue

            for i_entity in range(len(d_mmCIF1['_entity.id'])):
                if d_mmCIF1['_entity.type'][i_entity] == 'polymer':
                    if int(d_mmCIF1['_entity.pdbx_number_of_molecules'][i_entity]) != 1:
                        print d_mmCIF1['_entity.pdbx_number_of_molecules']
                        print pdb1, cluster
                        stop

            SG1 = d_mmCIF1['_symmetry.space_group_name_H-M']

            for i_pdb2 in range(i_pdb1+1,len(l_pdbs)):

                pdb2 = l_pdbs[i_pdb2]

##                if pdb2 != '2pf8': ## tmp!!!
##                    continue

##                if pdb1 != '3fui' or pdb2 != '3fuj':
##                    continue

                if not pdb2 in set_pdbs:
                    continue

                d_mmCIF2 = parse_mmCIF.main(pdb2,)

                bool_monomeric = check_monomeric(d_mmCIF2)
                if bool_monomeric == False:
                    continue

                bool_remediation_modres = check_modres(d_mmCIF2,pdb2,)
                if bool_remediation_modres == True:
                    continue

                if '_struct_ref_seq_dif.seq_num' in d_mmCIF2.keys():
                    if 'DELETION' in d_mmCIF2['_struct_ref_seq_dif.details']:
                        continue

                ## biounit monomeric?
                for i_entity in range(len(d_mmCIF2['_entity.id'])):
                    if d_mmCIF2['_entity.type'][i_entity] == 'polymer':
                        if int(d_mmCIF2['_entity.pdbx_number_of_molecules'][i_entity]) != 1:
                            continue

                SG2 = d_mmCIF2['_symmetry.space_group_name_H-M']

                if SG1 != SG2:
                    continue

                ## parse coordinates again after being shortened in previous loop
                try:
                    d_coords1, l_coords_alpha1 = mmCIF2coords.main(pdb1, d_mmCIF1)
                except:
                    fd = open('remediation_atom_site.label_alt_id.txt','a')
                    fd.write('%s\n' %(pdb1,))
                    fd.close()
                try:
                    d_coords2, l_coords_alpha2 = mmCIF2coords.main(pdb2, d_mmCIF2)
                except:
                    fd = open('remediation_atom_site.label_alt_id.txt','a')
                    fd.write('%s\n' %(pdb2,))
                    fd.close()

                ## align sequences/coordinates
                try:
                    l_coords_alpha1, l_coords_alpha2 = create_apo_holo_dataset.sequential_alignment_of_coordinates(
                        l_coords_alpha1, l_coords_alpha2,
                        d_mmCIF1, d_mmCIF2,
                        pdb1, pdb2,
                        )
                except:
                    fd = open('remediation_struct_ref_seq_dif.txt','a')
                    fd.write(
                        '%s %s %s %s\n' %(
                            pdb1,pdb2,
                            d_mmCIF1['_struct_ref_seq.pdbx_db_accession'],
                            d_mmCIF2['_struct_ref_seq.pdbx_db_accession'],
                            )
                        )
                    fd.close()
                    continue
                if len(l_coords_alpha1) != len(l_coords_alpha2):
                    print d_mmCIF1['_pdbx_poly_seq_scheme.pdb_mon_id']
                    print d_mmCIF2['_pdbx_poly_seq_scheme.pdb_mon_id']
                    print 'coords', len(l_coords_alpha1), len(l_coords_alpha2)
                    print 'seq', len(d_mmCIF1['_pdbx_poly_seq_scheme.pdb_mon_id'])
                    print 'seq', len(d_mmCIF2['_pdbx_poly_seq_scheme.pdb_mon_id'])
                    print pdb1, pdb2
                    d_coords1, l_coords_alpha1 = mmCIF2coords.main(pdb1, d_mmCIF1)
                    d_coords1, l_coords_alpha2 = mmCIF2coords.main(pdb1, d_mmCIF2)
                    print len(l_coords_alpha1), len(l_coords_alpha2)
                    stop
                    continue

                ##
                ## align structure 1 and 2
                ##
                instance_geometry = geometry.geometry()
                rmsd = instance_geometry.superpose(l_coords_alpha1,l_coords_alpha2)
                tv1 = instance_geometry.fitcenter
                rm = instance_geometry.rotation
                tv2 = instance_geometry.refcenter

                ## structural alignment
                for i_coord in range(len(l_coords_alpha2)):
                    l_coords_alpha2[i_coord] = numpy.dot(l_coords_alpha2[i_coord]-tv1,rm)+tv2

                ##
                ## vector from structure 1 to 2
                ##
                vector = []
                for i in range(len(l_coords_alpha1)):
                    vector += [
                        l_coords_alpha1[i][0]-l_coords_alpha2[i][0],
                        l_coords_alpha1[i][1]-l_coords_alpha2[i][1],
                        l_coords_alpha1[i][2]-l_coords_alpha2[i][2],
                        ]
                vector = numpy.array(vector)

                ##
                ## calculate normal modes of structure 1
                ##
                cutoff = 10
                try:
                    matrix_hessian1 = NMA.hessian_calculation(l_coords_alpha1, cutoff, verbose = False)
                    eigenvectors1, eigenvalues1 = NMA.diagonalize_hessian(matrix_hessian1, verbose = False)
                    matrix_hessian2 = NMA.hessian_calculation(l_coords_alpha2, cutoff, verbose = False)
                    eigenvectors2, eigenvalues2 = NMA.diagonalize_hessian(matrix_hessian2, verbose = False)
                except:
                    continue

                ##
                ## calculate overlap between normal modes and difference vector
                ##
                eigenvector1 = eigenvectors1[6]
                eigenvector2 = eigenvectors2[6]

                overlap1 = calc_overlap(eigenvector1,vector)
                overlap2 = calc_overlap(eigenvector2,vector)
                overlap3a = calc_overlap(eigenvector1,eigenvector2)
                overlap3b = calc_overlap(eigenvectors1[6],eigenvectors2[7])
                overlap3c = calc_overlap(eigenvectors1[7],eigenvectors2[6])
                overlap3 = max(overlap3a,overlap3b,overlap3c)

                fd = open('rmsd_v_overlap2/cluster%i.txt' %(i_line),'a')
                fd.write('%s %s\n' %(rmsd,overlap1))
                fd.close()
                fd = open('rmsd_v_overlap2/cluster%i.txt' %(i_line),'a')
                fd.write('%s %s\n' %(rmsd,overlap2))
                fd.close()
                fd = open('rmsd_v_overlap2/cluster%i_ev_v_ev.txt' %(i_line),'a')
                fd.write('%s %s\n' %(rmsd,overlap3a))
                fd.close()
                fd = open('rmsd_v_overlap2/cluster%i_ev_v_ev_max.txt' %(i_line),'a')
                fd.write('%s %s\n' %(rmsd,overlap3))
                fd.close()
                print pdb1, pdb2, 'cluster', i_line, 'size', len(l_pdbs),
                print 'overlap', '%4.2f' %(round(overlap1,2)), '%4.2f' %(round(overlap2,2)), '%4.2f' %(round(overlap3,2)), 'rmsd', '%4.2f' %(round(rmsd,2))

    return
Example #35
0
            surfaceloop | volume | physicalsurface | physicalvolume | comment \
            | skip1

    grammar = OneOrMore(command) + StringEnd()

    try:
        tokens = grammar.parseFile(filename)
    except ParseException, err:
        print err.line
        print " " * (err.column - 1) + "^"
        print err
        raise err

    lineloops = {}
    surfaceloops = {}
    g = geom.geometry()
    for x in tokens:
        if x[0] == "Point":
            g.addpoint(int(x[1]),
                       [float(x[2][0]),
                        float(x[2][1]),
                        float(x[2][2])])
        elif x[0] == "Line":
            assert len(x[2]) == 2
            g.addline(int(x[1]), [int(x[2][0]), int(x[2][1])])
        elif x[0] == "Circle":
            assert len(x[2]) == 3
            g.addline(int(x[1]), [int(x[2][0]), int(x[2][2])])
            #g.add1(geom.circle(int(x[1]),int(x[2][0]),int(x[2][1]),
            #    int(x[2][2])))
        elif x[0] == "Line Loop":
def main():

    import os
    import sys
    sys.path.append('/home/people/tc/svn/Protool/trunk')
    import geometry
    instance_geometry = geometry.geometry()

##    fd = open('clusters95.txt','r')
##    lines = fd.readlines()
##    fd.close()
##    d_pdbs = {}
##    d_clusters = {}
##    for line in lines:
##        cluster = int(line.split()[0])
##        if cluster not in d_clusters.keys():
##            d_clusters[cluster] = []
##        pdb = line.split()[2]
##        d_clusters[cluster] += [pdb]
##    for cluster in d_clusters:
##        l_pdbs = d_clusters[cluster]
##        if '2LZM:A' in l_pdbs:
##            break

    pdb1 = '2lzt'

##    l_pdbs = ['189L:A', '1C69:A', '1C6A:A', '1C6B:A', '1D9W:A', '1DYA:A', '1DYB:A', '1DYC:A', '1DYD:A', '1DYE:A', '1DYF:A', '1DYG:A', '1L00:A', '1L02:A', '1L03:A', '1L04:A', '1L05:A', '1L06:A', '1L07:A', '1L08:A', '1L09:A', '1L10:A', '1L11:A', '1L12:A', '1L13:A', '1L14:A', '1L15:A', '1L16:A', '1L17:A', '1L18:A', '1L19:A', '1L20:A', '1L21:A', '1L22:A', '1L23:A', '1L24:A', '1L25:A', '1L26:A', '1L27:A', '1L28:A', '1L29:A', '1L30:A', '1L31:A', '1L32:A', '1L33:A', '1L34:A', '1L37:A', '1L38:A', '1L42:A', '1L43:A', '1L44:A', '1L45:A', '1L46:A', '1L47:A', '1L48:A', '1L52:A', '1L53:A', '1L56:A', '1L57:A', '1L58:A', '1L60:A', '1L69:A', '1L70:A', '1L71:A', '1L96:A', '1L97:A', '1L97:B', '1L98:A', '1L99:A', '1LYD:A', '1T6H:A', '223L:A', '225L:A', '226L:A', '256L:A', '2LZM:A', '3LZM:A', '4LZM:A', '5LZM:A', '6LZM:A', '7LZM:A']
##    l_pdbs.remove('%s:A' %(pdb1.upper()))
##    l_pdbs.sort()

    l_pdbs = ['1sfg:A','1ja7:A','1h6m:A',]

    l_pdbs2 = [
        ## antibody
##        '2eiz','2eks','2yss','1a2y','1bql','1bvk','1c08','1fdl','1g7h','1g7i',
##        '1g7j','1g7l','1g7m',
        '1mel','1nbz','1yqv','1zvh',
        ## MODRES
        '132l','1at5','1at6',
        ## inhibitor
        '1gpq','1uuz',
        ## deletion
        '1uia','1uib',
        ## glycosylated
        '2b5z',
        ## NMR
        '1e8l',
        ## multiple models
        '1hc0','2d6b',
        ## different length
        '1lsg',
        ]

    l_pdbs_2lzm = [
        ## modified residue
        '1t6h',
        ## beta-mercapto-ethanol
        '1l97',
        ]

    d_coordinates = {}
    d_coordinates[pdb1],l_coordinates1 = parse_coordinates(pdb1,'A')

    max_rmsd = [0,0]
    for i in range(len(l_pdbs)):
        pdb = l_pdbs[i][:4].lower()
        chain = l_pdbs[i][-1]
        if pdb in l_pdbs_2lzm:
            continue
##        if i+1 < int(sys.argv[1]):
##            continue
        d_coordinates[pdb],l_coordinates2 = parse_coordinates(pdb,chain)
        if len(l_coordinates1) == 164 and len(l_coordinates2) in [162,163,]:
            rmsd = instance_geometry.superpose(l_coordinates1[:len(l_coordinates2)],l_coordinates2)
        elif len(l_coordinates1) != len(l_coordinates2):
            print pdb, chain, len(l_coordinates1), len(l_coordinates2)
            stop
        else:
            rmsd = instance_geometry.superpose(l_coordinates1,l_coordinates2)
        tv1 = instance_geometry.fitcenter
        rm = instance_geometry.rotation
        tv2 = instance_geometry.refcenter
        print pdb, chain, i+1, len(l_pdbs), rmsd
        if rmsd > max_rmsd[1]:
            max_rmsd = [pdb,rmsd]

    print max_rmsd
    
    return
def main(
    pdb1,
    pdb2,
    chains1_align,
    chains2_align,
):

    chains1_apply = chains1_align
    chains2_apply = chains2_align

    import os, sys, math
    sys.path.append('/home/people/tc/svn/Protool/')
    import geometry
    instance_geometry = geometry.geometry()

    domain_range = range(0, 9999)

    os.system('cp /data/pdb-v3.2/%s/pdb%s.ent %s.pdb' % (
        pdb1[1:3],
        pdb1,
        pdb1,
    ))
    os.system('cp /data/pdb-v3.2/%s/pdb%s.ent %s.pdb' % (
        pdb2[1:3],
        pdb2,
        pdb2,
    ))

    ss_range1, l_missing1, seqres1, l_modres = parse_header(
        pdb1,
        chains1_align,
    )
    ss_range2, l_missing2, seqres2, l_modres = parse_header(
        pdb2,
        chains2_align,
    )

    ss_range = list(set(ss_range1) & set(ss_range2))
    l_missing = list(set(l_missing1) | set(l_missing2))

    if len(seqres1) != len(seqres2):
        d_replace = {
            'TPO': 'THR',
            'PTR': 'TYR',
            ##                'SER':'CYS', ## 1tde v 1f6m
        }
        for i in range(len(seqres1)):
            if seqres1[i] in d_replace.keys():
                seqres1[i] = d_replace[seqres1[i]]
        for i in range(len(seqres2)):
            if seqres2[i] in d_replace.keys():
                seqres2[i] = d_replace[seqres2[i]]
        if not (''.join(seqres1) in ''.join(seqres2)
                or ''.join(seqres2) in ''.join(seqres1)):
            import sys
            sys.path.append('/home/people/tc/svn/EAT_DB/')
            import sequence_alignment
            d_res = {
                'ALA': 'A',
                'CYS': 'C',
                'ASP': 'D',
                'GLU': 'E',
                'PHE': 'F',
                'GLY': 'G',
                'HIS': 'H',
                'ILE': 'I',
                'LYS': 'K',
                'LEU': 'L',
                'MET': 'M',
                'ASN': 'N',
                'PRO': 'P',
                'GLN': 'Q',
                'ARG': 'R',
                'SER': 'S',
                'THR': 'T',
                'VAL': 'V',
                'TRP': 'W',
                'TYR': 'Y',
            }
            seq1 = ''
            for res in seqres1:
                seq1 += d_res[res]
            seq2 = ''
            for res in seqres2:
                seq2 += d_res[res]
            instance = sequence_alignment.NW(seq1, seq2)
            s1, s2 = instance.Align(verbose=False)[:2]
            l1 = len(s1) - len(s1.lstrip('-'))
            l2 = len(s2) - len(s2.lstrip('-'))
            r1 = len(s1) - len(s1.rstrip('-'))
            r2 = len(s2) - len(s2.rstrip('-'))
            print seqres1
            print seqres2
            print len(seqres1)
            print len(seqres2)
            print pdb1, pdb2
            print l1, l2, r1, r2
            print seqres2[l1:len(seqres2) - r1]
            print seqres1[l2:len(seqres1) - r2]
        else:
            s1 = ''.join(seqres1)
            s2 = ''.join(seqres2)
            if s1 in s2:
                seqres2 = seqres2[s2.index(s1) / 3:]
            else:
                seqres1 = seqres1[s1.index(s2) / 3:]
            if len(seqres1) != len(seqres2):
                print len(seqres1), len(seqres2)
                stop

    l_coordinates1 = parse_coordinates(
        pdb1,
        chains1_align,
        domain_range,
        ss_range,
        l_missing,
    )
    l_coordinates2 = parse_coordinates(
        pdb2,
        chains2_align,
        domain_range,
        ss_range,
        l_missing,
    )

    ##        l_coordinates1 = l_coordinates1[l2:len(l_coordinates1)-r2]
    ##        l_coordinates2 = l_coordinates2[l1:len(l_coordinates2)-r1]

    if len(l_coordinates1) == 0 or len(l_coordinates2) == 0:
        stop

    if len(l_coordinates1) != len(l_coordinates2):
        print len(l_coordinates1)
        print len(l_coordinates2)
        stop

    rmsd = instance_geometry.superpose(l_coordinates1, l_coordinates2)
    print pdb1, pdb2
    print 'rmsd', round(rmsd, 1)
    print 'residues', len(seqres1), len(seqres2)
    print 'coordinates', len(l_coordinates1)
    tv1 = instance_geometry.fitcenter
    rm = instance_geometry.rotation
    tv2 = instance_geometry.refcenter

    lines1 = apply_transformation_matrix(
        pdb1,
        chains1_apply,
        l_modres,
        [0, 0, 0],
        [[1, 0, 0], [0, 1, 0], [0, 0, 1]],
        [0, 0, 0],
    )
    lines2 = apply_transformation_matrix(
        pdb2,
        chains2_apply,
        l_modres,
        tv1,
        rm,
        tv2,
    )

    fd = open('rotated_%s%s.pdb' % (
        pdb1,
        pdb2,
    ), 'w')
    fd.writelines(lines1 + lines2)
    fd.close()

    l_coordinates1 = parse_coordinates(
        'rotated_' + pdb1,
        chains1_apply,
        range(-9999, 9999),
        ss_range,
        l_missing,
    )
    l_coordinates2 = parse_coordinates(
        'rotated_' + pdb2,
        chains2_apply,
        range(-9999, 9999),
        ss_range,
        l_missing,
    )

    SUM = 0.
    n = len(l_coordinates1)
    for i in range(n):
        SUM += sum((l_coordinates1[i] - l_coordinates2[i])**2)
    RMSD = math.sqrt(SUM / n)
    print 'RMSD all atoms', RMSD

    return RMSD, l_coordinates1, l_coordinates2
def main():

    import os, sys, math
    sys.path.append('/home/people/tc/svn/Protool/')
    import geometry
    instance_geometry = geometry.geometry()

##    ## lactoferrin
##    pdb1 = '1lfg'
##    pdb2 = '1lfh'
##    domain_range = range(1,88+1)+range(253,333+1)
##    chain = 'A'

##    ## trp repressor
##    pdb1 = '1wrp'
##    pdb2 = '2oz9' ## 2wrp
##    pdb2 = '1zt9' 
##    domain_range = range(1,999+1)
##    chain1 = 'R'
##    chain2 = 'R'
##    chain2 = 'A'
##    exclude_chain = ''

##    ## luciferase
##    pdb1 = '1ba3'
##    pdb2 = '1lci'
##    domain_range = range(1,999+1)
##    chain1 = 'A'
##    chain2 = 'A'
##    exclude_chain = ''

##    ## G3P DH
##    pdb1 = '1gd1'
##    pdb2 = '2gd1'
##    domain_range = range(1,999+1)
##    chain1 = 'O'
##    chain2 = 'O'
##    exclude_chain = ''

##    ## hexokinase
##    pdb1 = '1hkg'
##    pdb2 = '2yhx'
##    domain_range = range(1,999+1)
##    chain1 = 'A'
##    chain2 = 'A'
##    exclude_chain = ''

##    ## adk
##    pdb1 = '1ake'
##    pdb2 = '4ake'
##    domain_range = range(1,999+1)
##    chain1 = 'A'
##    chain2 = 'A'
##    exclude_chain = 'B'

##    ## t4l
##    pdb1 = '2lzm'
##    pdb2 = '150l'
####    domain_range = range(15,59+1)
####    domain_range = range(60,80+1)
##    domain_range = range(81,162+1)
##    chain1 = 'A'
##    chain2 = 'D'
##    exclude_chain = 'B'

    l_input = [
##        ##
##        {'pdb1':'1ipd','pdb2':'1osj','chain1':'A','chain2':'A','range':range(1,98+1)+range(253,345+1)},
##        {'pdb1':'1ipd','pdb2':'1osj','chain1':'A','chain2':'A','range':range(99,108+1)+range(109,252+1)},
###### shears
##        ## aspartate amino transferase
##        {'pdb1':'9aat','pdb2':'1ama','chain1':'A','chain2':'A','range':range(15,36+1)+range(349,410+1)},
##        {'pdb1':'9aat','pdb2':'1ama','chain1':'A','chain2':'A','range':range(50,312+1)},
        ## alcohol dehydrogenase
        {'pdb1':'6adh','pdb2':'8adh1','chain1':'A','chain2':'A','range':range(1,174+1)+range(322,374+1)},
        {'pdb1':'6adh','pdb2':'8adh2','chain1':'A','chain2':'A','range':range(193,317+1)},
##        ## citrate synthase
##        {'pdb1':'1cts','pdb2':'4cts','chain1':'A','chain2':'A','range':range(1,276+1)+range(386,999+1)},
###### hinges
##        ## atpsulf
##        {'pdb1':'1i2d','pdb2':'1m8p','chain1':'A','chain2':'A','range':range(1,389+1)},
##        ## dnak (different spacegroups)
##        {'pdb1':'1dkx','pdb2':'1dky','chain1':'A','chain2':'A','range':range(389,509+1)},
##        ## dnak (different spacegroups)
##        {'pdb1':'1ddt','pdb2':'1mdt','chain1':'A','chain2':'A','range':range(1,376+1)},
##        ## ecpdpbp
##        {'pdb1':'1dpp','pdb2':'1dpe','chain1':'A','chain2':'A','range':range(1,260+1)+range(479,999+1)},
##        ## ef2
##        {'pdb1':'1n0v','pdb2':'1n0u','chain1':'C','chain2':'A','range':range(1,478+1)}, ## large
##        {'pdb1':'1n0v','pdb2':'1n0u','chain1':'C','chain2':'A','range':range(479,560+1)}, ## independent
##        {'pdb1':'1n0v','pdb2':'1n0u','chain1':'C','chain2':'A','range':range(561,9999+1)}, ## small
##        ## febp
##        {'pdb1':'1d9v','pdb2':'1mrp','chain1':'A','chain2':'A','range':range(109,227+1)+range(292,309+1)},
##        {'pdb1':'1d9v','pdb2':'1mrp','chain1':'A','chain2':'A','range':range(1,96+1)+range(228,262+1)},
##        ## folylpolyglutamate synthetase
##        {'pdb1':'1jbv','pdb2':'1jbw','chain1':'A','chain2':'A','range':range(1,295+1)},
##        {'pdb1':'1jbv','pdb2':'1jbw','chain1':'A','chain2':'A','range':range(296,386+1)},
##        ## glucose ABC transporter ATPase subunit (different spacegroups)
##        {'pdb1':'1oxs','pdb2':'1oxu','chain1':'C','chain2':'C','range':range(1,209+1)},
##        {'pdb1':'1oxs','pdb2':'1oxu','chain1':'C','chain2':'C','range':range(244,999+1)},
##        ## groel domain
##        {'pdb1':'1aon','pdb2':'1oel','chain1':'A','chain2':'A','range':range(1,137+1)+range(410,999+1)},
##        {'pdb1':'1aon','pdb2':'1oel','chain1':'A','chain2':'A','range':range(192,374+1)},
##        {'pdb1':'1aon','pdb2':'1oel','chain1':'A','chain2':'A','range':range(138,190+1)+range(375,409+1)},
##        ## lao bp
##        {'pdb1':'2lao','pdb2':'1laf','chain1':'A','chain2':'E','range':range(1,90+1)+range(192,238+1)},
##        {'pdb1':'2lao','pdb2':'1laf','chain1':'A','chain2':'E','range':range(91,191+1)},
##        ## t4l
##        {'pdb1':'1l96','pdb2':'1l97','chain1':'A','chain2':'A','range':range(13,59+1)},
##        {'pdb1':'1l96','pdb2':'1l97','chain1':'A','chain2':'A','range':range(81,164+1)},
##        ## maltodextrin bp
##        {'pdb1':'1omp','pdb2':'3mbp','chain1':'A','chain2':'A','range':range(1,104+1)+range(268,313+1)},
##        {'pdb1':'1omp','pdb2':'3mbp','chain1':'A','chain2':'A','range':range(113,258+1)+range(314,370+1)},
##        ## mRNA capping enzyme
##        {'pdb1':'1ckm','pdb2':'1ckm','chain1':'A','chain2':'B','range':range(1,237+1)+range(319,327+1)},
##        {'pdb1':'1ckm','pdb2':'1ckm','chain1':'A','chain2':'B','range':range(241,303+1)},
##        ## mura
##        {'pdb1':'1ejd','pdb2':'1a2n','chain1':'A','chain2':'A','range':range(1,20+1)+range(230,417+1)},
##        {'pdb1':'1ejd','pdb2':'1a2n','chain1':'A','chain2':'A','range':range(20,230+1)},
##        ## oligopeptide bp
##        {'pdb1':'1rkm','pdb2':'2rkm','chain1':'A','chain2':'A','range':range(1,263+1)+range(491,517+1)},
##        {'pdb1':'1rkm','pdb2':'2rkm','chain1':'A','chain2':'A','range':range(277,477+1)},
##        ## protein kinase A
##        {'pdb1':'1jlu','pdb2':'1cmk','chain1':'E','chain2':'E','range':range(1,33+1)+range(125,310+1),
##        {'pdb1':'1jlu','pdb2':'1cmk','chain1':'E','chain2':'E','range':range(34,124+1)},
##        ## dna polymerase beta
##        {'pdb1':'1bpd','pdb2':'2bpg','chain1':'A','chain2':'A','range':range(1,82+1)},
##        {'pdb1':'1bpd','pdb2':'2bpg','chain1':'A','chain2':'A','range':range(106,132+1)},
##        {'pdb1':'1bpd','pdb2':'2bpg','chain1':'A','chain2':'A','range':range(148,262+1)},
##        {'pdb1':'1bpd','pdb2':'2bpg','chain1':'A','chain2':'A','range':range(262,335+1)},
##        ## ribose bp
##        {'pdb1':'1urp','pdb2':'2dri','chain1':'A','chain2':'A','range':range(1,98+1)+range(235,259+1)},
##        {'pdb1':'1urp','pdb2':'2dri','chain1':'A','chain2':'A','range':range(104,234+1)+range(265,271+1)},
##        ## thioredoxin reductase
##        {'pdb1':'1tde','pdb2':'1f6m','chain1':'A','chain2':'E','range':range(1,112+1)+range(248,320+1)},
##        {'pdb1':'1tde','pdb2':'1f6m','chain1':'A','chain2':'E','range':range(118,242+1)},
##        ## dna bp
##        {'pdb1':'1fgu','pdb2':'1jmc','chain1':'A','chain2':'A','range':range(183,283+1)},
##        ## transferrin
##        {'pdb1':'1bp5','pdb2':'1a8e','chain1':'A','chain2':'A','range':range(1,75+1)+range(249,316+1)},
##        {'pdb1':'1bp5','pdb2':'1a8e','chain1':'A','chain2':'A','range':range(103,242+1)},
##        ## uracil dna glycosylase
##        {'pdb1':'1ssp','pdb2':'1akz','chain1':'E','chain2':'A','range':range(82,144+1)+range(191,240+1)},
##        {'pdb1':'1ssp','pdb2':'1akz','chain1':'E','chain2':'A','range':range(166,182+1)+range(270,304+1)},
        ]

    for i in range(len(l_input)):

        pdb1 = l_input[i]['pdb1']
        pdb2 = l_input[i]['pdb2']
        chain1 = l_input[i]['chain1']
        chain2 = l_input[i]['chain2']
        domain_range = l_input[i]['range']

        os.system('cp /oxygenase_local/data/pdb/%s/pdb%s.ent %s.pdb' %(pdb1[1:3],pdb1,pdb1,))
        os.system('cp /oxygenase_local/data/pdb/%s/pdb%s.ent %s.pdb' %(pdb2[1:3],pdb2[:4],pdb2[:4],))

        ss_range1, l_missing1, seqres1, l_modres = parse_header(pdb1, chain1,)
        ss_range2, l_missing2, seqres2, l_modres = parse_header(pdb2[:4], chain2,)

        ss_range = list(set(ss_range1)&set(ss_range2))
        l_missing = list(set(l_missing1)|set(l_missing2))

        if len(seqres1) != len(seqres2):
            d_replace = {
                'TPO':'THR','PTR':'TYR',
##                'SER':'CYS', ## 1tde v 1f6m
                }
            for i in range(len(seqres1)):
                if seqres1[i] in d_replace.keys():
                    seqres1[i] = d_replace[seqres1[i]]
            for i in range(len(seqres2)):
                if seqres2[i] in d_replace.keys():
                    seqres2[i] = d_replace[seqres2[i]]
            if not (''.join(seqres1) in ''.join(seqres2) or ''.join(seqres2) in ''.join(seqres1)):
                import sys
                sys.path.append('/home/people/tc/svn/EAT_DB/')
                import sequence_alignment
                d_res = {
                    'ALA':'A','CYS':'C','ASP':'D','GLU':'E','PHE':'F',
                    'GLY':'G','HIS':'H','ILE':'I','LYS':'K','LEU':'L',
                    'MET':'M','ASN':'N','PRO':'P','GLN':'Q','ARG':'R',
                    'SER':'S','THR':'T','VAL':'V','TRP':'W','TYR':'Y',
                    }
                seq1 = ''
                for res in seqres1:
                    seq1 += d_res[res]
                seq2 = ''
                for res in seqres2:
                    seq2 += d_res[res]
                instance = sequence_alignment.NW(seq1,seq2)
                s1,s2 = instance.Align(verbose=False)[:2]
                l1 = len(s1)-len(s1.lstrip('-'))
                l2 = len(s2)-len(s2.lstrip('-'))
                r1 = len(s1)-len(s1.rstrip('-'))
                r2 = len(s2)-len(s2.rstrip('-'))
                print seqres1
                print seqres2
                print len(seqres1)
                print len(seqres2)
                print pdb1, pdb2
                print l1, l2, r1, r2
                print seqres2[l1:len(seqres2)-r1]
                print seqres1[l2:len(seqres1)-r2]

        l_coordinates1 = parse_coordinates(pdb1,chain1,domain_range,ss_range,l_missing,)
        l_coordinates2 = parse_coordinates(pdb2[:4],chain2,domain_range,ss_range,l_missing,)

##        l_coordinates1 = l_coordinates1[l2:len(l_coordinates1)-r2]
##        l_coordinates2 = l_coordinates2[l1:len(l_coordinates2)-r1]

        if len(l_coordinates1) != len(l_coordinates2):
            print len(l_coordinates1)
            print len(l_coordinates2)
            stop

        rmsd = instance_geometry.superpose(l_coordinates1,l_coordinates2)
        print pdb1, pdb2, round(rmsd,1), len(l_coordinates1)/3.
        tv1 = instance_geometry.fitcenter
        rm = instance_geometry.rotation
        tv2 = instance_geometry.refcenter

        apply_transformation_matrix(
            pdb1,chain1,l_modres,
            [0,0,0],[[1,0,0],[0,1,0],[0,0,1]],[0,0,0],
            )
        apply_transformation_matrix(
            pdb2,chain2,l_modres,
            tv1,rm,tv2,
            )

        l_coordinates1 = parse_coordinates(pdb1+'_rotated',chain1,range(1,9999),ss_range,l_missing,)
        l_coordinates2 = parse_coordinates(pdb2+'_rotated',chain2,range(1,9999),ss_range,l_missing,)

        SUM = 0.
        n = len(l_coordinates1)
        for i in range(n):
            SUM += sum((l_coordinates1[i]-l_coordinates2[i])**2)
        RMSD = math.sqrt(SUM/n)
        print RMSD

    return
Example #39
0
            surfaceloop | volume | physicalsurface | physicalvolume | comment \
            | skip1

    grammar= OneOrMore(command)+StringEnd()

    try:
        tokens= grammar.parseFile(filename)
    except ParseException, err:
        print err.line
        print " "*(err.column-1) + "^"
        print err
        raise err

    lineloops={}
    surfaceloops={}
    g=geom.geometry()
    for x in tokens:
        if x[0]=="Point":
            g.addpoint(int(x[1]),[float(x[2][0]),float(x[2][1]),float(x[2][2])])
        elif x[0]=="Line":
            assert len(x[2])==2
            g.addline(int(x[1]),[int(x[2][0]),int(x[2][1])])
        elif x[0]=="Circle":
            assert len(x[2])==3
            g.addline(int(x[1]),[int(x[2][0]),int(x[2][2])])
            #g.add1(geom.circle(int(x[1]),int(x[2][0]),int(x[2][1]),
            #    int(x[2][2])))
        elif x[0]=="Line Loop":
            lineloops[int(x[1])]=[int(y) for y in x[2]]
        elif x[0]=="Plane Surface":
            assert len(x[2])==1
## HEWL scatter plots of RMSD vs misc properties (pH diff, T diff, max resol)

## imports
import os,numpy
import core
import sys
sys.path.append('/home/people/tc/svn/tc_sandbox/pdb')
import parse_mmCIF
sys.path.append('/home/people/tc/svn/tc_sandbox/misc/')
import gnuplot, statistics
sys.path.append('/home/people/tc/svn/Protool/')
import geometry

instance_geometry = geometry.geometry()

## appendix
d_321 = {
    'ALA':'A','CYS':'C','ASP':'D','GLU':'E','PHE':'F',
    'GLY':'G','HIS':'H','ILE':'I','LYS':'K','LEU':'L',
    'MET':'M','ASN':'N','PRO':'P','GLN':'Q','ARG':'R',
    'SER':'S','THR':'T','VAL':'V','TRP':'W','TYR':'Y',
    }

## exclude/restrict
l_ligands_exclude = [
    'IOD', ## 1b2k, 1lkr
    'NAG','NDG', ## substrate
    'SCN', ## 1lcn, thiocyanate
    'CCN', ## acetonitrile cross linker (2lyo,3lyo)
    ]
Example #41
0
    def OnClick(self, event):
        # inspector = self.parent
        wk = self.parent.WorkGroup

        ID = event.GetId()
        if ID == self.BCK_ID:
            self.parent.ShowAction(self.parent.geometryActions)
        if ID == self.EMP_ID:
            geo = cad_geometry()
            wk.add_geometry(geometry(geo))
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... create object")
                macro_script.append("_geo = cad_geometry()")
                macro_script.append("wk.add_geometry(geometry(_geo))")
                macro_script.append("# ...")
        if ID == self.LIN_ID:
            from caid.cad_geometry import line as domain
            geo = domain()
            wk.add_geometry(geometry(geo))
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... create object")
                macro_script.append("_geo = line()")
                macro_script.append("wk.add_geometry(geometry(_geo))")
                macro_script.append("# ...")
        if ID == self.LNR_ID:
            self.parent.objectActionsCreateLinear.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateLinear)
        if ID == self.ARC_ID:
            self.parent.objectActionsCreateArc.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateArc)
        if ID == self.CRV_ID:
            self.parent.objectActionsCurve.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCurve)
        if ID == self.SQR_ID:
            from caid.cad_geometry import square as domain
            geo = domain()
            wk.add_geometry(geometry(geo))
            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... create object")
                macro_script.append("_geo = square()")
                macro_script.append("wk.add_geometry(geometry(_geo))")
                macro_script.append("# ...")
        if ID == self.BIL_ID:
            self.parent.objectActionsCreateBilinear.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateBilinear)
        if ID == self.CRC_ID:
            self.parent.objectActionsCreateCircle.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateCircle)
        if ID == self.QCR_ID:
            self.parent.objectActionsCreateQuartCircle.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateQuartCircle)
        if ID == self.ANL_ID:
            self.parent.objectActionsCreateAnnulus.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateAnnulus)
        if ID == self.CR5_ID:
            self.parent.objectActionsCreateCircle_5mp.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateCircle_5mp)
        if ID == self.TRL_ID:
            self.parent.objectActionsCreateTriangle.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateTriangle)
Example #42
0
    def OnClick(self, event):
        ID = event.GetId()
        if ID == self.BCK_ID:
            self.parent.ShowAction(self.parent.geometryActions)
        if ID == self.GO_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            geoItem = wk.inspector.currentGeometryItem
            _geo = cad_geometry()
            for nrb in geo:
                geo_t = cad_geometry()
                geo_t.append(nrb)

                # ... refinement
                list_t = None
                if self.n.sum() > 0:
                    list_t = []
                    for axis in range(0,nrb.dim):
                        ub = nrb.knots[axis][0]
                        ue = nrb.knots[axis][-1]
                        t = []
                        if self.n[axis] > 0:
                            t = np.linspace(ub,ue,self.n[axis]+2)[1:-1]
                        list_t.append(t)

                list_p = None
                if self.p.sum() > 0:
                    list_p = []
                    for axis in range(0,nrb.dim):
                        list_p.append(np.max(self.p[axis] - nrb.degree[axis], 0))

                list_m = None
                if self.m.sum() > 0:
                    list_m = []
                    for axis in range(0,nrb.dim):
                        list_m.append(self.m[axis])

                geo_t.refine(list_t=list_t, list_p=list_p, list_m=list_m)
                _geo.append(geo_t[0])

                # macro recording
                if wk.macroRecording:
                    macro_script = wk.macro_script
                    macro_script.new_line()
                    macro_script.append("# ... refine geometry")
                    macro_script.append("_geo = cad_geometry()")

                    geo_id = wk.list_geo.index(geo)
                    macro_script.append("geo_id = "+str(geo_id))
                    macro_script.append("geo = geometries[geo_id]")
                    macro_script.append("for nrb in geo:")
                    macro_script.append("\tgeo_t = cad_geometry()")
                    macro_script.append("\tgeo_t.append(nrb)")

                    str_list_t = [list(ts) for ts in list_t]
                    macro_script.append("\tlist_t = "+ str(str_list_t))
                    macro_script.append("\tlist_p = "+ str(list_p))
                    macro_script.append("\tlist_m = "+ str(list_m))
                    macro_script.append("\tgeo_t.refine(list_t=list_t, list_p=list_p, list_m=list_m)")
                    macro_script.append("\t_geo.append(geo_t[0])")
                    macro_script.append("wk.add_geometry(geometry(_geo))")
                    macro_script.append("# ...")
            # ...

            _geo.set_internal_faces(geo.internal_faces)
            _geo.set_external_faces(geo.external_faces)
            _geo.set_connectivity(geo.connectivity)

            geo_new = geometry(_geo)
            geo_newItem = wk.add_geometry(geo_new)
Example #43
0
    def main(self, pdb1, pdb2, chains1, chains2):

        import Numeric, math, os

        import quakes
        instance_quakes = quakes.quakes()

        import sys
        sys.path.append('/home/people/tc/python/Protool/')
        import geometry
        instance_geometry = geometry.geometry()

        pdbs = [pdb1,pdb2]

        ##
        ## parse coordinates to dictionary
        ##
        d_noncoordinates = {}
        d_coordinates = {}
        for pdb in pdbs:

            ## read pdb file
            fd = open('%s%s.pdb' %(self.pdbpath, pdb),'r')
            lines = fd.readlines()
            fd.close()

            ## parse pdb file
            d_noncoords = instance_quakes.parse_pdbnoncoordinatesections(lines, pdb)
            d_coords = instance_quakes.parse_pdbcoordinatesection(lines, pdb)
            d_noncoordinates[pdb] = d_noncoords
            d_coordinates[pdb] = d_coords

        ##
        ## convert dictionary of coordinates to list of coordinates
        ##
        coordinates1 = []
        coordinates2 = []
        d_alignATOMseq = {}
        for i in range(len(chains1)):

            chain1 = chains1[i]
            chain2 = chains2[i]

            d_res_nos1, d_res_nos2, l1, l2, ATOMseq1, ATOMseq2 = instance_quakes.alignATOMseq(d_coordinates, d_noncoordinates, pdb1, pdb2, chain1, chain2)
            d_alignATOMseq[chain2] = {}
            d_alignATOMseq[chain2]['d_res_nos1'] = d_res_nos1
            d_alignATOMseq[chain2]['d_res_nos2'] = d_res_nos2
            d_alignATOMseq[chain2]['l1'] = l1
            d_alignATOMseq[chain2]['l2'] = l2
            coords1, coords2, rescount = instance_quakes.ATOMrecords2coordinates(d_coordinates, pdb1, pdb2, chain1, chain2, d_res_nos1, d_res_nos2, l1, l2, ATOMseq1, ATOMseq2)

            coordinates1 += coords1
            coordinates2 += coords2

        ##
        ## align coordinates
        ##
        rmsd = instance_geometry.superpose(coordinates1,coordinates2)
        tv1 = instance_geometry.fitcenter
        rm = instance_geometry.rotation
        tv2 = instance_geometry.refcenter

        ##
        ## calculate RMSD of transformed coordinates of individual residues
        ##
        lines1 = []
        lines2 = []
        atom_no = 0
        for i in range(len(chains1)):

            chain1 = chains1[i]
            chain2 = chains2[i]

            for SEQRESpos1 in range(l2,len(ATOMseq1)+l2):

                SEQRESpos2 = SEQRESpos1+l1-l2
                res_no1 = d_res_nos1[SEQRESpos1]['res_no']
                res_no2 = d_res_nos2[SEQRESpos2]['res_no']
                if res_no1 == '-' or res_no2 == '-':
                    continue
                iCode1 = d_res_nos1[SEQRESpos1]['iCode']
                iCode2 = d_res_nos2[SEQRESpos2]['iCode']

                if res_no1 not in d_coordinates[pdb1]['chains'][chain1]['residues'].keys():
                    continue
                if res_no2 not in d_coordinates[pdb2]['chains'][chain2]['residues'].keys():
                    continue
                if 'REMARK' in d_coordinates[pdb1]['chains'][chain1]['residues'][res_no1]['d_iCodes'][iCode1].keys():
                    continue
                if 'REMARK' in d_coordinates[pdb2]['chains'][chain2]['residues'][res_no2]['d_iCodes'][iCode2].keys():
                    continue

                d_resname = {
                    pdb1:{'chain':chain1,'res_no':res_no1,'iCode':iCode1},
                    pdb2:{'chain':chain2,'res_no':res_no2,'iCode':iCode2},
                    }
                for pdb in d_resname.keys():
                    chain = d_resname[pdb]['chain']
                    res_no = d_resname[pdb]['res_no']
                    iCode = d_resname[pdb]['iCode']
                    res_name = d_coordinates[pdb]['chains'][chain]['residues'][res_no]['d_iCodes'][iCode]['res_name']
                    d_atoms = d_coordinates[pdb]['chains'][chain]['residues'][res_no]['d_iCodes'][iCode]['atoms']
                    d_resname[pdb]['res_name'] = res_name
                    d_resname[pdb]['d_atoms'] = d_atoms
                res_name1 = d_resname[pdb1]['res_name']
                res_name2 = d_resname[pdb2]['res_name']
                d_atoms1 = d_resname[pdb1]['d_atoms']
                d_atoms2 = d_resname[pdb2]['d_atoms']
##                    print pdb1, pdb2, chain1, chain2, res_no1, res_no2, res_name1, res_name2

                ##
                ## calculate rmsd for the atoms of the residue
                ##
                SS = []
                for atom_name in d_atoms1.keys():
                    if atom_name not in d_atoms2.keys():
                        continue
                    coordinate1 = d_atoms1[atom_name]['coordinate']
                    coordinate2 = Numeric.matrixmultiply(rm, d_atoms2[atom_name]['coordinate']-tv1)+tv2
                    SS += [sum((coordinate2-coordinate1)**2)]
                RMSD = math.sqrt(sum(SS)/len(SS))
                occupancy = bfactor = RMSD/rmsd
                ##
                ## append atoms and coordinates to lines
                ##
                for atom_name in d_atoms1.keys():
                    if atom_name not in d_atoms2.keys():
                        continue
                    coordinate1 = d_atoms1[atom_name]['coordinate']
                    coordinate2 = d_atoms2[atom_name]['coordinate']
                    x1 = coordinate1[0]; y1 = coordinate1[1]; z1 = coordinate1[2]
                    x2 = coordinate2[0]; y2 = coordinate2[1]; z2 = coordinate1[2]
                    atom_no += 1
                    altloc = ''
                    charge = ''
                    if 'H' in atom_name:
                        element = 'H'
                    else:
                        element = atom_name[0]
                    lines1 += [
                        '%6s%5i %4s%1s%3s %1s%4i%1s   %8.3f%8.3f%8.3f%6.2f%6.2f          %2s%2s\n'
                        %('ATOM'.ljust(6), atom_no, atom_name.ljust(4), altloc, res_name1.ljust(3), chain1, res_no1, iCode1, x1, y1, z1, occupancy, bfactor, element.rjust(2), charge.rjust(2))
                        ]
                    lines2 += [
                        '%6s%5i %4s%1s%3s %1s%4i%1s   %8.3f%8.3f%8.3f%6.2f%6.2f          %2s%2s\n'
                        %('ATOM'.ljust(6), atom_no, atom_name.ljust(4), altloc, res_name2.ljust(3), chain2, res_no2, iCode2, x2, y2, z2, occupancy, bfactor, element.rjust(2), charge.rjust(2))
                        ]

        fd = open('%s%s.pdb' %(self.path_out,pdb1),'w')
        fd.writelines(lines1)
        fd.close()
        fd = open('%s%s.pdb' %(self.path_out,pdb2),'w')
        fd.writelines(lines2)
        fd.close()

        for pdb in pdbs:
            ## write rasmol script
            lines = [
                'rasmol -nodisplay %s%s.pdb << EOF\n' %(self.path_out,pdb),
                'color temperature\n',
                'spacefill\n',
                'write %s%s.ppm\n' %(self.path_tmp,pdb),
                'exit\n',
                ]
            ## write rasmol script to file
            fd = open('%s%srasmol.src' %(self.path_tmp,pdb),'w')
            fd.writelines(lines)
            fd.close()
            ## execute rasmol script
            os.system('source %s%srasmol.src' %(self.path_tmp,pdb))
            ## convert rasmol output
            os.system('convert %s%s.ppm -resize x80 %s%s.gif' %(self.path_tmp,pdb, self.path_out,pdb))
            ## clean up
            os.system('rm %s%s.ppm' %(self.path_tmp,pdb))
        ## clean up
        os.system('rm %s%srasmol.src' %(self.path_tmp,pdb))
        
        os.system

        return
Example #44
0

class MyApp(wx.App):
    """Our application class
    """

    def OnInit(self):
        """Initialize by creating the split window with the tree
        """
        frame = Inspector(None, -1, "Inspector")
        frame.Show(True)
        self.SetTopWindow(frame)
        self.frame = frame

        return True


if __name__ == "__main__":
    app = MyApp(0)
    frame = app.frame
    tree = frame.tree
    from caid.cad_geometry import circle_5mp, square

    s1 = circle_5mp()
    s2 = square()
    geo1 = geometry(s1)
    geo2 = geometry(s2)
    tree.add_geometry(geo1)
    tree.add_geometry(geo2)
    app.MainLoop()
def main(pdb1,pdb2,chains1_align,chains2_align,):

    chains1_apply = chains1_align
    chains2_apply = chains2_align

    import os, sys, math
    sys.path.append('/home/people/tc/svn/Protool/')
    import geometry
    instance_geometry = geometry.geometry()

    domain_range = range(0,9999)

    os.system('cp /data/pdb-v3.2/%s/pdb%s.ent %s.pdb' %(pdb1[1:3],pdb1,pdb1,))
    os.system('cp /data/pdb-v3.2/%s/pdb%s.ent %s.pdb' %(pdb2[1:3],pdb2,pdb2,))
    
    ss_range1, l_missing1, seqres1, l_modres = parse_header(pdb1, chains1_align,)
    ss_range2, l_missing2, seqres2, l_modres = parse_header(pdb2, chains2_align,)

    ss_range = list(set(ss_range1)&set(ss_range2))
    l_missing = list(set(l_missing1)|set(l_missing2))

    if len(seqres1) != len(seqres2):
        d_replace = {
            'TPO':'THR','PTR':'TYR',
##                'SER':'CYS', ## 1tde v 1f6m
            }
        for i in range(len(seqres1)):
            if seqres1[i] in d_replace.keys():
                seqres1[i] = d_replace[seqres1[i]]
        for i in range(len(seqres2)):
            if seqres2[i] in d_replace.keys():
                seqres2[i] = d_replace[seqres2[i]]
        if not (''.join(seqres1) in ''.join(seqres2) or ''.join(seqres2) in ''.join(seqres1)):
            import sys
            sys.path.append('/home/people/tc/svn/EAT_DB/')
            import sequence_alignment
            d_res = {
                'ALA':'A','CYS':'C','ASP':'D','GLU':'E','PHE':'F',
                'GLY':'G','HIS':'H','ILE':'I','LYS':'K','LEU':'L',
                'MET':'M','ASN':'N','PRO':'P','GLN':'Q','ARG':'R',
                'SER':'S','THR':'T','VAL':'V','TRP':'W','TYR':'Y',
                }
            seq1 = ''
            for res in seqres1:
                seq1 += d_res[res]
            seq2 = ''
            for res in seqres2:
                seq2 += d_res[res]
            instance = sequence_alignment.NW(seq1,seq2)
            s1,s2 = instance.Align(verbose=False)[:2]
            l1 = len(s1)-len(s1.lstrip('-'))
            l2 = len(s2)-len(s2.lstrip('-'))
            r1 = len(s1)-len(s1.rstrip('-'))
            r2 = len(s2)-len(s2.rstrip('-'))
            print seqres1
            print seqres2
            print len(seqres1)
            print len(seqres2)
            print pdb1, pdb2
            print l1, l2, r1, r2
            print seqres2[l1:len(seqres2)-r1]
            print seqres1[l2:len(seqres1)-r2]
        else:
            s1 = ''.join(seqres1)
            s2 = ''.join(seqres2)
            if s1 in s2:
                seqres2 = seqres2[s2.index(s1)/3:]
            else:
                seqres1 = seqres1[s1.index(s2)/3:]
            if len(seqres1) != len(seqres2):
                print len(seqres1), len(seqres2)
                stop

    l_coordinates1 = parse_coordinates(pdb1,chains1_align,domain_range,ss_range,l_missing,)
    l_coordinates2 = parse_coordinates(pdb2,chains2_align,domain_range,ss_range,l_missing,)

##        l_coordinates1 = l_coordinates1[l2:len(l_coordinates1)-r2]
##        l_coordinates2 = l_coordinates2[l1:len(l_coordinates2)-r1]

    if len(l_coordinates1) == 0 or len(l_coordinates2) == 0:
        stop

    if len(l_coordinates1) != len(l_coordinates2):
        print len(l_coordinates1)
        print len(l_coordinates2)
        stop

    rmsd = instance_geometry.superpose(l_coordinates1,l_coordinates2)
    print pdb1, pdb2
    print 'rmsd', round(rmsd,1)
    print 'residues', len(seqres1), len(seqres2)
    print 'coordinates', len(l_coordinates1)
    tv1 = instance_geometry.fitcenter
    rm = instance_geometry.rotation
    tv2 = instance_geometry.refcenter

    lines1 = apply_transformation_matrix(
        pdb1,chains1_apply,l_modres,
        [0,0,0],[[1,0,0],[0,1,0],[0,0,1]],[0,0,0],
        )
    lines2 = apply_transformation_matrix(
        pdb2,chains2_apply,l_modres,
        tv1,rm,tv2,
        )

    fd = open('rotated_%s%s.pdb' %(pdb1,pdb2,),'w')
    fd.writelines(lines1+lines2)
    fd.close()

    l_coordinates1 = parse_coordinates('rotated_'+pdb1,chains1_apply,range(-9999,9999),ss_range,l_missing,)
    l_coordinates2 = parse_coordinates('rotated_'+pdb2,chains2_apply,range(-9999,9999),ss_range,l_missing,)

    SUM = 0.
    n = len(l_coordinates1)
    for i in range(n):
        SUM += sum((l_coordinates1[i]-l_coordinates2[i])**2)
    RMSD = math.sqrt(SUM/n)
    print 'RMSD all atoms', RMSD

    return RMSD,l_coordinates1,l_coordinates2
Example #46
0
        wk = self.WorkGroup
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_DELETE:
            wk.directAct.removeObject()

class MyApp(wx.App):
    '''Our application class
    '''
    def OnInit(self):
        '''Initialize by creating the split window with the tree
        '''
        frame = Inspector(None, -1, 'Inspector')
        frame.Show(True)
        self.SetTopWindow(frame)
        self.frame = frame

        return True

if __name__ == '__main__':
    app = MyApp(0)
    frame = app.frame
    tree = frame.tree
    from caid.cad_geometry import circle_5mp, square
    s1 = circle_5mp()
    s2 = square()
    geo1 = geometry(s1)
    geo2 = geometry(s2)
    tree.add_geometry(geo1)
    tree.add_geometry(geo2)
    app.MainLoop()
Example #47
0
    def OnClick(self, event):
        ID = event.GetId()
        if ID == self.NEW_ID:
            self.parent.ShowAction(self.parent.geometryActionsNew)
        if ID == self.ADD_ID:
            self.parent.ShowAction(self.parent.geometryActionsAdd)
        if ID == self.DEL_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            geoItem = wk.inspector.currentGeometryItem
            geo_id = wk.list_geo.index(geo)
            wk.remove_geometry(geoItem, geo)

            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... delete geometry")
                macro_script.append("geo_id = "+str(geo_id))
                macro_script.append("geo = geometries[geo_id]")
                macro_script.append("geoItem = geo.treeItem")
                macro_script.append("wk.remove_geometry(geoItem, geo)")
                macro_script.append("# ...")

        if ID == self.DUP_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo_new = wk.inspector.currentGeometry.copy()
            geo_newItem = wk.add_geometry(geo_new)
            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... copy geometry")
                geo_id = wk.list_geo.index(geo)
                macro_script.append("geo_id = "+str(geo_id))
                macro_script.append("geo = geometries[geo_id]")
                macro_script.append("_geo = geo.copy()")
                macro_script.append("wk.add_geometry(geometry(_geo))")
                macro_script.append("# ...")

        if ID == self.PLJ_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            import matplotlib.pyplot as plt
            try:
                MeshResolution = geo.list_patchInfo[0].steps[0]
            except:
                MeshResolution = 10
            geo.plotJacobians(MeshResolution=MeshResolution)
            plt.colorbar()
            plt.show()
        if ID == self.PLM_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            import matplotlib.pyplot as plt
            MeshResolution = geo.list_patchInfo[0].steps[0]
            geo.plotMesh(MeshResolution=MeshResolution)
            plt.show()
        if ID == self.EXP_ID:
            from global_vars import CAIDwildcard
            # Create a save file dialog
            dialog = wx.FileDialog ( None, style = wx.SAVE | wx.OVERWRITE_PROMPT
                                   , wildcard=CAIDwildcard)
            # Show the dialog and get user input
            if dialog.ShowModal() == wx.ID_OK:
                ls_file = dialog.GetPath()
                wk = self.parent.WorkGroup
                geo = wk.inspector.currentGeometry
                geo.save(ls_file)

                # macro recording
                if wk.macroRecording:
                    macro_script = wk.macro_script
                    macro_script.new_line()
                    macro_script.append("# ... export geometry")
                    geo_id = wk.list_geo.index(geo)
                    macro_script.append("geo_id = "+str(geo_id))
                    macro_script.append("geo = geometries[geo_id]")
                    macro_script.append("filename = \""+ls_file+"\"")
                    macro_script.append("geo.save(filename)")
                    macro_script.append("# ...")

            # Destroy the dialog
            dialog.Destroy()
        if ID == self.EDT_ID:
            from Editor import Editor
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            edt = Editor(wk.parent, -1, 'Editor')
            filename = edt.DoOpenGeometryAsFile(geo)
            # wait until the editor is closed
            createNewGeo = False
            while edt:
                if edt.modify:
                    createNewGeo = True
                wx.MilliSleep(10)
                wx.GetApp().Yield()
            if createNewGeo:
                newgeo = cad_geometry(filename)
                geo_new = geometry(newgeo)
                geo_newItem = wk.add_geometry(geo_new)
            try:
                os.remove(filename)
            except:
                pass
        if ID == self.TRS_ID:
            self.parent.objectActionsTranslate.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsTranslate)
        if ID == self.ROT_ID:
            self.parent.objectActionsRotate.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsRotate)
        if ID == self.SCL_ID:
            self.parent.objectActionsScale.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsScale)
        if ID == self.REF_ID:
            self.parent.ShowAction(self.parent.geometryActionsRefine)
        if ID == self.PEX_ID:
            self.parent.objectActionsPolarExtrude.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsPolarExtrude)
        if ID == self.EXD_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            geoItem = wk.inspector.currentGeometryItem
            list_geo = geo.expand()
            for _geo in list_geo:
                geo_new = geometry(_geo)
                geo_newItem = wk.add_geometry(geo_new)
            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... expand geometry")
                geo_id = wk.list_geo.index(geo)
                macro_script.append("geo_id = "+str(geo_id))
                macro_script.append("geo = geometries[geo_id]")
                macro_script.append("list_geo = geo.expand()")
                macro_script.append("for _geo in list_geo:")
                macro_script.append("\twk.add_geometry(geometry(_geo))")
                macro_script.append("# ...")

        if ID == self.IMP_ID:
            # Create an open file dialog
            dialog = wx.FileDialog(None, style = wx.OPEN)
            # Show the dialog and get user input
            if dialog.ShowModal() == wx.ID_OK:
                filename = dialog.GetPath()
                # TODO update recent files
#                self.UpdateRecentFiles(filename)
                geo = cad_geometry(filename)
                wk = self.parent.WorkGroup
                wk.add_geometry(geometry(geo))
                # macro recording
                if wk.macroRecording:
                    macro_script = wk.macro_script
                    macro_script.new_line()
                    macro_script.append("# ... import geometry")
                    macro_script.append("filename = \""+filename+"\"")
                    macro_script.append("_geo = cad_geometry(filename)")
                    macro_script.append("wk.add_geometry(geometry(_geo))")
                    macro_script.append("# ...")
            # Destroy the dialog
            dialog.Destroy()
        if ID == self.REI_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            geoItem = wk.inspector.currentGeometryItem
            geo.initialize_info()
            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... initialize info geometry")
                geo_id = wk.list_geo.index(geo)
                macro_script.append("geo_id = "+str(geo_id))
                macro_script.append("geo = geometries[geo_id]")
                macro_script.append("geo.initialize_info()")
                macro_script.append("wk.Refresh(inspector=True)")
                macro_script.append("# ...")
            wk.Refresh(inspector=True)
        if ID == self.UPI_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            geoItem = wk.inspector.currentGeometryItem
            geo.update()
            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... update geometry")
                geo_id = wk.list_geo.index(geo)
                macro_script.append("geo_id = "+str(geo_id))
                macro_script.append("geo = geometries[geo_id]")
                macro_script.append("geo.update()")
                macro_script.append("wk.Refresh(inspector=True)")
                macro_script.append("# ...")
            wk.Refresh(inspector=True)
        if ID == self.T5P_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            item = wk.inspector.tree.GetSelection()
            geo_bnd = wk.inspector.tree.GetPyData(item)
            face = geo_bnd.face
            faceItem = wk.inspector.tree.GetItemParent(item)
            patchItem = wk.inspector.tree.GetItemParent(faceItem)
            geoItem = wk.inspector.tree.GetItemParent(patchItem)
            geo = wk.inspector.tree.GetPyData(geoItem)
            _geo = cad_geometry()
            _geo.append(geo[0])
            geo_new = geometry(_geo.to5patchs(face))
            geo_newItem = wk.add_geometry(geo_new)
            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... to-5-patchs geometry")
                geo_id = wk.list_geo.index(geo)
                macro_script.append("geo_id = "+str(geo_id))
                macro_script.append("geo = geometries[geo_id]")
                macro_script.append("_geo = cad_geometry()")
                macro_script.append("_geo.append(geo[0])")
                macro_script.append("face = "+str(face))
                macro_script.append("_geo = _geo.to5patchs(face)")
                macro_script.append("wk.add_geometry(geometry(_geo))")
                macro_script.append("wk.Refresh()")
                macro_script.append("# ...")
            wk.Refresh()
Example #48
0
    def OnClick(self, event):
        # inspector = self.parent
        wk = self.parent.WorkGroup

        ID = event.GetId()
        if ID == self.BCK_ID:
            self.parent.ShowAction(self.parent.geometryActions)
        if ID == self.EMP_ID:
            geo = cad_geometry()
            wk.add_geometry(geometry(geo))
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... create object")
                macro_script.append("_geo = cad_geometry()")
                macro_script.append("wk.add_geometry(geometry(_geo))")
                macro_script.append("# ...")
        if ID == self.LIN_ID:
            from caid.cad_geometry import line as domain
            geo = domain()
            wk.add_geometry(geometry(geo))
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... create object")
                macro_script.append("_geo = line()")
                macro_script.append("wk.add_geometry(geometry(_geo))")
                macro_script.append("# ...")
        if ID == self.LNR_ID:
            self.parent.objectActionsCreateLinear.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateLinear)
        if ID == self.ARC_ID:
            self.parent.objectActionsCreateArc.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateArc)
        if ID == self.CRV_ID:
            self.parent.objectActionsCurve.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCurve)
        if ID == self.SQR_ID:
            from caid.cad_geometry import square as domain
            geo = domain()
            wk.add_geometry(geometry(geo))
            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... create object")
                macro_script.append("_geo = square()")
                macro_script.append("wk.add_geometry(geometry(_geo))")
                macro_script.append("# ...")
        if ID == self.BIL_ID:
            self.parent.objectActionsCreateBilinear.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateBilinear)
        if ID == self.CRC_ID:
            self.parent.objectActionsCreateCircle.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateCircle)
        if ID == self.QCR_ID:
            self.parent.objectActionsCreateQuartCircle.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateQuartCircle)
        if ID == self.ANL_ID:
            self.parent.objectActionsCreateAnnulus.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateAnnulus)
        if ID == self.CR5_ID:
            self.parent.objectActionsCreateCircle_5mp.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateCircle_5mp)
        if ID == self.PC5_ID:
            self.parent.objectActionsCreatePinched_Circle_5mp.asGeometry()
            self.parent.ShowAction(
                self.parent.objectActionsCreatePinched_Circle_5mp)
        if ID == self.TRL_ID:
            self.parent.objectActionsCreateTriangle.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsCreateTriangle)
        if ID == self.CUB_ID:
            #            from caid.cad_geometry import cube as domain
            from caid.cad_geometry import trilinear as domain
            geo = domain()
            wk.add_geometry(geometry(geo))
Example #49
0
def main():

    import os, sys, math
    sys.path.append('/home/people/tc/svn/Protool/')
    import geometry
    instance_geometry = geometry.geometry()

    ##    ## lactoferrin
    ##    pdb1 = '1lfg'
    ##    pdb2 = '1lfh'
    ##    domain_range = range(1,88+1)+range(253,333+1)
    ##    chain = 'A'

    ##    ## trp repressor
    ##    pdb1 = '1wrp'
    ##    pdb2 = '2oz9' ## 2wrp
    ##    pdb2 = '1zt9'
    ##    domain_range = range(1,999+1)
    ##    chain1 = 'R'
    ##    chain2 = 'R'
    ##    chain2 = 'A'
    ##    exclude_chain = ''

    ##    ## luciferase
    ##    pdb1 = '1ba3'
    ##    pdb2 = '1lci'
    ##    domain_range = range(1,999+1)
    ##    chain1 = 'A'
    ##    chain2 = 'A'
    ##    exclude_chain = ''

    ##    ## G3P DH
    ##    pdb1 = '1gd1'
    ##    pdb2 = '2gd1'
    ##    domain_range = range(1,999+1)
    ##    chain1 = 'O'
    ##    chain2 = 'O'
    ##    exclude_chain = ''

    ##    ## hexokinase
    ##    pdb1 = '1hkg'
    ##    pdb2 = '2yhx'
    ##    domain_range = range(1,999+1)
    ##    chain1 = 'A'
    ##    chain2 = 'A'
    ##    exclude_chain = ''

    ##    ## adk
    ##    pdb1 = '1ake'
    ##    pdb2 = '4ake'
    ##    domain_range = range(1,999+1)
    ##    chain1 = 'A'
    ##    chain2 = 'A'
    ##    exclude_chain = 'B'

    ##    ## t4l
    ##    pdb1 = '2lzm'
    ##    pdb2 = '150l'
    ####    domain_range = range(15,59+1)
    ####    domain_range = range(60,80+1)
    ##    domain_range = range(81,162+1)
    ##    chain1 = 'A'
    ##    chain2 = 'D'
    ##    exclude_chain = 'B'

    l_input = [
        ##        ##
        ##        {'pdb1':'1ipd','pdb2':'1osj','chain1':'A','chain2':'A','range':range(1,98+1)+range(253,345+1)},
        ##        {'pdb1':'1ipd','pdb2':'1osj','chain1':'A','chain2':'A','range':range(99,108+1)+range(109,252+1)},
        ###### shears
        ##        ## aspartate amino transferase
        ##        {'pdb1':'9aat','pdb2':'1ama','chain1':'A','chain2':'A','range':range(15,36+1)+range(349,410+1)},
        ##        {'pdb1':'9aat','pdb2':'1ama','chain1':'A','chain2':'A','range':range(50,312+1)},
        ## alcohol dehydrogenase
        {
            'pdb1': '6adh',
            'pdb2': '8adh1',
            'chain1': 'A',
            'chain2': 'A',
            'range': range(1, 174 + 1) + range(322, 374 + 1)
        },
        {
            'pdb1': '6adh',
            'pdb2': '8adh2',
            'chain1': 'A',
            'chain2': 'A',
            'range': range(193, 317 + 1)
        },
        ##        ## citrate synthase
        ##        {'pdb1':'1cts','pdb2':'4cts','chain1':'A','chain2':'A','range':range(1,276+1)+range(386,999+1)},
        ###### hinges
        ##        ## atpsulf
        ##        {'pdb1':'1i2d','pdb2':'1m8p','chain1':'A','chain2':'A','range':range(1,389+1)},
        ##        ## dnak (different spacegroups)
        ##        {'pdb1':'1dkx','pdb2':'1dky','chain1':'A','chain2':'A','range':range(389,509+1)},
        ##        ## dnak (different spacegroups)
        ##        {'pdb1':'1ddt','pdb2':'1mdt','chain1':'A','chain2':'A','range':range(1,376+1)},
        ##        ## ecpdpbp
        ##        {'pdb1':'1dpp','pdb2':'1dpe','chain1':'A','chain2':'A','range':range(1,260+1)+range(479,999+1)},
        ##        ## ef2
        ##        {'pdb1':'1n0v','pdb2':'1n0u','chain1':'C','chain2':'A','range':range(1,478+1)}, ## large
        ##        {'pdb1':'1n0v','pdb2':'1n0u','chain1':'C','chain2':'A','range':range(479,560+1)}, ## independent
        ##        {'pdb1':'1n0v','pdb2':'1n0u','chain1':'C','chain2':'A','range':range(561,9999+1)}, ## small
        ##        ## febp
        ##        {'pdb1':'1d9v','pdb2':'1mrp','chain1':'A','chain2':'A','range':range(109,227+1)+range(292,309+1)},
        ##        {'pdb1':'1d9v','pdb2':'1mrp','chain1':'A','chain2':'A','range':range(1,96+1)+range(228,262+1)},
        ##        ## folylpolyglutamate synthetase
        ##        {'pdb1':'1jbv','pdb2':'1jbw','chain1':'A','chain2':'A','range':range(1,295+1)},
        ##        {'pdb1':'1jbv','pdb2':'1jbw','chain1':'A','chain2':'A','range':range(296,386+1)},
        ##        ## glucose ABC transporter ATPase subunit (different spacegroups)
        ##        {'pdb1':'1oxs','pdb2':'1oxu','chain1':'C','chain2':'C','range':range(1,209+1)},
        ##        {'pdb1':'1oxs','pdb2':'1oxu','chain1':'C','chain2':'C','range':range(244,999+1)},
        ##        ## groel domain
        ##        {'pdb1':'1aon','pdb2':'1oel','chain1':'A','chain2':'A','range':range(1,137+1)+range(410,999+1)},
        ##        {'pdb1':'1aon','pdb2':'1oel','chain1':'A','chain2':'A','range':range(192,374+1)},
        ##        {'pdb1':'1aon','pdb2':'1oel','chain1':'A','chain2':'A','range':range(138,190+1)+range(375,409+1)},
        ##        ## lao bp
        ##        {'pdb1':'2lao','pdb2':'1laf','chain1':'A','chain2':'E','range':range(1,90+1)+range(192,238+1)},
        ##        {'pdb1':'2lao','pdb2':'1laf','chain1':'A','chain2':'E','range':range(91,191+1)},
        ##        ## t4l
        ##        {'pdb1':'1l96','pdb2':'1l97','chain1':'A','chain2':'A','range':range(13,59+1)},
        ##        {'pdb1':'1l96','pdb2':'1l97','chain1':'A','chain2':'A','range':range(81,164+1)},
        ##        ## maltodextrin bp
        ##        {'pdb1':'1omp','pdb2':'3mbp','chain1':'A','chain2':'A','range':range(1,104+1)+range(268,313+1)},
        ##        {'pdb1':'1omp','pdb2':'3mbp','chain1':'A','chain2':'A','range':range(113,258+1)+range(314,370+1)},
        ##        ## mRNA capping enzyme
        ##        {'pdb1':'1ckm','pdb2':'1ckm','chain1':'A','chain2':'B','range':range(1,237+1)+range(319,327+1)},
        ##        {'pdb1':'1ckm','pdb2':'1ckm','chain1':'A','chain2':'B','range':range(241,303+1)},
        ##        ## mura
        ##        {'pdb1':'1ejd','pdb2':'1a2n','chain1':'A','chain2':'A','range':range(1,20+1)+range(230,417+1)},
        ##        {'pdb1':'1ejd','pdb2':'1a2n','chain1':'A','chain2':'A','range':range(20,230+1)},
        ##        ## oligopeptide bp
        ##        {'pdb1':'1rkm','pdb2':'2rkm','chain1':'A','chain2':'A','range':range(1,263+1)+range(491,517+1)},
        ##        {'pdb1':'1rkm','pdb2':'2rkm','chain1':'A','chain2':'A','range':range(277,477+1)},
        ##        ## protein kinase A
        ##        {'pdb1':'1jlu','pdb2':'1cmk','chain1':'E','chain2':'E','range':range(1,33+1)+range(125,310+1),
        ##        {'pdb1':'1jlu','pdb2':'1cmk','chain1':'E','chain2':'E','range':range(34,124+1)},
        ##        ## dna polymerase beta
        ##        {'pdb1':'1bpd','pdb2':'2bpg','chain1':'A','chain2':'A','range':range(1,82+1)},
        ##        {'pdb1':'1bpd','pdb2':'2bpg','chain1':'A','chain2':'A','range':range(106,132+1)},
        ##        {'pdb1':'1bpd','pdb2':'2bpg','chain1':'A','chain2':'A','range':range(148,262+1)},
        ##        {'pdb1':'1bpd','pdb2':'2bpg','chain1':'A','chain2':'A','range':range(262,335+1)},
        ##        ## ribose bp
        ##        {'pdb1':'1urp','pdb2':'2dri','chain1':'A','chain2':'A','range':range(1,98+1)+range(235,259+1)},
        ##        {'pdb1':'1urp','pdb2':'2dri','chain1':'A','chain2':'A','range':range(104,234+1)+range(265,271+1)},
        ##        ## thioredoxin reductase
        ##        {'pdb1':'1tde','pdb2':'1f6m','chain1':'A','chain2':'E','range':range(1,112+1)+range(248,320+1)},
        ##        {'pdb1':'1tde','pdb2':'1f6m','chain1':'A','chain2':'E','range':range(118,242+1)},
        ##        ## dna bp
        ##        {'pdb1':'1fgu','pdb2':'1jmc','chain1':'A','chain2':'A','range':range(183,283+1)},
        ##        ## transferrin
        ##        {'pdb1':'1bp5','pdb2':'1a8e','chain1':'A','chain2':'A','range':range(1,75+1)+range(249,316+1)},
        ##        {'pdb1':'1bp5','pdb2':'1a8e','chain1':'A','chain2':'A','range':range(103,242+1)},
        ##        ## uracil dna glycosylase
        ##        {'pdb1':'1ssp','pdb2':'1akz','chain1':'E','chain2':'A','range':range(82,144+1)+range(191,240+1)},
        ##        {'pdb1':'1ssp','pdb2':'1akz','chain1':'E','chain2':'A','range':range(166,182+1)+range(270,304+1)},
    ]

    for i in range(len(l_input)):

        pdb1 = l_input[i]['pdb1']
        pdb2 = l_input[i]['pdb2']
        chain1 = l_input[i]['chain1']
        chain2 = l_input[i]['chain2']
        domain_range = l_input[i]['range']

        os.system('cp /oxygenase_local/data/pdb/%s/pdb%s.ent %s.pdb' % (
            pdb1[1:3],
            pdb1,
            pdb1,
        ))
        os.system('cp /oxygenase_local/data/pdb/%s/pdb%s.ent %s.pdb' % (
            pdb2[1:3],
            pdb2[:4],
            pdb2[:4],
        ))

        ss_range1, l_missing1, seqres1, l_modres = parse_header(
            pdb1,
            chain1,
        )
        ss_range2, l_missing2, seqres2, l_modres = parse_header(
            pdb2[:4],
            chain2,
        )

        ss_range = list(set(ss_range1) & set(ss_range2))
        l_missing = list(set(l_missing1) | set(l_missing2))

        if len(seqres1) != len(seqres2):
            d_replace = {
                'TPO': 'THR',
                'PTR': 'TYR',
                ##                'SER':'CYS', ## 1tde v 1f6m
            }
            for i in range(len(seqres1)):
                if seqres1[i] in d_replace.keys():
                    seqres1[i] = d_replace[seqres1[i]]
            for i in range(len(seqres2)):
                if seqres2[i] in d_replace.keys():
                    seqres2[i] = d_replace[seqres2[i]]
            if not (''.join(seqres1) in ''.join(seqres2)
                    or ''.join(seqres2) in ''.join(seqres1)):
                import sys
                sys.path.append('/home/people/tc/svn/EAT_DB/')
                import sequence_alignment
                d_res = {
                    'ALA': 'A',
                    'CYS': 'C',
                    'ASP': 'D',
                    'GLU': 'E',
                    'PHE': 'F',
                    'GLY': 'G',
                    'HIS': 'H',
                    'ILE': 'I',
                    'LYS': 'K',
                    'LEU': 'L',
                    'MET': 'M',
                    'ASN': 'N',
                    'PRO': 'P',
                    'GLN': 'Q',
                    'ARG': 'R',
                    'SER': 'S',
                    'THR': 'T',
                    'VAL': 'V',
                    'TRP': 'W',
                    'TYR': 'Y',
                }
                seq1 = ''
                for res in seqres1:
                    seq1 += d_res[res]
                seq2 = ''
                for res in seqres2:
                    seq2 += d_res[res]
                instance = sequence_alignment.NW(seq1, seq2)
                s1, s2 = instance.Align(verbose=False)[:2]
                l1 = len(s1) - len(s1.lstrip('-'))
                l2 = len(s2) - len(s2.lstrip('-'))
                r1 = len(s1) - len(s1.rstrip('-'))
                r2 = len(s2) - len(s2.rstrip('-'))
                print seqres1
                print seqres2
                print len(seqres1)
                print len(seqres2)
                print pdb1, pdb2
                print l1, l2, r1, r2
                print seqres2[l1:len(seqres2) - r1]
                print seqres1[l2:len(seqres1) - r2]

        l_coordinates1 = parse_coordinates(
            pdb1,
            chain1,
            domain_range,
            ss_range,
            l_missing,
        )
        l_coordinates2 = parse_coordinates(
            pdb2[:4],
            chain2,
            domain_range,
            ss_range,
            l_missing,
        )

        ##        l_coordinates1 = l_coordinates1[l2:len(l_coordinates1)-r2]
        ##        l_coordinates2 = l_coordinates2[l1:len(l_coordinates2)-r1]

        if len(l_coordinates1) != len(l_coordinates2):
            print len(l_coordinates1)
            print len(l_coordinates2)
            stop

        rmsd = instance_geometry.superpose(l_coordinates1, l_coordinates2)
        print pdb1, pdb2, round(rmsd, 1), len(l_coordinates1) / 3.
        tv1 = instance_geometry.fitcenter
        rm = instance_geometry.rotation
        tv2 = instance_geometry.refcenter

        apply_transformation_matrix(
            pdb1,
            chain1,
            l_modres,
            [0, 0, 0],
            [[1, 0, 0], [0, 1, 0], [0, 0, 1]],
            [0, 0, 0],
        )
        apply_transformation_matrix(
            pdb2,
            chain2,
            l_modres,
            tv1,
            rm,
            tv2,
        )

        l_coordinates1 = parse_coordinates(
            pdb1 + '_rotated',
            chain1,
            range(1, 9999),
            ss_range,
            l_missing,
        )
        l_coordinates2 = parse_coordinates(
            pdb2 + '_rotated',
            chain2,
            range(1, 9999),
            ss_range,
            l_missing,
        )

        SUM = 0.
        n = len(l_coordinates1)
        for i in range(n):
            SUM += sum((l_coordinates1[i] - l_coordinates2[i])**2)
        RMSD = math.sqrt(SUM / n)
        print RMSD

    return
Example #50
0
    def OnClick(self, event):
        ID = event.GetId()
        if ID == self.NEW_ID:
            self.parent.ShowAction(self.parent.geometryActionsNew)
        if ID == self.ADD_ID:
            self.parent.ShowAction(self.parent.geometryActionsAdd)
        if ID == self.DEL_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            geoItem = wk.inspector.currentGeometryItem
            geo_id = wk.list_geo.index(geo)
            wk.remove_geometry(geoItem, geo)

            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... delete geometry")
                macro_script.append("geo_id = " + str(geo_id))
                macro_script.append("geo = geometries[geo_id]")
                macro_script.append("geoItem = geo.treeItem")
                macro_script.append("wk.remove_geometry(geoItem, geo)")
                macro_script.append("# ...")

        if ID == self.DUP_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup

            geo = wk.inspector.currentGeometry
            geo_new = wk.inspector.currentGeometry.copy()
            geo_newItem = wk.add_geometry(geo_new)
            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... copy geometry")
                geo_id = wk.list_geo.index(geo)
                macro_script.append("geo_id = " + str(geo_id))
                macro_script.append("geo = geometries[geo_id]")
                macro_script.append("_geo = geo.copy()")
                macro_script.append("wk.add_geometry(geometry(_geo))")
                macro_script.append("# ...")

        if ID == self.PLJ_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            import matplotlib.pyplot as plt
            try:
                MeshResolution = geo.list_patchInfo[0].steps[0]
            except:
                MeshResolution = 10
            geo.plotJacobians(MeshResolution=MeshResolution)
            plt.colorbar()
            plt.show()
        if ID == self.PLM_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            import matplotlib.pyplot as plt
            MeshResolution = geo.list_patchInfo[0].steps[0]
            geo.plotMesh(MeshResolution=MeshResolution)
            plt.show()
        if ID == self.EXP_ID:
            from global_vars import CAIDwildcard
            # Create a save file dialog
            dialog = wx.FileDialog(None,
                                   style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT,
                                   wildcard=CAIDwildcard)
            # Show the dialog and get user input
            if dialog.ShowModal() == wx.ID_OK:
                ls_file = dialog.GetPath()
                wk = self.parent.WorkGroup
                geo = wk.inspector.currentGeometry
                geo.save(ls_file)

                # macro recording
                if wk.macroRecording:
                    macro_script = wk.macro_script
                    macro_script.new_line()
                    macro_script.append("# ... export geometry")
                    geo_id = wk.list_geo.index(geo)
                    macro_script.append("geo_id = " + str(geo_id))
                    macro_script.append("geo = geometries[geo_id]")
                    macro_script.append("filename = \"" + ls_file + "\"")
                    macro_script.append("geo.save(filename)")
                    macro_script.append("# ...")

            # Destroy the dialog
            dialog.Destroy()
        if ID == self.EDT_ID:
            from Editor import Editor
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            edt = Editor(wk.parent, -1, 'Editor')
            filename = edt.DoOpenGeometryAsFile(geo)
            # wait until the editor is closed
            createNewGeo = False
            while edt:
                if edt.modify:
                    createNewGeo = True
                wx.MilliSleep(10)
                wx.GetApp().Yield()
            if createNewGeo:
                newgeo = cad_geometry(filename)
                geo_new = geometry(newgeo)
                geo_newItem = wk.add_geometry(geo_new)
            try:
                os.remove(filename)
            except:
                pass
        if ID == self.TRS_ID:
            self.parent.objectActionsTranslate.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsTranslate)
        if ID == self.ROT_ID:
            self.parent.objectActionsRotate.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsRotate)
        if ID == self.SCL_ID:
            self.parent.objectActionsScale.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsScale)
        if ID == self.REF_ID:
            self.parent.ShowAction(self.parent.geometryActionsRefine)
        if ID == self.PEX_ID:
            self.parent.objectActionsPolarExtrude.asGeometry()
            self.parent.ShowAction(self.parent.objectActionsPolarExtrude)
        if ID == self.EXD_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            geoItem = wk.inspector.currentGeometryItem
            list_geo = geo.expand()
            for _geo in list_geo:
                geo_new = geometry(_geo)
                geo_newItem = wk.add_geometry(geo_new)
            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... expand geometry")
                geo_id = wk.list_geo.index(geo)
                macro_script.append("geo_id = " + str(geo_id))
                macro_script.append("geo = geometries[geo_id]")
                macro_script.append("list_geo = geo.expand()")
                macro_script.append("for _geo in list_geo:")
                macro_script.append("\twk.add_geometry(geometry(_geo))")
                macro_script.append("# ...")

        if ID == self.IMP_ID:
            # Create an open file dialog
            dialog = wx.FileDialog(None, style=wx.FD_OPEN)
            # Show the dialog and get user input
            if dialog.ShowModal() == wx.ID_OK:
                filename = dialog.GetPath()
                # TODO update recent files
                #                self.UpdateRecentFiles(filename)
                geo = cad_geometry(filename)
                wk = self.parent.WorkGroup
                wk.add_geometry(geometry(geo))
                # macro recording
                if wk.macroRecording:
                    macro_script = wk.macro_script
                    macro_script.new_line()
                    macro_script.append("# ... import geometry")
                    macro_script.append("filename = \"" + filename + "\"")
                    macro_script.append("_geo = cad_geometry(filename)")
                    macro_script.append("wk.add_geometry(geometry(_geo))")
                    macro_script.append("# ...")
            # Destroy the dialog
            dialog.Destroy()
        if ID == self.REI_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            geoItem = wk.inspector.currentGeometryItem
            geo.initialize_info()
            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... initialize info geometry")
                geo_id = wk.list_geo.index(geo)
                macro_script.append("geo_id = " + str(geo_id))
                macro_script.append("geo = geometries[geo_id]")
                macro_script.append("geo.initialize_info()")
                macro_script.append("wk.Refresh(inspector=True)")
                macro_script.append("# ...")
            wk.Refresh(inspector=True)
        if ID == self.UPI_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            geo = wk.inspector.currentGeometry
            geoItem = wk.inspector.currentGeometryItem
            geo.update()
            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... update geometry")
                geo_id = wk.list_geo.index(geo)
                macro_script.append("geo_id = " + str(geo_id))
                macro_script.append("geo = geometries[geo_id]")
                macro_script.append("geo.update()")
                macro_script.append("wk.Refresh(inspector=True)")
                macro_script.append("# ...")
            wk.Refresh(inspector=True)
        if ID == self.T5P_ID:
            # inspector = self.parent
            wk = self.parent.WorkGroup
            item = wk.inspector.tree.GetSelection()
            geo_bnd = wk.inspector.tree.GetItemData(item)
            face = geo_bnd.face
            faceItem = wk.inspector.tree.GetItemParent(item)
            patchItem = wk.inspector.tree.GetItemParent(faceItem)
            geoItem = wk.inspector.tree.GetItemParent(patchItem)
            geo = wk.inspector.tree.GetItemData(geoItem)
            _geo = cad_geometry()
            _geo.append(geo[0])
            geo_new = geometry(_geo.to5patchs(face))
            geo_newItem = wk.add_geometry(geo_new)
            # macro recording
            if wk.macroRecording:
                macro_script = wk.macro_script
                macro_script.new_line()
                macro_script.append("# ... to-5-patchs geometry")
                geo_id = wk.list_geo.index(geo)
                macro_script.append("geo_id = " + str(geo_id))
                macro_script.append("geo = geometries[geo_id]")
                macro_script.append("_geo = cad_geometry()")
                macro_script.append("_geo.append(geo[0])")
                macro_script.append("face = " + str(face))
                macro_script.append("_geo = _geo.to5patchs(face)")
                macro_script.append("wk.add_geometry(geometry(_geo))")
                macro_script.append("wk.Refresh()")
                macro_script.append("# ...")
            wk.Refresh()
def main():

## trjconv -f 2LZM_wt.trr -o 2LZM_wt_trjconv.pdb -s 2LZM_wt_MD.tpr -skip 10 -sep

    fd = open('2lzm.pdb','r')
    lines1 = fd.readlines()
    fd.close()
    lines2 = []
    for line in lines1:
        record = line[:6].strip()
        if record in ['HELIX','TURN','SHEET',]:
            lines2 += [line]

    for i in range(50):
        fd = open('%i.pdb' %(i),'r')
        lines = fd.readlines()
        fd.close()
        lines = lines2+lines
        fd = open('nma%i.pdb' %(i),'w')
        fd.writelines(lines)
        fd.close()
    stop

    import sys, os, numpy
    sys.path.append('/home/people/tc/svn/tc_sandbox/quakes/')
    import phipsi_comparison
    sys.path.append('/home/people/tc/svn/tc_sandbox/misc/')
    import phipsi_plot
    sys.path.append('/home/people/tc/svn/Protool/')
    import geometry
    instance_geometry = geometry.geometry()

    d_residues = {
        'ALA':'A','CYS':'C','ASP':'D','GLU':'E','PHE':'F',
        'GLY':'G','HIS':'H','ILE':'I','LYS':'K','LEU':'L',
        'MET':'M','ASN':'N','PRO':'P','GLN':'Q','ARG':'R',
        'SER':'S','THR':'T','VAL':'V','TRP':'W','TYR':'Y',
        }

    d_max = {}

    d_ramachandran = {}
    for res in d_residues.values():
        d_ramachandran[res] = {}
        for phi in range(-180,180):
            d_ramachandran[res][phi] = {}
            for psi in range(-180,180):
                d_ramachandran[res][phi][psi] = 0
    d_ramachandran = phipsi_comparison.parse_dihedrals(d_residues) ## slow
##                d_ramachandran[res][phi][psi] = 1

    for res in d_ramachandran.keys():
        max = 0
        for phi in d_ramachandran[res].keys():
            for psi in d_ramachandran[res][phi].keys():
                count = d_ramachandran[res][phi][psi]
                if count > max:
                    max = count
        d_max[res] = max

    option = 'gromacs'
    option = 'pdbs'

    if option == 'frames':
        l = range(50)
    elif option == 'pdbs':
        l = ['150l',]
        chain = 'D'
    elif option == 'gromacs':
        l = []
        for i in range(101):
            l += ['2LZM_wt_trjconv_%i' %(i)]
        chain = ' '

    fd = open('2LZM_wt_trjconv_0.pdb','r')
    lines = fd.readlines()
    fd.close()
    l_coords_ref = []
    for line in lines:
        record = line[:6].strip()
        if record == 'ATOM':
            atom_name = line[12:16].strip()
            if atom_name == 'CA':
                x = float(line[30:38])
                y = float(line[38:46])
                z = float(line[46:54])
                coord = numpy.array([x,y,z,])
                l_coords_ref += [coord]

    d_transformations = {}
    for pdb in l:
        if pdb == '2LZM_wt_trjconv_0.pdb':
            continue
        fd = open('%s.pdb' %(pdb),'r')
        lines = fd.readlines()
        fd.close()
        l_coords = []
        for line in lines:
            record = line[:6].strip()
            if record == 'ATOM':
                atom_name = line[12:16].strip()
                if atom_name == 'CA' and line[21] == chain:
                    x = float(line[30:38])
                    y = float(line[38:46])
                    z = float(line[46:54])
                    coord = numpy.array([x,y,z,])
                    l_coords += [coord]
        l_coords_ref = l_coords_ref[:len(l_coords)]
        rmsd = instance_geometry.superpose(l_coords_ref,l_coords)
        tv1 = instance_geometry.fitcenter
        rm = instance_geometry.rotation
        tv2 = instance_geometry.refcenter
        d_transformations[pdb] = [tv1,rm,tv2,]

    for pdb in l:

        print pdb

        if option == 'gromacs':
##            i = int(pdb[pdb.rindex('_')+1:])
            prefix = 'rasmol%s' %(i)
        else:
            prefix = 'rasmol%s' %(pdb)

        lines_rotated = []

        ## write rasmol script
        lines_rasmol = [
            'rasmol -nodisplay %s_rotated.pdb << EOF\n' %(pdb),
            'cartoon\n',
            'wireframe 0\n',
            ]
     
        d_phipsi, lines_gnuplot = phipsi_plot.calculate_phipsi(pdb, chain = chain)

        fd = open('%s.pdb' %(pdb))
        lines1 = fd.readlines()
        fd.close()

        for line1 in lines1:

            record = line1[:6].strip()

            if record in ['HELIX','TURN','SHEET',]:
                lines_rotated += [line1]

            if record != 'ATOM':
                continue

            if line1[21] != chain:
                continue

            atom_name = line1[12:16].strip()
    ##        if atom_name != 'CA':
    ##            continue
            if atom_name not in ['N','CA','C','O',]:
                continue

            bfactor = float(line1[60:66])
            res_no = int(line1[22:26])
            res_name = line1[17:20].strip()
            if res_no not in d_phipsi.keys():
                bfactor = 50.
                continue
            else:
                phi = int(d_phipsi[res_no][0])
                psi = int(d_phipsi[res_no][1])
                if phi == 180.:
                    phi = -180.
                if psi == 180.:
                    psi = -180.
                bfactor = (
                    100
                    *d_ramachandran[d_residues[res_name]][phi][psi]
                    /float(d_max[d_residues[res_name]])
                    )

            x = float(line1[30:38])
            y = float(line1[38:46])
            z = float(line1[46:54])
            coordinate = numpy.array([x,y,z,])
            if pdb != '2LZM_wt_trjconv_0':
                tv1 = d_transformations[pdb][0]
                rm = d_transformations[pdb][1]
                tv2 = d_transformations[pdb][2]
                coordinate = numpy.dot(coordinate-tv1,rm)+tv2
            lines_rotated += ['%s%8.3f%8.3f%8.3f%s%6.2f%s' %(
                line1[:30],
                coordinate[0],coordinate[1],coordinate[2],
                line1[54:60],bfactor,line1[66:]
                )]

            h = 159.+80*bfactor/100.
            s = 240.
            l = 120.+120.*(50-abs(bfactor-50))/50.
            r,g,b = hsl2rgb(h,s,l,)
            lines_rasmol += [
                'select %i\n' %(res_no),
                'color [%i,%i,%i]\n' %(
                    r, g, b,
                    )
                ]

        fd = open('%s_rotated.pdb' %(pdb),'w')
        fd.writelines(lines_rotated)
        fd.close()

        lines_rasmol += [
##                    'ribbons\n',
            'rotate x 100\n',
            'rotate z 30\n',
            'rotate x 100\n',
            'rotate z 90\n',
            'rotate x 40\n',
            'rotate y -20\n',
            'write %s.ppm\n' %(prefix),
            'exit\n',
            ]
        ## write rasmol script to file
        fd = open('%srasmol.src' %(prefix),'w')
        fd.writelines(lines_rasmol)
        fd.close()
        ## execute rasmol script
        os.system('source %srasmol.src > %srasmol.log' %(prefix,prefix))
        ## convert rasmol output
##                os.system('convert %s.ppm -resize x80 %s.gif' %(prefix,prefix))
        os.system('convert %s.ppm %s.gif' %(prefix,prefix))
        ## clean up
        os.remove('%s.ppm' %(prefix))
        os.remove('%srasmol.log' %(prefix))
        os.remove('%srasmol.src' %(prefix))
##                os.remove('frame%s.pdb' %(str(i).zfill(2)))

    if option == 'gromacs':

        line = 'convert '
        for i in range(101): ## 0 to 100
            line += 'rasmol%s.gif ' %(i)
        for i in range(101-1-1,-1+1,-1): ## 99 to 1
            line += 'rasmol%s.gif ' %(i)
        line += '-loop 0 2lzm_MD.gif'
        print line
        os.system(line)
##        for frame in range(50):
##            os.remove('rasmol%s.gif' %(i))

    return
Example #52
0
def main():

    ## trjconv -f 2LZM_wt.trr -o 2LZM_wt_trjconv.pdb -s 2LZM_wt_MD.tpr -skip 10 -sep

    fd = open('2lzm.pdb', 'r')
    lines1 = fd.readlines()
    fd.close()
    lines2 = []
    for line in lines1:
        record = line[:6].strip()
        if record in [
                'HELIX',
                'TURN',
                'SHEET',
        ]:
            lines2 += [line]

    for i in range(50):
        fd = open('%i.pdb' % (i), 'r')
        lines = fd.readlines()
        fd.close()
        lines = lines2 + lines
        fd = open('nma%i.pdb' % (i), 'w')
        fd.writelines(lines)
        fd.close()
    stop

    import sys, os, numpy
    sys.path.append('/home/people/tc/svn/tc_sandbox/quakes/')
    import phipsi_comparison
    sys.path.append('/home/people/tc/svn/tc_sandbox/misc/')
    import phipsi_plot
    sys.path.append('/home/people/tc/svn/Protool/')
    import geometry
    instance_geometry = geometry.geometry()

    d_residues = {
        'ALA': 'A',
        'CYS': 'C',
        'ASP': 'D',
        'GLU': 'E',
        'PHE': 'F',
        'GLY': 'G',
        'HIS': 'H',
        'ILE': 'I',
        'LYS': 'K',
        'LEU': 'L',
        'MET': 'M',
        'ASN': 'N',
        'PRO': 'P',
        'GLN': 'Q',
        'ARG': 'R',
        'SER': 'S',
        'THR': 'T',
        'VAL': 'V',
        'TRP': 'W',
        'TYR': 'Y',
    }

    d_max = {}

    d_ramachandran = {}
    for res in d_residues.values():
        d_ramachandran[res] = {}
        for phi in range(-180, 180):
            d_ramachandran[res][phi] = {}
            for psi in range(-180, 180):
                d_ramachandran[res][phi][psi] = 0
    d_ramachandran = phipsi_comparison.parse_dihedrals(d_residues)  ## slow
    ##                d_ramachandran[res][phi][psi] = 1

    for res in d_ramachandran.keys():
        max = 0
        for phi in d_ramachandran[res].keys():
            for psi in d_ramachandran[res][phi].keys():
                count = d_ramachandran[res][phi][psi]
                if count > max:
                    max = count
        d_max[res] = max

    option = 'gromacs'
    option = 'pdbs'

    if option == 'frames':
        l = range(50)
    elif option == 'pdbs':
        l = [
            '150l',
        ]
        chain = 'D'
    elif option == 'gromacs':
        l = []
        for i in range(101):
            l += ['2LZM_wt_trjconv_%i' % (i)]
        chain = ' '

    fd = open('2LZM_wt_trjconv_0.pdb', 'r')
    lines = fd.readlines()
    fd.close()
    l_coords_ref = []
    for line in lines:
        record = line[:6].strip()
        if record == 'ATOM':
            atom_name = line[12:16].strip()
            if atom_name == 'CA':
                x = float(line[30:38])
                y = float(line[38:46])
                z = float(line[46:54])
                coord = numpy.array([
                    x,
                    y,
                    z,
                ])
                l_coords_ref += [coord]

    d_transformations = {}
    for pdb in l:
        if pdb == '2LZM_wt_trjconv_0.pdb':
            continue
        fd = open('%s.pdb' % (pdb), 'r')
        lines = fd.readlines()
        fd.close()
        l_coords = []
        for line in lines:
            record = line[:6].strip()
            if record == 'ATOM':
                atom_name = line[12:16].strip()
                if atom_name == 'CA' and line[21] == chain:
                    x = float(line[30:38])
                    y = float(line[38:46])
                    z = float(line[46:54])
                    coord = numpy.array([
                        x,
                        y,
                        z,
                    ])
                    l_coords += [coord]
        l_coords_ref = l_coords_ref[:len(l_coords)]
        rmsd = instance_geometry.superpose(l_coords_ref, l_coords)
        tv1 = instance_geometry.fitcenter
        rm = instance_geometry.rotation
        tv2 = instance_geometry.refcenter
        d_transformations[pdb] = [
            tv1,
            rm,
            tv2,
        ]

    for pdb in l:

        print pdb

        if option == 'gromacs':
            ##            i = int(pdb[pdb.rindex('_')+1:])
            prefix = 'rasmol%s' % (i)
        else:
            prefix = 'rasmol%s' % (pdb)

        lines_rotated = []

        ## write rasmol script
        lines_rasmol = [
            'rasmol -nodisplay %s_rotated.pdb << EOF\n' % (pdb),
            'cartoon\n',
            'wireframe 0\n',
        ]

        d_phipsi, lines_gnuplot = phipsi_plot.calculate_phipsi(pdb,
                                                               chain=chain)

        fd = open('%s.pdb' % (pdb))
        lines1 = fd.readlines()
        fd.close()

        for line1 in lines1:

            record = line1[:6].strip()

            if record in [
                    'HELIX',
                    'TURN',
                    'SHEET',
            ]:
                lines_rotated += [line1]

            if record != 'ATOM':
                continue

            if line1[21] != chain:
                continue

            atom_name = line1[12:16].strip()
            ##        if atom_name != 'CA':
            ##            continue
            if atom_name not in [
                    'N',
                    'CA',
                    'C',
                    'O',
            ]:
                continue

            bfactor = float(line1[60:66])
            res_no = int(line1[22:26])
            res_name = line1[17:20].strip()
            if res_no not in d_phipsi.keys():
                bfactor = 50.
                continue
            else:
                phi = int(d_phipsi[res_no][0])
                psi = int(d_phipsi[res_no][1])
                if phi == 180.:
                    phi = -180.
                if psi == 180.:
                    psi = -180.
                bfactor = (100 *
                           d_ramachandran[d_residues[res_name]][phi][psi] /
                           float(d_max[d_residues[res_name]]))

            x = float(line1[30:38])
            y = float(line1[38:46])
            z = float(line1[46:54])
            coordinate = numpy.array([
                x,
                y,
                z,
            ])
            if pdb != '2LZM_wt_trjconv_0':
                tv1 = d_transformations[pdb][0]
                rm = d_transformations[pdb][1]
                tv2 = d_transformations[pdb][2]
                coordinate = numpy.dot(coordinate - tv1, rm) + tv2
            lines_rotated += [
                '%s%8.3f%8.3f%8.3f%s%6.2f%s' %
                (line1[:30], coordinate[0], coordinate[1], coordinate[2],
                 line1[54:60], bfactor, line1[66:])
            ]

            h = 159. + 80 * bfactor / 100.
            s = 240.
            l = 120. + 120. * (50 - abs(bfactor - 50)) / 50.
            r, g, b = hsl2rgb(
                h,
                s,
                l,
            )
            lines_rasmol += [
                'select %i\n' % (res_no),
                'color [%i,%i,%i]\n' % (
                    r,
                    g,
                    b,
                )
            ]

        fd = open('%s_rotated.pdb' % (pdb), 'w')
        fd.writelines(lines_rotated)
        fd.close()

        lines_rasmol += [
            ##                    'ribbons\n',
            'rotate x 100\n',
            'rotate z 30\n',
            'rotate x 100\n',
            'rotate z 90\n',
            'rotate x 40\n',
            'rotate y -20\n',
            'write %s.ppm\n' % (prefix),
            'exit\n',
        ]
        ## write rasmol script to file
        fd = open('%srasmol.src' % (prefix), 'w')
        fd.writelines(lines_rasmol)
        fd.close()
        ## execute rasmol script
        os.system('source %srasmol.src > %srasmol.log' % (prefix, prefix))
        ## convert rasmol output
        ##                os.system('convert %s.ppm -resize x80 %s.gif' %(prefix,prefix))
        os.system('convert %s.ppm %s.gif' % (prefix, prefix))
        ## clean up
        os.remove('%s.ppm' % (prefix))
        os.remove('%srasmol.log' % (prefix))
        os.remove('%srasmol.src' % (prefix))
##                os.remove('frame%s.pdb' %(str(i).zfill(2)))

    if option == 'gromacs':

        line = 'convert '
        for i in range(101):  ## 0 to 100
            line += 'rasmol%s.gif ' % (i)
        for i in range(101 - 1 - 1, -1 + 1, -1):  ## 99 to 1
            line += 'rasmol%s.gif ' % (i)
        line += '-loop 0 2lzm_MD.gif'
        print line
        os.system(line)


##        for frame in range(50):
##            os.remove('rasmol%s.gif' %(i))

    return
Example #53
0
    def solve_steady(self):
        """
        function: solve_steady
        Solves for the steady state solution
        Parameters:
            -None
        Returns:
            -None
        """
        self.logger.info('Starting steady state solving...')
        self.logger.info('Setting the geometry...')
        self.geom = geometry(self.config['Bfield'], self.config['delta'],
                             self.config['R'], self.config['d'],
                             self.config['z'])
        self.logger.info('Geometry set')
        self.logger.info('The initial electron spectrum...')
        self.__init_spectrum('11')
        self.logger.info('Set the initial spectrum')
        # Synchrotron
        self.logger.info('Synchrotron...')
        A = self.geom.A
        self.particles['22_local'].flux['0'] = np.zeros(
            config['grid_22_local'])
        # transition from electron_j to gamma_i
        self.particles['22_local'].flux['0'] = \
            A * np.dot(self.synch_rate,
                       self.particles['11'].flux['0'] /
                       self.particles['11'].e_diff) / self.particles['22'].e_diff
        # This is not implemented in Damien's code
        # Also not sure what type of function onemexpdexp is,
        # it is not implemented in Damien's code
        # Opacity
        # ASSA = self.geom.ASSA
        # tauCst = self.geom.tauCst
        # for i in range(0, config['grid 22']):
        #     summtau = 0.
        #     for j in range(0, config['grid 11']):
        #         summtau += (self.opacity_rate[i][j] *
        #                     (self.particles['11'].flux['0'][j] /
        #                      (self.particles['11'].e_borders[j+1] -
        #                       self.particles['11'].e_borders[j])))
        #     summtau = ASSA*tauCst*summtau
        #     self.particles['22'].flux['0'][i] = (
        #         self.particles['22'].flux['0'][i] * onemexpdexp(summtau)
        #     )

        # IC
        self.logger.info('Inverse Compton...')
        self.particles['22_local'].flux['2'] = np.zeros(
            config['grid_22_local'])
        self.particles['22'].flux['0'] = np.zeros(config['grid_22'])
        self.particles['22'].flux['2'] = np.zeros(config['grid_22'])
        # Rescaling the photon grid according to the local version
        self.rescale('22_local', '22')
        summIC = np.zeros(config['grid_22'])
        for i in range(0, config['grid_22']):

            # This is now a matrix vector multiplication
            term = (
                np.dot(
                    self.IC_rate[i, :, :, 0],  # * mask,
                    self.particles['11'].flux['0'] /
                    self.particles['11'].e_diff))
            summIC[i] = np.sum(self.particles['22'].flux['0'] * term)

        summICfinal = (0.75 * phys_const['c'] * phys_const['sigmaT'] * summIC /
                       self.particles['22'].e_diff)

        # Multiply the emissivity by the volume.
        self.particles['22'].flux['2'] = (
            (4. * pi * self.geom.R**3 * self.geom.delta**3 /
             (self.geom.d**2 * unit_conv['Mpc_to_cm']**2 * 4. * pi * 3.)) *
            ((self.geom.R / phys_const['c']) * summICfinal) * phys_const['h'] *
            self.particles['22'].e_grid)
        self.particles['22'].flux['0'] = (
            (4. * pi * self.geom.R**3 * self.geom.delta**3 /
             (self.geom.d**2 * unit_conv['Mpc_to_cm']**2 * 4. * pi * 3.)) *
            self.particles['22'].flux['0'] * phys_const['h'] *
            self.particles['22'].e_grid)

        # Pair
        # Is not implemented
        # Normalizing pre-storage

        # Todo: Why? Think this is causes a problem when
        # changing parameters and refitting

        self.particles['22'].e_grid = (self.particles['22'].e_grid *
                                       self.geom.delta / (1. + self.geom.z))
        # Storing results
        self.logger.info('Storing results...')
        saveString = '../data/results.pkl'
        with open(saveString, 'wb') as f:
            cPickle.dump(self.particles, f, protocol=cPickle.HIGHEST_PROTOCOL)
        # Load with
        # with open(saveString, 'rb') as f:
        #             self.particles = cPickle.load(f)
        self.logger.info('Finished steady state solving...')
        self.logger.info('Results stored in particle fluxes...')
        handlers = self.logger.handlers[:]
        for handler in handlers:
            handler.close()
            self.logger.removeHandler(handler)
    def main(
        self, jobid, lines, atoms_hessian = ['CA'], frames = 50,
        cutoff_distance = 10.,
        path_python = None, verbose = False, paralleldir = '',
        biomolecule = None, chains = [], model = None,
        ):

        '''
        Use first model if no model specified by user.
        chain(s): Y, biomolecule: Y; parse chains specified by user and apply transformation
        chain(s): Y, biomolecule: N; parse chains specified by user but don't apply transformation
        chain(s): N, biomolecule: Y; parse chains of biomolecule and apply transformation
        chain(s): N, biomolecule: N; parse chains of first biomolecule and apply transformation
        '''

        import os, Numeric, goodvibes_core

        results = []

        ## parse pdb
        (
            d_REMARK350,
            d_primary, ## i.e. SEQRES, MODRES
            d_secondary, ## i.e. HELIX, SHEET
            d_coordinates, ## i.e. ATOM, HETATM, TER, MODEL, ENDMDL
            d_ligands,
            ) = goodvibes_core.parse_pdb(lines, chains)

        ## assume multimeric biological unit if chains not specified by user
        if chains == []:
            chains = d_coordinates['chains'].keys()
            chains.sort()

        ##
        ## calculate N and convert coordinates from dic to list
        ##
        N, d_hessian, l_coordinates = goodvibes_core.parse_dictionary_of_coordinates(d_coordinates, chains, atoms_hessian)

        ##
        ## calculate distance matrix
        ##
        matrix_distances = goodvibes_core.calculate_distance_matrix(l_coordinates)

        ##
        ## calculate hessian matrix
        ##
        matrix_hessian = self.hessian_calculation(N, d_coordinates, chains, atoms_hessian, float(cutoff_distance), d_secondary, matrix_distances, l_coordinates, verbose = verbose)

        ##
        ## diagonalize hessian matrix
        ##
        eigenvectors_nonperturbed, eigenvalues_nonperturbed, eigenvectors_comb_nonperturbed, = goodvibes_core.eigenv_calccomb(
                matrix_hessian, jobid, verbose,
                )

##        fd = open('/oxygenase_local/data/pdb/50/pdb150l.ent','r')
        fd = open('/oxygenase_local/data/pdb/lz/pdb2lzm.ent','r')
        lines = fd.readlines()
        fd.close()
        (
            d_REMARK350,
            d_primary, ## i.e. SEQRES, MODRES
            d_secondary, ## i.e. HELIX, SHEET
            d_coordinates, ## i.e. ATOM, HETATM, TER, MODEL, ENDMDL
            d_ligands,
            ) = goodvibes_core.parse_pdb(lines, chains)
        N, d_hessian, l_coordinates2 = goodvibes_core.parse_dictionary_of_coordinates(d_coordinates, chains, atoms_hessian)
        if len(l_coordinates) != len(l_coordinates2):
            print len(l_coordinates), len(l_coordinates2)
            stop
        ## import geometry
        import sys
        sys.path.append('/home/people/tc/svn/Protool/trunk/')
        import geometry
        instance_geometry = geometry.geometry()
        ## superpose
        rmsd = instance_geometry.superpose(l_coordinates,l_coordinates2)
        tv1 = instance_geometry.fitcenter
        rm = instance_geometry.rotation
        tv2 = instance_geometry.refcenter
        print rmsd
        ## calculate differences
        l_differences = []
        for i in range(len(l_coordinates)):
            coord1 = l_coordinates[i]
            coord2 = Numeric.matrixmultiply(l_coordinates2[i]-tv1,rm)+tv2
            l_differences += [
                coord1[0]-coord2[0],
                coord1[1]-coord2[1],
                coord1[2]-coord2[2],
                ]
        vector_difference = Numeric.array(l_differences)
        import math
        for mode in range(20):
            vector_nonperturbed = eigenvectors_nonperturbed[mode]
            overlap = math.fabs(goodvibes_core.cosangle(vector_nonperturbed, vector_difference))
            overlaps = []
            for i in range(0,164,3):
                numerator = (
                    vector_nonperturbed[i+0]*vector_difference[i+0]+
                    vector_nonperturbed[i+1]*vector_difference[i+1]+
                    vector_nonperturbed[i+2]*vector_difference[i+2]
                    )
                denominator = (
                    math.sqrt(vector_nonperturbed[i+0]**2+vector_nonperturbed[i+1]**2+vector_nonperturbed[i+2]**2)*
                    math.sqrt(vector_difference[i+0]**2+vector_difference[i+1]**2+vector_difference[i+2]**2)
                    )
                overlaps += [numerator/denominator]
            if mode == 6:
                print sum(overlaps)/len(overlaps)
                
            print mode, overlap
        stop

        ##
        ## visualize eigenvectors
        ##
        goodvibes_core.morph(
            eigenvectors_nonperturbed, frames, chains, d_coordinates,
            jobid, d_primary,
            )

        ##
        ## do plots prior to perturbation
        ##
##        goodvibes_core.pre_perturbation_plot(
##            jobid,cutoff_distance,chains,d_secondary,
##            eigenvectors_nonperturbed,eigenvectors_comb_nonperturbed,
##            )

        ##
        ## set data lists and append matrices to be plotted for each combination of modes 6-12 before initiating loops over the two axes of the plot
        ##
        datadic = goodvibes_core.datadic_return(N)

        return