public void UpdateCoords(IList <Vector> coords, bool skip_nulls) { kdtree = new KDTree.KDTree <Atom>(3); foreach (Atom atom in atoms) { int id = atom.ID; if (skip_nulls && coords[id] == null) { continue; } this.coords[id] = coords[id].Clone(); try { kdtree.insert(this.coords[id], atom); } catch (Exception) { HDebug.Assert(false); var check = kdtree.search(this.coords[id]); Vector veps = new double[3]; veps.SetValue(0.00000001); kdtree.insert(this.coords[id] + veps, atom); } } }
void Awake() { pointCloud = new float3[20000]; query = new KDQuery(); for (int i = 0; i < pointCloud.Length; i++) { pointCloud[i] = new float3( (1f + Random.value * 0.25f), (1f + Random.value * 0.25f), (1f + Random.value * 0.25f) ); } for (int i = 0; i < pointCloud.Length; i++) { for (int j = 0; j < i; j++) { pointCloud[i] += LorenzStep(pointCloud[i]) * 0.01f; } } tree = new KDTree.KDTree(pointCloud, 32); }
private void Cleanup() { _kdProxy = null; if (_bmp != null) { _bmp.Dispose(); } _bmp = null; }
/// <summary> /// Checks and searchs neighbor points for given point /// </summary> /// <param name="allPoints">Dataset</param> /// <param name="point">centered point to be searched neighbors</param> /// <param name="epsilon">radius of center point</param> /// <param name="neighborPts">result neighbors</param> private DbscanPoint <T>[] RegionQuery(KDTree.KDTree <DbscanPoint <T> > tree, T point, double epsilon) { var neighbors = new List <DbscanPoint <T> >(); var e = tree.NearestNeighbors(new[] { point.posX, point.posY, point.posZ }, 10, epsilon); while (e.MoveNext()) { neighbors.Add(e.Current); } return(neighbors.ToArray()); }
/// <summary> /// Randomise the layout of points. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Click(object sender, RoutedEventArgs e) { // Create a new bitmap and set it as our canvas background. pBitmap = BitmapFactory.New((int)cnvPoints.ActualWidth, (int)cnvPoints.ActualHeight); var pBrush = new ImageBrush(); pBrush.ImageSource = pBitmap; cnvPoints.Background = pBrush; // Clear the bitmap to light blue. using (pBitmap.GetBitmapContext()) pBitmap.Clear(Colors.LightBlue); // Get the number we want to generate and update the UI. var iResult = 0; if (!int.TryParse(txtPoints.Text, out iResult)) { txtPoints.Foreground = Brushes.Red; return; } if (iResult < 0) { txtPoints.Foreground = Brushes.Red; return; } txtPoints.Foreground = Brushes.Black; // Clear the tree and canvas. cnvPoints.Children.Clear(); pTree = new KDTree.KDTree <EllipseWrapper>(2); // Create a list of points and draw a ghost ellipse for each one. using (pBitmap.GetBitmapContext()) { // Generate X new random items. var pRandom = new Random(); for (int i = 0; i < iResult; ++i) { // Position it and add it to the canvas. var x = pRandom.NextDouble() * cnvPoints.ActualWidth; var y = pRandom.NextDouble() * cnvPoints.ActualHeight; // Add it to the tree. pTree.AddPoint(new double[] { x, y }, new EllipseWrapper(x, y)); // Draw a ghost visual for it. //pBitmap.DrawEllipse((int)x - 2, (int)y - 2, (int)x + 2, (int)y + 2, Colors.Green); pBitmap.DrawEllipse((int)x - 2, (int)y - 2, (int)x + 2, (int)y + 2, Colors.Orange); } } }
long Construct() { stopwatch.Reset(); stopwatch.Start(); tree = new KDTree.KDTree(); tree.Build(testingArray); stopwatch.Stop(); return(stopwatch.ElapsedMilliseconds); }
/// <summary> /// calculates a list of points from a point cloud, projects them to a plane and downsamples the result to ensure an average distribution of points /// </summary> /// <param name="pInputContainer">the container point cloud</param> /// <param name="pFloor">the floor to project the points on</param> /// <param name="pDownSampleFactor">a downsample factor to refine the points</param> /// <returns>a list of points projected on the floor palane</returns> static List <TPoint> CalculateCorrespondingPointsOnPlaneDownsampled(PointCloud pInputContainer, PlaneModel pFloor, double pDownSampleFactor) { //get corresponding points on plane List <TPoint> corPointsOnPlane = new List <TPoint>(); KDTree.KDTree <TPoint> corTree = new KDTree.KDTree <TPoint>(3); foreach (Point p in pInputContainer.pointcloud_hs) { //create point model, add point on plane and add distance to said plane TPoint tp; tp.point = new Point(Utility._3Dto2Dprojection.ClosestPointOnPlane(pFloor.anxPlane, new ANX.Framework.Vector3(p.point.X, p.point.Y, p.point.Z))); tp.distanceToPlane = PointCloud.calculateDistancePointToPlane(p, pFloor.anxPlane); corPointsOnPlane.Add(tp); corTree.AddPoint(new double[3] { tp.point.point.X, tp.point.point.Y, tp.point.point.Z }, tp); } //downsample where depth = max List <TPoint> corPointsOnPlaneDownsampled = new List <TPoint>(); foreach (TPoint p in corPointsOnPlane) { if (!p.point.processed) { //set current point as best fit TPoint maxDepthPoint = p; p.point.processed = true; //check neighbours if better fit exists KDTree.NearestNeighbour <TPoint> nn = corTree.NearestNeighbors(new double[] { p.point.point.X, p.point.point.Y, p.point.point.Z }, 100000, pDownSampleFactor <= 0 ? 0.01d : pDownSampleFactor); while (nn.MoveNext()) { if (!nn.Current.point.processed) { nn.Current.point.processed = true; if (nn.Current.distanceToPlane > maxDepthPoint.distanceToPlane) { maxDepthPoint = nn.Current; } } } //add best fit to new model corPointsOnPlaneDownsampled.Add(p); } } return(corPointsOnPlaneDownsampled); }
public Runner(ref IList <InputLine> cuts, ref IList <InputLine> fills) { Stopwatch sw = new Stopwatch(); double minDistance = 1e30; int closestCut = new int(); int closestFill = new int(); sw.Start(); KDTree.KDTree <InputLine> cutTree = new KDTree.KDTree <InputLine>(3); for (int i = 0; i < cuts.Count(); i++) { cutTree.AddPoint(new double[] { cuts[i].X, cuts[i].Y, cuts[i].Z }, cuts[i]); } sw.Stop(); Console.WriteLine("Tree Created in {0:0.00} milliseconds", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); for (int j = 0; j < fills.Count(); j++) { var pIter = cutTree.NearestNeighbors(new double[] { fills[j].X, fills[j].Y, fills[j].Z }, 1); while (pIter.MoveNext()) { InputLine pCurrent = pIter.Current; double currentDistance = new double(); currentDistance = pCurrent.Distance(fills[j]); if (currentDistance < minDistance) { minDistance = currentDistance; closestCut = pCurrent.PID; closestFill = fills[j].PID; } } } //cuts.Remove(new InputLine().Add(string.Format("{0},1,1,1,1",closestCut))); sw.Stop(); Console.WriteLine("Nearest Neighbor Found in {0:0.00} milliseconds", sw.ElapsedMilliseconds); Console.WriteLine("Closet Points are {0} units appart", Math.Sqrt(minDistance)); Console.WriteLine("Closet Points Cut:{0}, Fill:{1}", closestCut, closestFill); }
public static IEnumerable <Universe.Nonbonded> EnumNonbondeds (Universe.Atoms atoms , IList <Vector> coords , int size , double maxdist // = 12 , FuncListTip3pHBond func , string[] options ) { bool[] waters = new bool[coords.Count]; KDTree.KDTree <Universe.Atom> kdtree_water = new KDTree.KDTree <Universe.Atom>(3); foreach (var atom in atoms) { if (coords[atom.ID] == null) { continue; } bool water = atom.IsWater(); waters[atom.ID] = water; if (water) { kdtree_water.insert(coords[atom.ID], atom); } } Universe.Nonbondeds _nonbondeds; _nonbondeds = new Universe.Nonbondeds(atoms, size, maxdist); _nonbondeds.UpdateCoords(coords, true); foreach (var nonbonded in _nonbondeds.EnumNonbondeds(true)) { HDebug.Assert(nonbonded.atoms.Length == 2); var atom0 = nonbonded.atoms[0]; var atom1 = nonbonded.atoms[1]; if (waters[atom0.ID] && waters[atom1.ID]) { continue; } yield return(nonbonded); } foreach (Universe.Nonbonded nonbonded in func(atoms, coords, waters, kdtree_water, options)) { yield return(nonbonded); } }
public static IList <Atom> CloneByReindexByCoords(this IList <Atom> atoms, IList <Vector> coords, int serialStart = 1) { KDTree.KDTree <object> kdtree = new KDTree.KDTree <object>(3); for (int i = 0; i < coords.Count; i++) { kdtree.insert(coords[i], i); } Atom[] natoms = new Atom[atoms.Count]; for (int ai = 0; ai < natoms.Length; ai++) { Atom atom = atoms[ai]; Vector coord = atom.coord; int ni = (int)(kdtree.nearest(coord)); Vector ncoord = coords[ni]; double dist = (coord - ncoord).Dist; HDebug.AssertTolerance(0.001, dist); HDebug.Assert(natoms[ni] == null); natoms[ni] = Atom.FromData(serial: serialStart + ni , name: atom.name , resName: atom.resName , chainID: atom.chainID , resSeq: atom.resSeq , x: atom.x , y: atom.y , z: atom.z , altLoc: atom.altLoc , iCode: atom.iCode , occupancy: atom.occupancy , tempFactor: atom.tempFactor , element: atom.element , charge: atom.charge ); } if (HDebug.IsDebuggerAttached) { for (int i = 0; i < natoms.Length; i++) { HDebug.Assert(natoms[i] != null); } } return(natoms); }
public static IEnumerable <Universe.Nonbonded> ListTip3pNears (Universe.Atoms atoms , IList <Vector> coords , bool[] waters , KDTree.KDTree <Universe.Atom> kdtree_water , string[] options ) { double cutoff = 16; foreach (var option in options) { if (option.StartsWith("TIP3P:cutoff:")) { cutoff = double.Parse(option.Replace("TIP3P:cutoff:", "")); } } foreach (var atom in atoms) { if (waters[atom.ID] == false) { continue; } foreach (var near in kdtree_water.nearest(coords[atom.ID], 100)) { if (waters[near.ID] == false) { continue; } if (atom == near) { continue; } if (atom.Inter123.Contains(near)) { continue; } double dist = (coords[atom.ID] - coords[near.ID]).Dist; if (dist > cutoff) { continue; } yield return(new Universe.Nonbonded(atom, near)); } } }
/// <summary> /// /// </summary> /// <param name="allPoints">Dataset</param> /// <param name="point">point to be in a cluster</param> /// <param name="neighborPts">other points in same region with point parameter</param> /// <param name="clusterId">given clusterId</param> /// <param name="epsilon">Desired region ball range</param> /// <param name="minPts">Minimum number of points to be in a region</param> private void ExpandCluster(KDTree.KDTree <DbscanPoint <T> > tree, DbscanPoint <T> p, DbscanPoint <T>[] neighborPts, int clusterId, double epsilon, int minPts) { p.ClusterId = clusterId; //for (int i = 0; i < neighborPts.Length; i++) //{ // DbscanPoint<T> pn = neighborPts[i]; // if (!pn.IsVisited) // { // pn.IsVisited = true; // DbscanPoint<T>[] neighborPts2 = RegionQuery(tree, pn.ClusterPoint, epsilon); ; // if (neighborPts2.Length >= minPts) // { // neighborPts = neighborPts.Union(neighborPts2).ToArray(); // } // } // if (pn.ClusterId == (int)ClusterIds.Unclassified) // pn.ClusterId = clusterId; //} var queue = new Queue <DbscanPoint <T> >(neighborPts); while (queue.Count > 0) { var point = queue.Dequeue(); if (point.ClusterId == (int)ClusterIds.Unclassified) { point.ClusterId = clusterId; } if (point.IsVisited) { continue; } point.IsVisited = true; var neighbors = RegionQuery(tree, point.ClusterPoint, epsilon); if (neighbors.Length >= minPts) { foreach (var neighbor in neighbors.Where(neighbor => !neighbor.IsVisited)) { queue.Enqueue(neighbor); } } } }
public void ComputeClusterDbscan(T[] allPoints, double epsilon, int minPts, out HashSet <T[]> clusters, ref List <int> clusterIds) { DbscanPoint <T>[] allPointsDbscan = allPoints.Where(x => x.posX != 0 || x.posY != 0 || x.posZ != 0) .Select(x => new DbscanPoint <T>(x)).ToArray(); var tree = new KDTree.KDTree <DbscanPoint <T> >(3); for (var i = 0; i < allPointsDbscan.Length; ++i) { Record temp = allPointsDbscan[i].ClusterPoint; tree.AddPoint(new double[] { temp.posX, temp.posY, temp.posZ }, allPointsDbscan[i]); } int clusterId = 0; for (int i = 0; i < allPointsDbscan.Length; i++) { DbscanPoint <T> p = allPointsDbscan[i]; if (p.IsVisited) { clusterIds.Add(p.ClusterId); continue; } p.IsVisited = true; var neighborPts = RegionQuery(tree, p.ClusterPoint, epsilon); if (neighborPts.Length < minPts) { p.ClusterId = (int)ClusterIds.Noise; } else { clusterId++; ExpandCluster(tree, p, neighborPts, clusterId, epsilon, minPts); } clusterIds.Add(p.ClusterId); } clusters = new HashSet <T[]>( allPointsDbscan .Where(x => x.ClusterId > 0) .GroupBy(x => x.ClusterId) .Select(x => x.Select(y => y.ClusterPoint).ToArray()) ); }
/// <summary> /// Perform calculations and update data. /// </summary> /// <param name="updateTime">Time since last update.</param> /// <remarks>include base.Update(renderTime); in overloads to preserve updating UpdateTime field.</remarks> public override void Update(RenderTime updateTime) { // if we don't have a data provider, don't update if (MM_Repository.OverallDisplay.Contour == MM_Display.MM_Contour_Enum.None) { return; } if (!MM_Repository.ContourDataProviders.TryGetValue(MM_Repository.OverallDisplay.ContourData, out DataProvider)) { return; } base.Update(updateTime); bool contourChanged = _lastProvider != MM_Repository.OverallDisplay.ContourData; if (Surface.Coordinates.ZoomLevel != _zoomLevel || _kdProxy == null || contourChanged || (updateTime.TotalTime - _lastUpdate).TotalSeconds > MM_Repository.OverallDisplay.ContourRefreshTime) { _lastUpdate = updateTime.TotalTime; _lastProvider = MM_Repository.OverallDisplay.ContourData; _kdProxy = new KDTree.KDTree <ContourData>(2); _zoomLevel = Surface.Coordinates.ZoomLevel; foreach (var item in DataProvider.GetData()) { var coord = MM_Coordinates.LngLatToScreenVector2(item.LngLat, _zoomLevel); item.XY = coord; _kdProxy.AddPoint(new double[] { coord.X, coord.Y }, item); } if (_bmp != null) { _bmp.Dispose(); } if (contourChanged) { Surface.AddOnscreenMessage("Contour layer changed: " + _lastProvider.ToString(), SharpDX.Color.Aqua); } } }
public Nonbondeds(Atoms atoms , int size , double maxdist // = 12 ) { // length this.size = size; // maxdist this.maxdist = maxdist; this.maxdist2 = maxdist * maxdist; // atoms & coords HDebug.Assert(size == atoms.Count); this.atoms = new Atom[size]; foreach (Atom atom in atoms) { int id = atom.ID; HDebug.Assert(this.atoms[id] == null); this.atoms[id] = atom; } // assign memory for this.coords and this.nonbondeds this.coords = new Vector[size]; this.kdtree = null; }
public bool CheckCenterEmpty(T[] clusterPoints, T centerPoint, double epsilon, int maxPts) { DbscanPoint <T>[] clusterPointsDbscan = clusterPoints.Select(x => new DbscanPoint <T>(x)).ToArray(); var tree = new KDTree.KDTree <DbscanPoint <T> >(3); for (var i = 0; i < clusterPointsDbscan.Length; ++i) { Record temp = clusterPointsDbscan[i].ClusterPoint; tree.AddPoint(new double[] { temp.posX, temp.posY, temp.posZ }, clusterPointsDbscan[i]); } Record tempCenter = new DbscanPoint <T>(centerPoint).ClusterPoint; tree.AddPoint(new double[] { tempCenter.posX, tempCenter.posY, tempCenter.posZ }, new DbscanPoint <T>(centerPoint)); var neighborPts = RegionQuery(tree, centerPoint, epsilon); if (neighborPts.Length > maxPts) { return(false); } else { return(true); } }
public static IEnumerable <IList <Pdb.IAtom> > SoakMoleculeISolventBox(IList <Pdb.IAtom> mole, IList <IList <Pdb.IAtom> > solv_atoms, Namd.Prm prm) { yield return(mole); KDTree.KDTree <Pdb.IAtom> kdtree_mole = new KDTree.KDTree <Pdb.IAtom>(3); foreach (var atom in mole) { kdtree_mole.insert(atom.coord, atom); } //List<Pdb.IAtom> socked = new List<Pdb.IAtom>(); //socked.AddRange(mole); Dictionary <string, double> elem_radius = new Dictionary <string, double> { #region {"C", 1.90}, ... // public static NbndInfo[] nbndinfo_set_SSTeMcs6c = new NbndInfo[] // { { "C", 1.90 }, // new NbndInfo{ nbndtype=NbndType.nbnd , atomelem="C", rmin2=1.90, charge=0.0, epsilon=-0.1}, { "H", 1.20 }, // new NbndInfo{ nbndtype=NbndType.nbnd , atomelem="H", rmin2=1.20, charge=0.0, epsilon=-0.1}, { "O", 1.70 }, // new NbndInfo{ nbndtype=NbndType.nbnd , atomelem="O", rmin2=1.70, charge=0.0, epsilon=-0.1}, { "N", 1.85 }, // new NbndInfo{ nbndtype=NbndType.nbnd , atomelem="N", rmin2=1.85, charge=0.0, epsilon=-0.1}, { "S", 2.00 }, // new NbndInfo{ nbndtype=NbndType.nbnd , atomelem="S", rmin2=2.00, charge=0.0, epsilon=-0.1}, { "F", 1.47 }, // new NbndInfo{ nbndtype=NbndType.nbnd , atomelem="F", rmin2=1.47, charge=0.0, epsilon=-0.1}, /// same to unif0 { "P", 1.80 }, // new NbndInfo{ nbndtype=NbndType.nbnd , atomelem="P", rmin2=1.80, charge=0.0, epsilon=-0.1}, /// same to unif0 // new NbndInfo{ nbndtype=NbndType.nbnd14, atomelem="C", rmin2=1.90, charge=0.0, epsilon=-0.1}, // new NbndInfo{ nbndtype=NbndType.nbnd14, atomelem="H", rmin2=1.20, charge=0.0, epsilon=-0.1}, // new NbndInfo{ nbndtype=NbndType.nbnd14, atomelem="O", rmin2=1.40, charge=0.0, epsilon=-0.1}, /// special treatment: 1.70 -> 1.40 // new NbndInfo{ nbndtype=NbndType.nbnd14, atomelem="N", rmin2=1.55, charge=0.0, epsilon=-0.1}, /// special treatment: 1.85 -> 1.55 // new NbndInfo{ nbndtype=NbndType.nbnd14, atomelem="S", rmin2=2.00, charge=0.0, epsilon=-0.1}, // new NbndInfo{ nbndtype=NbndType.nbnd14, atomelem="F", rmin2=1.47, charge=0.0, epsilon=-0.1}, /// same to unif0 // new NbndInfo{ nbndtype=NbndType.nbnd14, atomelem="P", rmin2=1.80, charge=0.0, epsilon=-0.1}, /// same to unif0 // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // //new NbndInfo{ nbndtype=NbndType.nbnd, atomelem="", rmin2=0.00, charge=0.0, epsilon=-0.1}, // // http://en.wikipedia.org/wiki/Van_der_Waals_radius { "CL", 1.75 }, // new NbndInfo{ nbndtype=NbndType.nbnd, atomelem="CL", rmin2=1.75, charge=0.0, epsilon=-0.1}, { "CU", 1.40 }, // new NbndInfo{ nbndtype=NbndType.nbnd, atomelem="CU", rmin2=1.40, charge=0.0, epsilon=-0.1}, // // http://en.wikipedia.org/wiki/Atomic_radii_of_the_elements_(data_page) { "MG", 1.73 }, // new NbndInfo{ nbndtype=NbndType.nbnd, atomelem="MG", rmin2=1.73, charge=0.0, epsilon=-0.1}, // magnesium { "K", 2.75 }, // new NbndInfo{ nbndtype=NbndType.nbnd, atomelem="K" , rmin2=2.75, charge=0.0, epsilon=-0.1}, // potassium { "POT", 2.75 }, // new NbndInfo{ nbndtype=NbndType.nbnd, atomelem="POT",rmin2=2.75, charge=0.0, epsilon=-0.1}, // potassium // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // par_all27_prot_na.prm // // FE 0.010000 0.000000 0.650000 ! ALLOW HEM // new NbndInfo{ nbndtype=NbndType.nbnd , atomelem="FE" ,rmin2=0.65, charge=0.0, epsilon=-0.1}, // new NbndInfo{ nbndtype=NbndType.nbnd14, atomelem="FE" ,rmin2=0.65, charge=0.0, epsilon=-0.1}, // }; #endregion }; bool noclash_with_mole = false; foreach (var atoms in solv_atoms) { List <Pdb.IAtom> noclash_atoms = new List <Pdb.IAtom>(); foreach (var atom in atoms) { Vector atom_coord = atom.coord; double atom_rmin = elem_radius[atom.element.Trim()]; Pdb.IAtom near = kdtree_mole.nearest(atom_coord); double near_rmin = elem_radius[near.element.Trim()]; double dist = (atom_coord - near.coord).Dist; if (atom.name == "OH2 ") { if ((atom_rmin + near_rmin) < dist) { noclash_with_mole = true; } else { noclash_with_mole = false; } } if (noclash_with_mole) { noclash_atoms.Add(atom); //yield return atom; //socked.Add(atom); } } if (noclash_atoms.Count != 0) { yield return(noclash_atoms); } } }
void Start() { query = new KDTree.KDQuery(); tree = new KDTree.KDTree <JustPoint>(points, 8); }
public static Universe Build(Tinker.Xyz xyz, Tinker.Prm prm, Pdb pdb , double?tolCoordPdbXyz // 0.002 for default distance // (0.001 * sqrt(3) = 0.0017321, which is the largest tolerance between pdb and xyz) // null for not ordering by distance; ) { Universe univ = new Universe(); Dictionary <int, Prm.Atom> prm_id2atom = prm.atoms.ToIdDictionary(); Dictionary <int, Prm.Vdw> prm_cls2vdw = prm.vdws.ToClassDictionary(); Dictionary <int, Prm.Vdw14> prm_cls2vdw14 = prm.vdw14s.ToClassDictionary(); Dictionary <Tuple <int, int>, Prm.Bond> prm_cls2bond = prm.bonds.ToClassDictionary(); Dictionary <Tuple <int, int, int>, Prm.Angle> prm_cls2angle = prm.angles.ToClassDictionary(); Dictionary <Tuple <int, int, int>, Prm.Ureybrad> prm_cls2ureybrad = prm.ureybrads.ToClassDictionary(); Dictionary <Tuple <int, int, int, int>, Prm.Improper> prm_cls2improper = prm.impropers.ToClassDictionary(); Dictionary <Tuple <int, int, int, int>, Prm.Torsion> prm_cls2torsion = prm.torsions.ToClassDictionary(); Dictionary <int, Prm.Charge> prm_id2charge = prm.charges.ToIdDictionary(); Prm.Biotype[] prm_biotypes = prm.biotypes; Xyz.Atom[] xyz_atoms = xyz.atoms; Pdb.Atom[] pdb_atoms = (pdb != null) ? pdb.atoms : null; Dictionary <int, Xyz.Atom> xyz_id2atom = xyz_atoms.ToIdDictionary(); KDTree.KDTree <Tuple <int, Pdb.Atom> > coord2pdbatom = null; { if (pdb_atoms != null) { coord2pdbatom = new KDTree.KDTree <Tuple <int, Pdb.Atom> >(3); for (int ia = 0; ia < pdb_atoms.Length; ia++) { Pdb.Atom pdb_atom = pdb_atoms[ia]; Vector coord = pdb_atom.coord; coord2pdbatom.insert(coord.ToArray(), new Tuple <int, Pdb.Atom>(ia, pdb_atom)); } } } Atoms atoms = new Atoms(univ); /// Debug.Assert(pdb.atoms.Length == top_atoms.Count); for (int i = 0; i < xyz_atoms.Length; i++) { Xyz.Atom xyz_atom = xyz_atoms[i]; Pdb.Atom pdb_atom = null; // = (pdb_atoms != null) ? (pdb_atoms[i]) : null; if (coord2pdbatom != null) { Vector xyz_coord = xyz_atom.Coord; Tuple <int, Pdb.Atom> ia_atom = coord2pdbatom.nearest(xyz_coord); Vector pdb_coord = ia_atom.Item2.coord; if (tolCoordPdbXyz == null) { pdb_atom = pdb_atoms[i]; } else { if ((xyz_coord - pdb_coord).Dist < tolCoordPdbXyz) { pdb_atom = ia_atom.Item2; } else { //HDebug.Assert(false); pdb_atom = null; } } } if (pdb_atom != null) { string pdb_atom_type = pdb_atom.element.Trim(); string xyz_atom_type = xyz_atom.AtomType.Trim(); if (HDebug.IsDebuggerAttached && pdb_atom_type.Length > 0) // sometimes element is blank: " " { HDebug.AssertIf(pdb_atom_type[0] == xyz_atom_type[0]); } if (tolCoordPdbXyz != null) { HDebug.AssertTolerance(tolCoordPdbXyz.Value, xyz_atom.Coord - pdb_atom.coord); } } //if(pdb_atom != null) Debug.Assert(xyz_atom.Id == pdb_atom.serial); HDebug.Assert(i + 1 == xyz_atom.Id); Prm.Atom prm_atom = prm_id2atom [xyz_atom.AtomId]; Prm.Charge prm_charge = prm_id2charge[xyz_atom.AtomId]; Prm.Vdw prm_vdw = null; Prm.Vdw14 prm_vdw14 = null; if (prm_cls2vdw.ContainsKey(prm_atom.Class)) { prm_vdw = prm_cls2vdw [prm_atom.Class]; } if (prm_cls2vdw14.ContainsKey(prm_atom.Class)) { prm_vdw14 = prm_cls2vdw14[prm_atom.Class]; } if (pdb_atom != null) { if (pdb_atom.element.Trim() != "") { if (pdb_atom.element.Trim() != prm_atom.AtomElem) { throw new Exception(); } } } Atom uatom = new Atom(AtomId: xyz_atom.Id , AtomName: ((pdb_atom != null) ? (pdb_atom.name.Trim()) : ("?" + prm_atom.Type)) /// fix later , AtomType: prm_atom.Type , AtomElem: prm_atom.AtomElem , ResidueId: ((pdb_atom != null) ? (pdb_atom.resSeq) : (-1)) /// fix later , ResidueName: ((pdb_atom != null) ? (pdb_atom.resName.Trim()) : ("?res")) /// fix later , Charge: prm_charge.pch , Mass: prm_atom.Mass , epsilon: ((prm_vdw != null) ? prm_vdw.Epsilon : 0) , Rmin2: ((prm_vdw != null) ? prm_vdw.Rmin2 : 0) , eps_14: ((prm_vdw14 != null) ? prm_vdw14.Eps_14 : double.NaN) , Rmin2_14: ((prm_vdw14 != null) ? prm_vdw14.Rmin2_14 : double.NaN) , sources: new object[] { xyz_atom, pdb_atom, prm_atom, prm_charge } ); uatom.Coord = xyz_atom.Coord; atoms.Add(uatom); } // bonds Bonds bonds; { Dictionary <Tuple <Atom, Atom>, Bond> lbonds = new Dictionary <Tuple <Atom, Atom>, Bond>(); for (int i = 0; i < xyz_atoms.Length; i++) { int id0 = xyz_atoms[i].Id; HDebug.Assert(id0 == i + 1); int atm0 = xyz_atoms[i].AtomId; int cls0 = prm_id2atom[atm0].Class; Atom atom0 = atoms[id0 - 1]; HDebug.Assert(atom0.AtomId == id0); Tuple <int, int> cls; foreach (int id1 in xyz_atoms[i].BondedIds) { int atm1 = xyz_id2atom[id1].AtomId; int cls1 = prm_id2atom[atm1].Class; Atom atom1 = atoms[id1 - 1]; HDebug.Assert(atom1.AtomId == id1); HashSet <Prm.Bond> bondtypes = new HashSet <Prm.Bond>(); Atom[] iatom = null; cls = new Tuple <int, int>(cls0, cls1); if (prm_cls2bond.ContainsKey(cls)) { bondtypes.Add(prm_cls2bond[cls]); iatom = new Atom[] { atom0, atom1 }; } cls = new Tuple <int, int>(cls1, cls0); if (prm_cls2bond.ContainsKey(cls)) { bondtypes.Add(prm_cls2bond[cls]); iatom = new Atom[] { atom1, atom0 }; } HDebug.Assert(bondtypes.Count == 1); if (bondtypes.Count >= 1) { Prm.Bond bondtype = bondtypes.Last(); HDebug.Assert(bondtype != null); // sort atom id, in order to avoid duplication of bonds such that (0,1) and (1,0) if (iatom.First().ID > iatom.Last().ID) { iatom = iatom.Reverse().ToArray(); } var key = new Tuple <Atom, Atom>(iatom[0], iatom[1]); Bond bond = new Bond(iatom[0], iatom[1], bondtype.Kb, bondtype.b0, bondtype); if (lbonds.ContainsKey(key) == false) { lbonds.Add(key, bond); } else { HDebug.Assert(bond.Kb == lbonds[key].Kb); HDebug.Assert(bond.b0 == lbonds[key].b0); } } } } bonds = new Bonds(); foreach (Bond bond in lbonds.Values) { HDebug.Assert(bond.atoms.Length == 2); HDebug.Assert(bond.atoms[0].ID < bond.atoms[1].ID); bonds.Add(bond); Atom atom0 = bond.atoms[0]; Atom atom1 = bond.atoms[1]; atom0.Bonds.Add(bond); atom0.Inter123.Add(atom1); atom0.Inter12.Add(atom1); atom1.Bonds.Add(bond); atom1.Inter123.Add(atom0); atom1.Inter12.Add(atom0); } } HashSet <Atom>[] inter12 = new HashSet <Atom> [xyz_atoms.Length]; HashSet <Tuple <Atom, Atom> >[] inter123 = new HashSet <Tuple <Atom, Atom> > [xyz_atoms.Length]; HashSet <Tuple <Atom, Atom, Atom> >[] inter1234 = new HashSet <Tuple <Atom, Atom, Atom> > [xyz_atoms.Length]; { HDebug.Assert(xyz_atoms.Length == atoms.Count); foreach (Atom atom in atoms) { inter12 [atom.ID] = new HashSet <Atom>(atom.Inter12); inter123 [atom.ID] = new HashSet <Tuple <Atom, Atom> >(); inter1234[atom.ID] = new HashSet <Tuple <Atom, Atom, Atom> >(); } // build inter123 and inter1234 for (int i = 0; i < xyz_atoms.Length; i++) { Atom atom0 = atoms[i]; HDebug.Assert(atom0.ID == i); foreach (Atom atom1 in inter12[atom0.ID]) { HDebug.Assert(atom0 != atom1); foreach (Atom atom2 in inter12[atom1.ID]) { HDebug.Assert(atom1 != atom2); if (atom0 == atom2) { continue; } inter123[atom0.ID].Add(new Tuple <Atom, Atom>(atom1, atom2)); foreach (Atom atom3 in inter12[atom2.ID]) { HDebug.Assert(atom2 != atom3); if (atom0 == atom2) { continue; } if (atom0 == atom3) { continue; } if (atom1 == atom3) { continue; } inter1234[atom0.ID].Add(new Tuple <Atom, Atom, Atom>(atom1, atom2, atom3)); } } } } } // angles Angles angles; { Dictionary <Tuple <Atom, Atom, Atom>, Angle> langles = new Dictionary <Tuple <Atom, Atom, Atom>, Angle>(); foreach (Atom atom0 in atoms) { int id0 = xyz_atoms[atom0.ID].Id; HDebug.Assert(id0 == atom0.ID + 1); int atm0 = xyz_atoms[atom0.ID].AtomId; int cls0 = prm_id2atom[atm0].Class; foreach (var atom123 in inter123[atom0.ID]) { Atom atom1 = atom123.Item1; int atm1 = xyz_atoms[atom1.ID].AtomId; int cls1 = prm_id2atom[atm1].Class; Atom atom2 = atom123.Item2; int atm2 = xyz_atoms[atom2.ID].AtomId; int cls2 = prm_id2atom[atm2].Class; Tuple <int, int, int> cls; Atom[] iatom = null; HashSet <Prm.Angle> angs = new HashSet <Prm.Angle>(); HashSet <Prm.Ureybrad> urbs = new HashSet <Prm.Ureybrad>(); cls = new Tuple <int, int, int>(cls0, cls1, cls2); if (prm_cls2angle.ContainsKey(cls)) { angs.Add(prm_cls2angle[cls]); iatom = new Atom[] { atom0, atom1, atom2 }; } if (prm_cls2ureybrad.ContainsKey(cls)) { urbs.Add(prm_cls2ureybrad[cls]); } cls = new Tuple <int, int, int>(cls2, cls1, cls0); if (prm_cls2angle.ContainsKey(cls)) { angs.Add(prm_cls2angle[cls]); iatom = new Atom[] { atom2, atom1, atom0 }; } if (prm_cls2ureybrad.ContainsKey(cls)) { urbs.Add(prm_cls2ureybrad[cls]); } HDebug.Assert(angs.Count == 1); HDebug.Assert(urbs.Count <= angs.Count); if (angs.Count >= 1) { Prm.Angle ang = angs.Last(); HDebug.Assert(ang != null); Prm.Ureybrad urb = null; if (urbs.Count >= 1) { urb = urbs.Last(); } // sort atom id, in order to avoid duplication of bonds such that (0,1) and (1,0) if (iatom.First().ID > iatom.Last().ID) { iatom = iatom.Reverse().ToArray(); } var key = new Tuple <Atom, Atom, Atom>(iatom[0], iatom[1], iatom[2]); Angle angle = new Angle(iatom[0], iatom[1], iatom[2] , Ktheta: ang.Ktheta , Theta0: ang.Theta0 , Kub: ((urb != null) ? urb.Kub : 0) , S0: ((urb != null) ? urb.S0 : 0) , sources: new object[] { ang, urb } ); if (langles.ContainsKey(key) == false) { langles.Add(key, angle); } else { HDebug.Assert(langles[key].Ktheta == angle.Ktheta , langles[key].Theta0 == angle.Theta0 , langles[key].Kub == angle.Kub , langles[key].S0 == angle.S0 ); } } } } angles = new Angles(); foreach (Angle angle in langles.Values) { HDebug.Assert(angle.atoms.Length == 3); HDebug.Assert(angle.atoms[0].ID < angle.atoms[2].ID); angles.Add(angle); Atom atom0 = angle.atoms[0]; Atom atom1 = angle.atoms[1]; Atom atom2 = angle.atoms[2]; atom0.Angles.Add(angle); atom0.Inter123.Add(atom1); atom0.Inter123.Add(atom2); atom1.Angles.Add(angle); atom1.Inter123.Add(atom2); atom1.Inter123.Add(atom0); atom2.Angles.Add(angle); atom2.Inter123.Add(atom0); atom2.Inter123.Add(atom1); } } // dihedrals Dihedrals dihedrals; { Dictionary <Tuple <Atom, Atom, Atom, Atom>, List <Dihedral> > ldihedrals = new Dictionary <Tuple <Atom, Atom, Atom, Atom>, List <Dihedral> >(); foreach (Atom atom0 in atoms) { int id0 = xyz_atoms[atom0.ID].Id; HDebug.Assert(id0 == atom0.ID + 1); int atm0 = xyz_atoms[atom0.ID].AtomId; int cls0 = prm_id2atom[atm0].Class; Tuple <int, int, int, int> cls; foreach (var atom1234 in inter1234[atom0.ID]) { Atom atom1 = atom1234.Item1; int atm1 = xyz_atoms[atom1.ID].AtomId; int cls1 = prm_id2atom[atm1].Class; Atom atom2 = atom1234.Item2; int atm2 = xyz_atoms[atom2.ID].AtomId; int cls2 = prm_id2atom[atm2].Class; Atom atom3 = atom1234.Item3; int atm3 = xyz_atoms[atom3.ID].AtomId; int cls3 = prm_id2atom[atm3].Class; HashSet <Prm.Torsion> tors = new HashSet <Prm.Torsion>(); Atom[] iatom = null; cls = new Tuple <int, int, int, int>(cls0, cls1, cls2, cls3); if (prm_cls2torsion.ContainsKey(cls)) { tors.Add(prm_cls2torsion[cls]); iatom = new Atom[] { atom0, atom1, atom2, atom3 }; } cls = new Tuple <int, int, int, int>(cls3, cls2, cls1, cls0); if (prm_cls2torsion.ContainsKey(cls)) { tors.Add(prm_cls2torsion[cls]); iatom = new Atom[] { atom3, atom2, atom1, atom0 }; } HDebug.Assert(tors.Count == 1); if (tors.Count >= 1) { // sort atom id, in order to avoid duplication of bonds such that (0,1) and (1,0) if (iatom.First().ID > iatom.Last().ID) { iatom = iatom.Reverse().ToArray(); } var key = new Tuple <Atom, Atom, Atom, Atom>(iatom[0], iatom[1], iatom[2], iatom[3]); if (ldihedrals.ContainsKey(key) == false) { ldihedrals.Add(key, new List <Dihedral>()); Prm.Torsion tor = tors.Last(); foreach (var tordat in tor.GetListData()) { Dihedral dihedral = new Dihedral(iatom[0], iatom[1], iatom[2], iatom[3] , Kchi: tordat.Kchi , n: tordat.n , delta: tordat.delta , sources: new object[] { tor } ); ldihedrals[key].Add(dihedral); HDebug.Assert(dihedral.n != 0); } } else { // do not check its contents because ... } } } } dihedrals = new Dihedrals(); foreach (var ldihedral in ldihedrals.Values) { foreach (Dihedral dihedral in ldihedral) { HDebug.Assert(dihedral.atoms.Length == 4); HDebug.Assert(dihedral.atoms[0].ID < dihedral.atoms[3].ID); dihedrals.Add(dihedral); dihedral.atoms[0].Dihedrals.Add(dihedral); dihedral.atoms[1].Dihedrals.Add(dihedral); dihedral.atoms[2].Dihedrals.Add(dihedral); dihedral.atoms[3].Dihedrals.Add(dihedral); } } } // impropers Impropers impropers = new Impropers(); { Dictionary <Tuple <Atom, Atom, Atom, Atom>, Improper> limpropers = new Dictionary <Tuple <Atom, Atom, Atom, Atom>, Improper>(); foreach (Atom atom0 in atoms) { /// #################################### /// ## ## /// ## Improper Dihedral Parameters ## /// ## ## /// #################################### /// /// ################################################################## /// ## ## /// ## Following CHARMM style, the improper for a trigonal atom ## /// ## D bonded to atoms A, B and C could be input as improper ## /// ## dihedral angle D-A-B-C. The actual angle computed by the ## /// ## program is then literally the dihedral D-A-B-C, which will ## /// ## always have as its ideal value zero degrees. In general ## /// ## D-A-B-C is different from D-B-A-C; the order of the three ## /// ## peripheral atoms matters. In the original CHARMM parameter ## /// ## files, the trigonal atom is often listed last; ie, as ## /// ## C-B-A-D instead of D-A-B-C. ## /// ## ## /// ## Some of the improper angles are "double counted" in the ## /// ## CHARMM protein parameter set. Since TINKER uses only one ## /// ## improper parameter per site, we have doubled these force ## /// ## constants in the TINKER version of the CHARMM parameters. ## /// ## Symmetric parameters, which are the origin of the "double ## /// ## counted" CHARMM values, are handled in the TINKER package ## /// ## by assigning all symmetric states and using the TINKER ## /// ## force constant divided by the symmetry number. ## /// ## ## /// ## ... ## /// ################################################################## int id0 = xyz_atoms[atom0.ID].Id; HDebug.Assert(id0 == atom0.ID + 1); int atm0 = xyz_atoms[atom0.ID].AtomId; int cls0 = prm_id2atom[atm0].Class; bool bAtom0InImpropers = false; foreach (var cls in prm_cls2improper.Keys) { if (cls.Item1 == cls0) { bAtom0InImpropers = true; } } if (bAtom0InImpropers == false) { continue; } Atom[] bondeds0 = inter12[atom0.ID].ToArray(); if (bondeds0.Length < 3) { continue; } for (int i = 0; i < bondeds0.Length - 2; i++) { Atom atom1 = bondeds0[i]; int atm1 = xyz_atoms[atom1.ID].AtomId; int cls1 = prm_id2atom[atm1].Class; for (int j = i + 1; j < bondeds0.Length - 1; j++) { Atom atom2 = bondeds0[j]; int atm2 = xyz_atoms[atom2.ID].AtomId; int cls2 = prm_id2atom[atm2].Class; for (int k = j + 1; k < bondeds0.Length; k++) { Atom atom3 = bondeds0[k]; int atm3 = xyz_atoms[atom3.ID].AtomId; int cls3 = prm_id2atom[atm3].Class; Tuple <int, int, int, int> cls; HashSet <Prm.Improper> imps = new HashSet <Prm.Improper>(); Atom[] iatom = null; cls = new Tuple <int, int, int, int>(cls0, cls1, cls2, cls3); if (prm_cls2improper.ContainsKey(cls)) { imps.Add(prm_cls2improper[cls]); iatom = new Atom[] { atom0, atom1, atom2, atom3 }; } cls = new Tuple <int, int, int, int>(cls3, cls2, cls1, cls0); if (prm_cls2improper.ContainsKey(cls)) { imps.Add(prm_cls2improper[cls]); iatom = new Atom[] { atom3, atom2, atom1, atom0 }; } cls = new Tuple <int, int, int, int>(cls0, cls1, cls3, cls2); if (prm_cls2improper.ContainsKey(cls)) { imps.Add(prm_cls2improper[cls]); iatom = new Atom[] { atom0, atom1, atom3, atom2 }; } cls = new Tuple <int, int, int, int>(cls2, cls3, cls1, cls0); if (prm_cls2improper.ContainsKey(cls)) { imps.Add(prm_cls2improper[cls]); iatom = new Atom[] { atom2, atom3, atom1, atom0 }; } cls = new Tuple <int, int, int, int>(cls0, cls2, cls1, cls3); if (prm_cls2improper.ContainsKey(cls)) { imps.Add(prm_cls2improper[cls]); iatom = new Atom[] { atom0, atom2, atom1, atom3 }; } cls = new Tuple <int, int, int, int>(cls3, cls1, cls2, cls0); if (prm_cls2improper.ContainsKey(cls)) { imps.Add(prm_cls2improper[cls]); iatom = new Atom[] { atom3, atom1, atom2, atom0 }; } cls = new Tuple <int, int, int, int>(cls0, cls2, cls3, cls1); if (prm_cls2improper.ContainsKey(cls)) { imps.Add(prm_cls2improper[cls]); iatom = new Atom[] { atom0, atom2, atom3, atom1 }; } cls = new Tuple <int, int, int, int>(cls1, cls3, cls2, cls0); if (prm_cls2improper.ContainsKey(cls)) { imps.Add(prm_cls2improper[cls]); iatom = new Atom[] { atom1, atom3, atom2, atom0 }; } cls = new Tuple <int, int, int, int>(cls0, cls3, cls1, cls2); if (prm_cls2improper.ContainsKey(cls)) { imps.Add(prm_cls2improper[cls]); iatom = new Atom[] { atom0, atom3, atom1, atom2 }; } cls = new Tuple <int, int, int, int>(cls2, cls1, cls3, cls0); if (prm_cls2improper.ContainsKey(cls)) { imps.Add(prm_cls2improper[cls]); iatom = new Atom[] { atom2, atom1, atom3, atom0 }; } cls = new Tuple <int, int, int, int>(cls0, cls3, cls2, cls1); if (prm_cls2improper.ContainsKey(cls)) { imps.Add(prm_cls2improper[cls]); iatom = new Atom[] { atom0, atom3, atom2, atom1 }; } cls = new Tuple <int, int, int, int>(cls1, cls2, cls3, cls0); if (prm_cls2improper.ContainsKey(cls)) { imps.Add(prm_cls2improper[cls]); iatom = new Atom[] { atom1, atom2, atom3, atom0 }; } HDebug.Assert(imps.Count <= 1); // for example, H-C-HHH has C-HHH connectivity but it is not improper... // so imps.count <= 1 if (imps.Count >= 1) { Prm.Improper imp = imps.Last(); // because iatoms contains the last case only. /////////////////////////////////////////////////////////////////////////////////////// // This bug was raised by Jae-Kyun Song at 2016-04-01 // // In 1AAC, (1501,C)-(1503,NC2)-(1502,NC2)-(1500,NC2) is reordered // // as (1500,NC2)-(1502,NC2)-(1503,NC2)-(1501,C) // // This bug was originally copied from dihedral code that is added to prevent adding // // duplicated interactions such as 1-2-3-4 and 4-3-2-1. // /////////////////////////////////////////////////////////////////////////////////////// /// old code // // sort atom id, in order to avoid duplication of bonds such that (0,1) and (1,0) // if(iatom.First().ID > iatom.Last().ID) // iatom = iatom.Reverse().ToArray(); // var key = new Tuple<Atom, Atom, Atom, Atom>(iatom[0], iatom[1], iatom[2], iatom[3]); /////////////////////////////////////////////////////////////////////////////////////// /// new code Tuple <Atom, Atom, Atom, Atom> key; { Atom key0 = iatom[0]; Atom[] key123 = (new Atom[] { iatom[1], iatom[2], iatom[3] }).SortByIDs(); key = new Tuple <Atom, Atom, Atom, Atom>(key0, key123[0], key123[1], key123[2]); } /////////////////////////////////////////////////////////////////////////////////////// Improper improper = new Improper(iatom[0], iatom[1], iatom[2], iatom[3] , Kpsi: imp.Kpsi , psi0: imp.psi0 , sources: new object[] { imp } ); if (limpropers.ContainsKey(key) == false) { limpropers.Add(key, improper); } else { HDebug.Assert(limpropers[key].Kpsi == improper.Kpsi , limpropers[key].psi0 == improper.psi0 ); } } } } } } foreach (var improper in limpropers.Values) { HDebug.Assert(improper.atoms.Length == 4); //HDebug.Assert(improper.atoms[0].ID < improper.atoms[3].ID); impropers.Add(improper); improper.atoms[0].Impropers.Add(improper); improper.atoms[1].Impropers.Add(improper); improper.atoms[2].Impropers.Add(improper); improper.atoms[3].Impropers.Add(improper); } } // 1-4 interactions for (int i = 0; i < atoms.Count; i++) { HashSet <Atom> Inter14 = new HashSet <Atom>(); BuildInter1toN(atoms[i], 4, Inter14); // find all atoms for 1-4 interaction Inter14.Remove(atoms[i]); // remove self foreach (Atom atom in atoms[i].Inter123) { Inter14.Remove(atom); // remove all 1-2, 1-3 interactions } atoms[i].Inter14 = Inter14; } Nonbonded14s nonbonded14s = new Nonbonded14s(); nonbonded14s.Build(atoms); //// nonbondeds //// do not make this list in advance, because it depends on the atom positions //Nonbondeds nonbondeds = new Nonbondeds(); //nonbondeds.Build(atoms); //Universe univ = new Universe(); univ.pdb = pdb; univ.refs.Add("xyz", xyz); univ.refs.Add("prm", prm); univ.refs.Add("pdb", pdb); univ.atoms = atoms; univ.bonds = bonds; univ.angles = angles; univ.dihedrals = dihedrals; univ.impropers = impropers; //univ.nonbondeds = nonbondeds ; // do not make this list in advance, because it depends on the atom positions univ.nonbonded14s = nonbonded14s; HDebug.Assert(univ.Verify()); if (HDebug.False) { List <Tuple <double, string, Bond> > lbnds = new List <Tuple <double, string, Bond> >(); foreach (Bond bnd in bonds) { lbnds.Add(new Tuple <double, string, Bond>(bnd.Kb , bnd.atoms[0].AtomType + "-" + bnd.atoms[1].AtomType , bnd)); } lbnds = lbnds.HSelectByIndex(lbnds.HListItem1().HIdxSorted().Reverse().ToArray()).ToList(); double avgKb = lbnds.HListItem1().Average(); List <Tuple <double, string, Angle> > langs = new List <Tuple <double, string, Angle> >(); List <Tuple <double, string, Angle> > langubs = new List <Tuple <double, string, Angle> >(); foreach (Angle ang in angles) { langs.Add(new Tuple <double, string, Angle>(ang.Ktheta , ang.atoms[0].AtomType + "-" + ang.atoms[1].AtomType + "-" + ang.atoms[2].AtomType , ang)); if (ang.Kub != 0) { langubs.Add(new Tuple <double, string, Angle>(ang.Kub , ang.atoms[0].AtomType + "-" + ang.atoms[1].AtomType + "-" + ang.atoms[2].AtomType , ang)); } } langs = langs.HSelectByIndex(langs.HListItem1().HIdxSorted().Reverse().ToArray()).ToList(); langubs = langubs.HSelectByIndex(langubs.HListItem1().HIdxSorted().Reverse().ToArray()).ToList(); double avgKtheta = langs.HListItem1().Average(); double avgKub = langubs.HListItem1().Average(); List <Tuple <double, string, Improper> > limps = new List <Tuple <double, string, Improper> >(); foreach (Improper imp in impropers) { limps.Add(new Tuple <double, string, Improper>(imp.Kpsi , imp.atoms[0].AtomType + "-" + imp.atoms[1].AtomType + "-" + imp.atoms[2].AtomType + "-" + imp.atoms[3].AtomType , imp)); } limps = limps.HSelectByIndex(limps.HListItem1().HIdxSorted().Reverse().ToArray()).ToList(); double avgKpsi = limps.HListItem1().Average(); List <Tuple <double, string, Dihedral> > ldihs = new List <Tuple <double, string, Dihedral> >(); foreach (Dihedral dih in dihedrals) { ldihs.Add(new Tuple <double, string, Dihedral>(dih.Kchi , dih.atoms[0].AtomType + "-" + dih.atoms[1].AtomType + "-" + dih.atoms[2].AtomType + "-" + dih.atoms[3].AtomType , dih)); } ldihs = ldihs.HSelectByIndex(ldihs.HListItem1().HIdxSorted().Reverse().ToArray()).ToList(); double avgKchi = ldihs.HListItem1().Average(); } return(univ); }
public static IEnumerable <Universe.Nonbonded> ListTip3pTetraHBond (Universe.Atoms atoms , IList <Vector> coords , bool[] waters , KDTree.KDTree <Universe.Atom> kdtree_water , string[] options ) { double cutoff = 16; foreach (var option in options) { if (option.StartsWith("TIP3P:cutoff:")) { cutoff = double.Parse(option.Replace("TIP3P:cutoff:", "")); } } int numHydNbnd = 3; foreach (var option in options) { if (option.StartsWith("TIP3P:numHydNbnd:")) { numHydNbnd = int.Parse(option.Replace("TIP3P:numHydNbnd:", "")); } } bool bOxyOxyInter = true; foreach (var option in options) { if (option.StartsWith("TIP3P:bOxyOxyInter:")) { bOxyOxyInter = bool.Parse(option.Replace("TIP3P:bOxyOxyInter:", "")); } } bool bHydHydInter = false; foreach (var option in options) { if (option.StartsWith("TIP3P:bHydHydInter:")) { bHydHydInter = bool.Parse(option.Replace("TIP3P:bHydHydInter:", "")); } } // oxy-oxy interactions if (bOxyOxyInter) { foreach (var oxy1 in atoms) { if (waters[oxy1.ID] == false) { continue; } if (oxy1.AtomElem != "O") { continue; } foreach (var oxy2 in kdtree_water.nearest(coords[oxy1.ID], 100)) { if (oxy2 == oxy1) { continue; } if (oxy2.AtomElem != "O") { continue; } if (oxy2.Inter123.Contains(oxy1)) { continue; } if (oxy2.ID < oxy1.ID) { continue; } double dist = (coords[oxy1.ID] - coords[oxy2.ID]).Dist; if (dist > cutoff) { continue; } yield return(new Universe.Nonbonded(oxy1, oxy2)); } } } // hyd-hyd interactions if (bHydHydInter) { foreach (var hyd1 in atoms) { if (waters[hyd1.ID] == false) { continue; } if (hyd1.AtomElem != "H") { continue; } foreach (var hyd2 in kdtree_water.nearest(coords[hyd1.ID], 100)) { if (hyd2 == hyd1) { continue; } if (hyd2.AtomElem != "H") { continue; } if (hyd2.Inter123.Contains(hyd1)) { continue; } if (hyd2.ID < hyd1.ID) { continue; } double dist = (coords[hyd1.ID] - coords[hyd2.ID]).Dist; if (dist > cutoff) { continue; } yield return(new Universe.Nonbonded(hyd1, hyd2)); } } } // oxy-hyd interactions Dictionary <Universe.Atom, HashSet <Universe.Atom> > water_oxy2hyd = new Dictionary <Universe.Atom, HashSet <Universe.Atom> >(); for (int i = 0; i < waters.Length; i++) { if (waters[i] == false) { continue; } if (atoms[i].AtomElem != "O") { continue; } water_oxy2hyd.Add(atoms[i], new HashSet <Universe.Atom>()); } foreach (var hyd in atoms) { if (waters[hyd.ID] == false) { continue; } if (hyd.AtomElem != "H") { continue; } int count = 0; foreach (var oxy in kdtree_water.nearest(coords[hyd.ID], 100)) { if (oxy == hyd) { continue; } if (oxy.AtomElem != "O") { continue; } if (oxy.Inter123.Contains(hyd)) { continue; } double dist = (coords[hyd.ID] - coords[oxy.ID]).Dist; if (dist > cutoff) { continue; } water_oxy2hyd[oxy].Add(hyd); count++; if (count < numHydNbnd) { continue; } break; } } foreach (var oxy2hyd in water_oxy2hyd) { var oxy = oxy2hyd.Key; if (oxy2hyd.Value.Count < Math.Max(2, numHydNbnd)) { foreach (var hyd in kdtree_water.nearest(coords[oxy.ID], 100)) { if (oxy == hyd) { continue; } if (hyd.AtomElem != "H") { continue; } if (oxy.Inter123.Contains(hyd)) { continue; } double dist = (coords[hyd.ID] - coords[oxy.ID]).Dist; if (dist > cutoff) { continue; } oxy2hyd.Value.Add(hyd); if (oxy2hyd.Value.Count >= Math.Max(2, numHydNbnd)) { break; } } } foreach (var hyd in oxy2hyd.Value) { yield return(new Universe.Nonbonded(oxy, hyd)); } } }
/// <summary> /// Randomise the layout of points. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Click(object sender, RoutedEventArgs e) { // Create a new bitmap and set it as our canvas background. pBitmap = BitmapFactory.New((int)cnvPoints.ActualWidth, (int)cnvPoints.ActualHeight); var pBrush = new ImageBrush(); pBrush.ImageSource = pBitmap; cnvPoints.Background = pBrush; // Clear the bitmap to light blue. using (pBitmap.GetBitmapContext()) pBitmap.Clear(Colors.LightBlue); // Get the number we want to generate and update the UI. var iResult = 0; if (!int.TryParse(txtPoints.Text, out iResult)) { txtPoints.Foreground = Brushes.Red; return; } if (iResult < 0) { txtPoints.Foreground = Brushes.Red; return; } txtPoints.Foreground = Brushes.Black; // Clear the tree and canvas. cnvPoints.Children.Clear(); pTree = new KDTree.KDTree<EllipseWrapper>(2); // Create a list of points and draw a ghost ellipse for each one. using (pBitmap.GetBitmapContext()) { // Generate X new random items. var pRandom = new Random(); for (int i = 0; i < iResult; ++i) { // Position it and add it to the canvas. var x = pRandom.NextDouble() * cnvPoints.ActualWidth; var y = pRandom.NextDouble() * cnvPoints.ActualHeight; // Add it to the tree. pTree.AddPoint(new double[] { x, y }, new EllipseWrapper(x, y)); // Draw a ghost visual for it. //pBitmap.DrawEllipse((int)x - 2, (int)y - 2, (int)x + 2, (int)y + 2, Colors.Green); pBitmap.DrawEllipse((int)x - 2, (int)y - 2, (int)x + 2, (int)y + 2, Colors.Orange); } } }
public static void SelfTest(string pdbname, string psfname, string prmname, string xyzname) { using (var temp = new HTempDirectory(@"C:\temp\", null)) { temp.EnterTemp(); { string resbase = "HTLib2.Bioinfo.HTLib2.Bioinfo.External.Tinker.Resources.selftest."; HResource.CopyResourceTo <Tinker>(resbase + pdbname, pdbname); HResource.CopyResourceTo <Tinker>(resbase + psfname, psfname); HResource.CopyResourceTo <Tinker>(resbase + "par_all27_prot_lipid.inp", prmname); if (xyzname != null) { HResource.CopyResourceTo <Tinker>(resbase + xyzname, xyzname); } HResource.CopyResourceTo <Tinker>(resbase + "charmm22.prm", "charmm22.prm"); { var pdb = Pdb.FromFile(pdbname); var psf = Namd.Psf.FromFile(psfname); var prm = Namd.Prm.FromFile(prmname); var xyz_prm = BuildFromNamd(pdb, psf, prm); xyz_prm.Item1.ToFile("TinkFromNamd.xyz", false); xyz_prm.Item2.ToFile("TinkFromNamd.prm"); } if (xyzname != null) { var xyz0 = Xyz.FromFile("TinkFromNamd.xyz", false); var prm0 = Prm.FromFile("TinkFromNamd.prm"); var grad0 = Run.Testgrad(xyz0, prm0, @"C:\temp\" //, "VDWTERM NONE" //, "CHARGETERM NONE" //, "BONDTERM NONE" //, "ANGLETERM NONE" //, "UREYTERM NONE" //, "IMPROPTERM NONE" //, "TORSIONTERM NONE" ); var forc0 = grad0.anlyts.GetForces(xyz0.atoms); var xyz1 = Xyz.FromFile(xyzname, false); var prm1 = Prm.FromFile("charmm22.prm"); var grad1 = Run.Testgrad(xyz1, prm1, @"C:\temp\" //, "VDWTERM NONE" //, "CHARGETERM NONE" //, "BONDTERM NONE" //, "ANGLETERM NONE" //, "UREYTERM NONE" //, "IMPROPTERM NONE" //, "TORSIONTERM NONE" ); var forc1 = grad1.anlyts.GetForces(xyz1.atoms); { KDTree.KDTree <object> kdtree = new KDTree.KDTree <object>(3); var atoms0 = xyz0.atoms; for (int i = 0; i < atoms0.Length; i++) { kdtree.insert(atoms0[i].Coord, i); } var atoms1 = xyz1.atoms; int[] idx1to0 = new int[atoms1.Length]; for (int i1 = 0; i1 < atoms1.Length; i1++) { Vector coord1 = atoms1[i1].Coord; int i0 = (int)kdtree.nearest(coord1); Vector coord0 = atoms0[i0].Coord; kdtree.delete(coord0); idx1to0[i0] = i1; } atoms1 = atoms1.HSelectByIndex(idx1to0); forc1 = forc1.HSelectByIndex(idx1to0); } Vector[] dforc = VectorBlock.PwSub(forc0, forc1).ToArray(); double[] dforcl = dforc.Dist(); double max_dforc = dforc.Dist().Max(); HDebug.Exception(max_dforc < 1); // 0.72682794387667848 { double EB = Math.Abs(grad0.enrgCmpnt.EB - grad1.enrgCmpnt.EB); HDebug.Exception(EB < 0.1); double EA = Math.Abs(grad0.enrgCmpnt.EA - grad1.enrgCmpnt.EA); HDebug.Exception(EA < 0.1); double EBA = Math.Abs(grad0.enrgCmpnt.EBA - grad1.enrgCmpnt.EBA); HDebug.Exception(EBA < 0.1); double EUB = Math.Abs(grad0.enrgCmpnt.EUB - grad1.enrgCmpnt.EUB); HDebug.Exception(EUB < 0.1); double EAA = Math.Abs(grad0.enrgCmpnt.EAA - grad1.enrgCmpnt.EAA); HDebug.Exception(EAA < 0.1); double EOPB = Math.Abs(grad0.enrgCmpnt.EOPB - grad1.enrgCmpnt.EOPB); HDebug.Exception(EOPB < 0.1); double EOPD = Math.Abs(grad0.enrgCmpnt.EOPD - grad1.enrgCmpnt.EOPD); HDebug.Exception(EOPD < 0.1); double EID = Math.Abs(grad0.enrgCmpnt.EID - grad1.enrgCmpnt.EID); HDebug.Exception(EID < 0.1); // 0.0019000000000000128 : N-terminus (and C-terminus) information is/are inconsistent betweeen namd-charmm and tink-charmm22 double EIT = Math.Abs(grad0.enrgCmpnt.EIT - grad1.enrgCmpnt.EIT); HDebug.Exception(EIT < 0.1); double ET = Math.Abs(grad0.enrgCmpnt.ET - grad1.enrgCmpnt.ET); HDebug.Exception(ET < 0.5); // 0.33029999999999404 : N-terminus (and C-terminus) information is/are inconsistent betweeen namd-charmm and tink-charmm22 double EPT = Math.Abs(grad0.enrgCmpnt.EPT - grad1.enrgCmpnt.EPT); HDebug.Exception(EPT < 0.1); double EBT = Math.Abs(grad0.enrgCmpnt.EBT - grad1.enrgCmpnt.EBT); HDebug.Exception(EBT < 0.1); double ETT = Math.Abs(grad0.enrgCmpnt.ETT - grad1.enrgCmpnt.ETT); HDebug.Exception(ETT < 0.1); double EV = Math.Abs(grad0.enrgCmpnt.EV - grad1.enrgCmpnt.EV); HDebug.Exception(EV < 0.1); double EC = Math.Abs(grad0.enrgCmpnt.EC - grad1.enrgCmpnt.EC); HDebug.Exception(EC < 0.5); // 0.37830000000002428 double ECD = Math.Abs(grad0.enrgCmpnt.ECD - grad1.enrgCmpnt.ECD); HDebug.Exception(ECD < 0.1); double ED = Math.Abs(grad0.enrgCmpnt.ED - grad1.enrgCmpnt.ED); HDebug.Exception(ED < 0.1); double EM = Math.Abs(grad0.enrgCmpnt.EM - grad1.enrgCmpnt.EM); HDebug.Exception(EM < 0.1); double EP = Math.Abs(grad0.enrgCmpnt.EP - grad1.enrgCmpnt.EP); HDebug.Exception(EP < 0.1); double ER = Math.Abs(grad0.enrgCmpnt.ER - grad1.enrgCmpnt.ER); HDebug.Exception(ER < 0.1); double ES = Math.Abs(grad0.enrgCmpnt.ES - grad1.enrgCmpnt.ES); HDebug.Exception(ES < 0.1); double ELF = Math.Abs(grad0.enrgCmpnt.ELF - grad1.enrgCmpnt.ELF); HDebug.Exception(ELF < 0.1); double EG = Math.Abs(grad0.enrgCmpnt.EG - grad1.enrgCmpnt.EG); HDebug.Exception(EG < 0.1); double EX = Math.Abs(grad0.enrgCmpnt.EX - grad1.enrgCmpnt.EX); HDebug.Exception(EX < 0.1); } } } temp.QuitTemp(); } //{ // //string pathbase = @"C:\Users\htna.IASTATE\svn\htnasvn_htna\Research.bioinfo.prog.NAMD\1A6G\New folder\"; // string pathbase = @"C:\Users\htna.IASTATE\svn\htnasvn_htna\Research.bioinfo.prog.NAMD\1A6G\"; // string toplbase = @"C:\Users\htna.IASTATE\svn\htnasvn_htna\Research.bioinfo.prog.NAMD\top_all27_prot_lipid\"; // var pdb = Pdb .FromFile(pathbase+"1A6G.psfgen.pdb"); // var psf = Namd.Psf.FromFile(pathbase+"1A6G.psfgen.psf"); // var prm = Namd.Prm.FromFile(toplbase+"par_all27_prot_na.prm"); // // pdb = Pdb .FromFile(@"K:\Tim-8TIM,1TPH,1M6J\Tim-1M6J\1M6J.psfgen.pdb"); // psf = Namd.Psf.FromFile(@"K:\Tim-8TIM,1TPH,1M6J\Tim-1M6J\1M6J.psfgen.psf"); // prm = Namd.Prm.FromFile(@"K:\Tim-8TIM,1TPH,1M6J\Tim-1M6J\par_all27_prot_lipid.inp"); // var xyz_prm = BuildFromNamd(pdb, psf, prm); // xyz_prm.Item1.ToFile(@"C:\temp\TinkFromNamd.xyz", false); // xyz_prm.Item2.ToFile(@"C:\temp\TinkFromNamd.prm"); //} }