id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
755,088
|
snapShotContainer.inline.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/sse4/snapShotContainer.inline.hpp
|
/*!
* \file snapshotContainer.inline.hpp
* \brief This file is used to add up using size every class.
* This source is optimized for SSE4 instruction set.
* Copyright (C) 2014 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef SSE4_SNAPSHOT_CONTAINER_INLINE_HPP
#define SSE4_SNAPSHOT_CONTAINER_INLINE_HPP
/*!
* \brief Increment instance count and using size.
* \param counter [in] Increment target class.
* \param operand [in] Right-hand operand (SRC operand).
* This value must be aligned 16bytes.
*/
inline void TSnapShotContainer::addInc(TObjectCounter *counter,
TObjectCounter *operand) {
asm volatile(
"movntdqa (%1), %%xmm0;"
"paddq (%0), %%xmm0;"
"movdqa %%xmm0, (%0);"
:
: "r"(counter), "r"(operand)
: "%xmm0"
);
}
/* Include other optimized inline functions from SSE2. */
#include "arch/x86/sse2/snapShotContainer.inline.hpp"
#endif // SSE4_SNAPSHOT_CONTAINER_INLINE_HPP
| 1,691
|
C++
|
.h
| 43
| 36.093023
| 82
| 0.709854
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,089
|
jvmInfo.inline.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/avx/jvmInfo.inline.hpp
|
/*!
* \file jvmInfo.inline.hpp
* \brief Getting JVM performance information.
* This source is optimized for AVX instruction set.
* Copyright (C) 2014 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef AVX_JVMINFO_INLINE_H
#define AVX_JVMINFO_INLINE_H
/*!
* \brief memcpy for gccause
*/
inline void TJvmInfo::loadGCCause(void) {
/* Strcpy with AVX (80 bytes).
* Sandy Bridge can two load operations per cycle.
* So we should execute sequentially 2-load / 1-store ops.
* Intel 64 and IA-32 Architectures Optimization Reference Manual
* 3.6.1.1 Make Use of Load Bandwidth in Intel Microarchitecture
* Code Name Sandy Bridge
*/
asm volatile(
"vmovdqu (%0), %%ymm0;"
"vmovdqu 32(%0), %%ymm1;"
"vmovdqa %%ymm0, (%1);"
"vmovdqu 64(%0), %%xmm0;"
"vmovdqa %%ymm1, 32(%1);"
"vmovdqa %%xmm0, 64(%1);"
:
: "d"(this->_gcCause), /* GC Cause address. */
"c"(this->gcCause) /* GC Cause container. */
: "cc", "%xmm0" /*, "%ymm0", "%ymm1" */
);
}
/*!
* \brief Set "Unknown GCCause" to gccause.
*/
inline void TJvmInfo::SetUnknownGCCause(void) {
asm volatile(
"vmovdqa (%1), %%xmm0;"
"vmovdqa %%xmm0, (%0);"
:
: "a"(this->gcCause), "c"(UNKNOWN_GC_CAUSE)
: "%xmm0"
);
}
#endif // AVX_JVMINFO_INLINE_H
| 2,024
|
C++
|
.h
| 60
| 30.766667
| 82
| 0.669388
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,090
|
snapShotContainer.inline.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/avx/snapShotContainer.inline.hpp
|
/*!
* \file snapShotContainer.inline.hpp
* \brief This file is used to add up using size every class.
* This source is optimized for AVX instruction set.
* Copyright (C) 2014 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef AVX_SNAPSHOTCONTAINER_INLINE_H
#define AVX_SNAPSHOTCONTAINER_INLINE_H
/*!
* \brief Increment instance count and using size.
* \param counter [in] Increment target class.
* \param operand [in] Right-hand operand (SRC operand).
* This value must be aligned 16bytes.
*/
inline void TSnapShotContainer::addInc(TObjectCounter *counter,
TObjectCounter *operand) {
asm volatile(
"vmovntdqa (%1), %%xmm0;"
"vpaddq (%0), %%xmm0, %%xmm0;"
"vmovdqa %%xmm0, (%0);"
:
: "r"(counter), "r"(operand)
: "%xmm0"
);
}
/*!
* \brief Zero clear to TObjectCounter.
* \param counter TObjectCounter to clear.
*/
inline void TSnapShotContainer::clearObjectCounter(TObjectCounter *counter) {
asm volatile(
"vpxor %%xmm0, %%xmm0, %%xmm0;"
"vmovdqa %%xmm0, (%0);"
:
: "r"(counter)
: "%xmm0"
);
}
/*!
* \brief Zero clear to TClassCounter and its children counter.
* \param counter TClassCounter to clear.
*/
inline void TSnapShotContainer::clearChildClassCounters(
TClassCounter *counter) {
#ifdef __amd64__
asm volatile(
"vpxor %%xmm0, %%xmm0, %%xmm0;"
"movq 8(%0), %%rax;" /* clsCounter->child */
".align 16;"
"1:"
" testq %%rax, %%rax;"
" jz 2f;"
" movq (%%rax), %%rbx;" /* child->counter */
" vmovdqa %%xmm0, (%%rbx);"
" movq 16(%%rax), %%rax;" /* child->next */
" jmp 1b;"
"2:"
" movq (%0), %%rbx;" /* clsCounter->counter */
" vmovdqa %%xmm0, (%%rbx);"
:
: "r"(counter)
: "%xmm0", "%rax", "%rbx", "cc"
);
#else // i386
asm volatile(
"vpxor %%xmm0, %%xmm0, %%xmm0;"
"movl 4(%0), %%eax;" /* clsCounter->child */
".align 16;"
"1:"
" testl %%eax, %%eax;"
" jz 2f;"
" movl (%%eax), %%ecx;" /* child->counter */
" vmovdqa %%xmm0, (%%ecx);"
" movl 8(%%eax), %%eax;" /* child->next */
" jmp 1b;"
"2:"
" movl (%0), %%ecx;" /* clsCounter->counter */
" vmovdqa %%xmm0, (%%ecx);"
:
: "r"(counter)
: "%xmm0", "%eax", "%ecx", "cc"
);
#endif
}
#endif // AVX_SNAPSHOTCONTAINER_INLINE_H
| 3,142
|
C++
|
.h
| 100
| 27.73
| 82
| 0.601977
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,091
|
avxBitMapMarker.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/avx/avxBitMapMarker.hpp
|
/*!
* \file avxBitMapMarker.hpp
* \brief Storeing and Controlling G1 marking bitmap.
* This source is optimized for AVX instruction set.
* Copyright (C) 2014-2016 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _AVXBITMAPMARKER_HPP
#define _AVXBITMAPMARKER_HPP
#include "arch/x86/sse2/sse2BitMapMarker.hpp"
/*!
* \brief This class is stored bit express flag in pointer range AVX version.
*/
class TAVXBitMapMarker : public TSSE2BitMapMarker {
public:
/*!
* \brief TAVXBitMapMarker constructor.
* \param startAddr [in] Start address of Java heap.
* \param size [in] Max Java heap size.
*/
TAVXBitMapMarker(const void *startAddr, const size_t size)
: TSSE2BitMapMarker(startAddr, size){};
/*!
* \brief TAVXBitMapMarker destructor.
*/
virtual ~TAVXBitMapMarker(){};
/*!
* \brief Clear bitmap flag.
*/
virtual void clear(void);
};
#endif // _AVXBITMAPMARKER_HPP
| 1,632
|
C++
|
.h
| 46
| 32.934783
| 82
| 0.738608
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,092
|
util.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/x86/avx/util.hpp
|
/*!
* \file util.hpp
* \brief Optimized utility functions for AVX instruction set.
* Copyright (C) 2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef AVX_UTIL_H
#define AVX_UTIL_H
inline void memcpy32(void *dest, const void *src) {
asm volatile(
"vmovdqa (%1), %%ymm0;"
"vmovdqa %%ymm0, (%0);"
:
: "r"(dest), "r"(src)
: /* "%ymm0" */
);
}
#endif // AVX_UTIL_H
| 1,129
|
C++
|
.h
| 32
| 32.84375
| 82
| 0.715722
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,093
|
armBitMapMarker.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/arm/armBitMapMarker.hpp
|
/*!
* \file armBitMapMarker.hpp
* \brief This file is used to store and control of bit map.
* Copyright (C) 2015-2016 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef ARMBITMAPMARKER_HPP
#define ARMBITMAPMARKER_HPP
#include <stddef.h>
#include "../../bitMapMarker.hpp"
/*!
* \brief This class is stored bit express flag in pointer range.
*/
class TARMBitMapMarker : public TBitMapMarker {
public:
/*!
* \brief TBitMapMarker constructor.
* \param startAddr [in] Start address of Java heap.
* \param size [in] Max Java heap size.
*/
TARMBitMapMarker(const void *startAddr, const size_t size)
: TBitMapMarker(startAddr, size){};
/*!
* \brief TBitMapMarker destructor.
*/
virtual ~TARMBitMapMarker(){};
/*!
* \brief Mark GC-marked address in this bitmap.
* \param addr [in] Oop address.
*/
virtual void setMark(const void *addr);
/*!
* \brief Check address which is already marked and set mark.
* \param addr [in] Oop address.
* \return Designated pointer is marked.
*/
virtual bool checkAndMark(const void *addr);
};
#endif // ARMBITMAPMARKER_HPP
| 1,830
|
C++
|
.h
| 53
| 31.811321
| 82
| 0.726964
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,094
|
snapShotContainer.inline.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/arm/snapShotContainer.inline.hpp
|
/*!
* \file snapShotContainer.inline.hpp
* \brief This file is used to add up using size every class.
* Copyright (C) 2015 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef SNAPSHOTCONTAINER_INLINE_HPP
#define SNAPSHOTCONTAINER_INLINE_HPP
/*!
* \brief Increment instance count and using size.
* \param counter [in] Increment target class.
* \param size [in] Increment object size.
*/
inline void TSnapShotContainer::Inc(TObjectCounter *counter, jlong size) {
#ifdef WORDS_BIGENDIAN
asm volatile(
"1:"
" ldrex %%r0, [%0, #4];"
" adds %%r0, %%r0, #1;"
" strex %%r1, %%r0, [%r0, #4];"
" tst %%r1, %%r1;"
" bne 1b;"
"2:"
" ldrex %%r0, [%0];"
" adc %%r0, %%r0, #0;"
" strex %%r1, %%r0, [%0];"
" tst %%r1, %%r1;"
" bne 2b;"
:
: "r"(&counter->count)
: "cc", "memory", "%r0", "%r1"
);
asm volatile(
"ldr %%r2, [%1, #4];"
"1:"
" ldrex %%r0, [%0, #4];"
" adds %%r0, %%r0, %%r2;"
" strex %%r1, %%r0, [%r0, #4];"
" tst %%r1, %%r1;"
" bne 1b;"
"ldr %%r2, [%1];"
"2:"
" ldrex %%r0, [%0];"
" adc %%r0, %%r0, %%r2;"
" strex %%r1, %%r0, [%0];"
" tst %%r1, %%r1;"
" bne 2b;"
:
: "r"(&counter->count), "r"(&counter->total_size)
: "cc", "memory", "%r0", "%r1", "%r2"
);
#else
asm volatile(
"1:"
" ldrex %%r0, [%0];"
" adds %%r0, %%r0, #1;"
" strex %%r1, %%r0, [%r0];"
" tst %%r1, %%r1;"
" bne 1b;"
"2:"
" ldrex %%r0, [%0, #4];"
" adc %%r0, %%r0, #0;"
" strex %%r1, %%r0, [%0, #4];"
" tst %%r1, %%r1;"
" bne 2b;"
:
: "r"(&counter->count)
: "cc", "memory", "%r0", "%r1"
);
asm volatile(
"ldr %%r2, [%1];"
"1:"
" ldrex %%r0, [%0];"
" adds %%r0, %%r0, %%r2;"
" strex %%r1, %%r0, [%r0];"
" tst %%r1, %%r1;"
" bne 1b;"
"ldr %%r2, [%1, #4];"
"2:"
" ldrex %%r0, [%0, #4];"
" adc %%r0, %%r0, %%r2;"
" strex %%r1, %%r0, [%0, #4];"
" tst %%r1, %%r1;"
" bne 2b;"
:
: "r"(&counter->count), "r"(&counter->total_size)
: "cc", "memory", "%r0", "%r1", "%r2"
);
#endif
}
#endif // SNAPSHOTCONTAINER_INLINE_HPP
| 2,964
|
C++
|
.h
| 105
| 24.371429
| 82
| 0.516468
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,095
|
lock.inline.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/arm/lock.inline.hpp
|
/*!
* \file lock.inline.hpp
* \brief This file defines spinlock functions.
* Copyright (C) 2015 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef LOCK_INLINE_HPP
#define LOCK_INLINE_HPP
#include <sched.h>
/*!
* \brief Wait spin lock.
* \param aLock [in] Target integer lock.
*/
inline void spinLockWait(volatile int *aLock) {
asm volatile(
"1:"
" ldrex %%r0, [%0];"
" tst %%r0, %%r0;"
" strexeq %%r0, %1, [%0];"
" tsteq %%r0, %%r0;"
" bne 1b;"
:
: "r"(aLock), "r"(1)
: "cc", "memory", "%r0"
);
};
/*!
* \brief Release spin lock.
* \param aLock [in] Target integer lock.
*/
inline void spinLockRelease(volatile int *aLock) {
asm volatile(
"1:"
" ldrex %%r0, [%0];"
" strex %%r0, %1, [%0];"
" tst %%r0, %%r0;"
" bne 1b;"
:
: "r"(aLock), "r"(0)
: "cc", "memory", "%r0"
);
};
#endif // LOCK_INLINE_HPP
| 1,624
|
C++
|
.h
| 57
| 25.631579
| 82
| 0.638924
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,096
|
jvmInfo.inline.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/arm/neon/jvmInfo.inline.hpp
|
/*!
* \file jvmInfo.inline.hpp
* \brief This file is used to get JVM performance information.
* This source is optimized for NEON instruction set.
* Copyright (C) 2015 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef NEON_JVMINFO_INLINE_H
#define NEON_JVMINFO_INLINE_H
/*!
* \brief memcpy for gccause
*/
inline void TJvmInfo::loadGCCause(void) {
/* Strcpy with NEON (80 bytes). */
asm volatile(
"vld1.8 {%%q0}, [%0]!;"
"vld1.8 {%%q1}, [%0]!;"
"vld1.8 {%%q2}, [%0]!;"
"vld1.8 {%%q3}, [%0]!;"
"vld1.8 {%%q4}, [%0];"
"vst1.8 {%%q0}, [%1]!;"
"vst1.8 {%%q1}, [%1]!;"
"vst1.8 {%%q2}, [%1]!;"
"vst1.8 {%%q3}, [%1]!;"
"vst1.8 {%%q4}, [%1];"
:
: "r"(this->_gcCause), /* GC Cause address. */
"r"(this->gcCause) /* GC Cause container. */
: "cc", "%q0", "%q1", "%q2", "%q3", "q4"
);
}
/*!
* \brief Set "Unknown GCCause" to gccause.
*/
inline void TJvmInfo::SetUnknownGCCause(void) {
asm volatile(
"vld1.8 {%%q0}, [%1];"
"vst1.8 {%%q0}, [%0];"
:
: "r"(this->gcCause), "r"(UNKNOWN_GC_CAUSE)
: "%q0"
);
}
#endif // NEON_JVMINFO_INLINE_H
| 1,840
|
C++
|
.h
| 58
| 28.724138
| 82
| 0.625422
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,097
|
snapShotContainer.inline.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/arm/neon/snapShotContainer.inline.hpp
|
/*!
* \file snapShotContainer.inline.hpp
* \brief This file is used to add up using size every class.
* This source is optimized for NEON instruction set.
* Copyright (C) 2015 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef NEON_SNAPSHOTCONTAINER_INLINE_H
#define NEON_SNAPSHOTCONTAINER_INLINE_H
/*!
* \brief Increment instance count and using size.
* \param counter [in] Increment target class.
* \param operand [in] Right-hand operand (SRC operand).
*/
inline void TSnapShotContainer::addInc(TObjectCounter *counter,
TObjectCounter *operand) {
asm volatile(
"vld1.8 {%%q0}, [%1];"
"vld1.8 {%%q1}, [%0];"
"vadd.I64 %%q2, %%q0, %%q1;"
"vst1.8 {%%q2}, [%0];"
:
: "r"(counter), "r"(operand)
: "%q0", "%q1", "%q2"
);
}
/*!
* \brief Zero clear to TObjectCounter.
* \param counter TObjectCounter to clear.
*/
inline void TSnapShotContainer::clearObjectCounter(TObjectCounter *counter) {
asm volatile(
"vbic.I64 %%q0, %%q0, %%q0;"
"vst1.8 {%%q0}, [%0];"
:
: "r"(counter)
: "%q0"
);
}
/*!
* \brief Zero clear to TClassCounter and its children counter.
* \param counter TClassCounter to clear.
*/
inline void TSnapShotContainer::clearChildClassCounters(
TClassCounter *counter) {
asm volatile(
"vbic.I64 %%q0, %%q0, %%q0;"
"ldr %%r0, [%0, #4];" /* clsCounter->child */
"1:"
" tst %%r0, %%r0;"
" beq 2f;"
" ldr %%r1, [%%r0];" /* child->counter */
" vst1.8 {%%q0}, [%%r1];"
" ldr %%r0, [%%r0, #8];" /* child->next */
" b 1b;"
"2:"
" ldr %%r0, [%0];" /* clsCounter->counter */
" vst1.8 {%%q0}, [%%r0];"
:
: "r"(counter)
: "cc", "%q0", "%r0", "%r1"
);
}
#endif // NEON_SNAPSHOTCONTAINER_INLINE_H
| 2,531
|
C++
|
.h
| 78
| 28.910256
| 82
| 0.625
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,098
|
neonBitMapMarker.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/arm/neon/neonBitMapMarker.hpp
|
/*!
* \file neonBitMapMarker.hpp
* \brief Storeing and Controlling G1 marking bitmap.
* This source is optimized for NEON instruction set.
* Copyright (C) 2015-2016 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef _NEONBITMAPMARKER_HPP
#define _NEONBITMAPMARKER_HPP
#include "arch/arm/armBitMapMarker.hpp"
/*!
* \brief This class is stored bit express flag in pointer range NEON version.
*/
class TNeonBitMapMarker : public TARMBitMapMarker {
public:
/*!
* \brief TNeonBitMapMarker constructor.
* \param startAddr [in] Start address of Java heap.
* \param size [in] Max Java heap size.
*/
TNeonBitMapMarker(const void *startAddr, const size_t size)
: TARMBitMapMarker(startAddr, size){};
/*!
* \brief TNeonBitMapMarker destructor.
*/
virtual ~TNeonBitMapMarker(){};
/*!
* \brief Clear bitmap flag.
*/
virtual void clear(void);
};
#endif // _NEONBITMAPMARKER_HPP
| 1,635
|
C++
|
.h
| 46
| 33
| 82
| 0.739735
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,099
|
util.hpp
|
HeapStats_heapstats/agent/src/heapstats-engines/arch/arm/neon/util.hpp
|
/*!
* \file util.hpp
* \brief Optimized utility functions for NEON instruction set.
* Copyright (C) 2015 Nippon Telegraph and Telephone Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef NEON_UTIL_H
#define NEON_UTIL_H
inline void memcpy32(void *dest, const void *src) {
asm volatile(
"vld1.8 {%%q0}, [%1]!;"
"vld1.8 {%%q1}, [%1];"
"vst1.8 {%%q0}, [%0]!;"
"vst1.8 {%%q1}, [%0];"
:
: "r"(dest), "r"(src)
: "cc", "%q0", "%q1"
);
}
#endif // NEON_UTIL_H
| 1,188
|
C++
|
.h
| 34
| 32.352941
| 82
| 0.692441
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,100
|
heapstats_md_x86.hpp
|
HeapStats_heapstats/agent/src/arch/x86/heapstats_md_x86.hpp
|
/*!
* \file heapstats_md_x86.hpp
* \brief Proxy library for HeapStats backend.
* This file implements x86 specific code for loading backend library.
* Copyright (C) 2014-2016 Yasumasa Suenaga
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef HEAPSTATS_MD_X86_HPP
#define HEAPSTATS_MD_X86_HPP
#include "heapstats_md.hpp"
/* Instruction set definition */
#define OPTIMIZE_NONE "none"
#define OPTIMIZE_SSE2 "sse2"
#define OPTIMIZE_SSE4 "sse4"
#define OPTIMIZE_AVX "avx"
#endif // HEAPSTATS_MD_X86_HPP
| 1,201
|
C++
|
.h
| 30
| 38.233333
| 82
| 0.761782
|
HeapStats/heapstats
| 128
| 18
| 1
|
GPL-2.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,101
|
test_mmcif.cpp
|
GrossfieldLab_loos/Packages/User/test_mmcif.cpp
|
#include <loos.hpp>
#include <gemmi/mmread.hpp>
#include <gemmi/cif.hpp>
#include <gemmi/mmcif.hpp> // cif::Document -> Structure
#include <gemmi/gz.hpp>
namespace cif = gemmi::cif;
int main(int argc, char *argv[]) {
std::string filename = std::string(argv[1]);
loos::AtomicGroup ag;
auto structure = gemmi::read_structure_file(filename, gemmi::CoorFormat::Mmcif);
auto unit_cell = structure.cell;
auto box = loos::GCoord(unit_cell.a, unit_cell.b, unit_cell.c);
ag.periodicBox(box);
// TODO: hard-wired to read first model, but there should probably be a way to read others
auto model = structure.first_model();
int atom_index = 0;
int residue_number = 1;
for (auto chain:model.chains) {
std::string chain_name = chain.name;
for (auto residue:chain.residues) {
std::string residue_name = residue.name;
auto label_seq = residue.label_seq;
std::string res_entity_id = residue.entity_id;
std::cout << "Residue: "
<< residue_number << "\t"
<< label_seq.str() << "\t"
<< res_entity_id << "\t"
<< residue.name << "\t"
<< residue.seqid.num.value << "\t"
<< std::endl;
for (auto atom:residue.atoms) {
loos::pAtom pa(new loos::Atom);
pa->index(atom.serial);
pa->id(atom_index);
pa->name(atom.name);
pa->PDBelement(atom.element.name());
pa->coords().x(atom.pos.x);
pa->coords().y(atom.pos.y);
pa->coords().z(atom.pos.z);
pa->resid(residue.seqid.num.value);
pa->chainId(chain_name);
// might as well fill in segid, even though it's not official
pa->segid(chain_name);
pa->resname(residue.name);
std::cout << atom.name << "\t"
<< atom.element.name() << "\t"
<< atom.pos.x << "\t"
<< atom.pos.y << "\t"
<< atom.pos.z << std::endl;
// TODO: charge is a char*, looks like it's usually "?" in actual
// mmCIF files. Perhaps a try/catch block to convert to float?
// TODO: since I've got the element, in principle I can look up the
// mass and atomic number, but doing so will require some changes to
// AtomicNumberDeducer
ag.append(pa);
atom_index++;
}
residue_number++;
}
}
std::cout << ag << std::endl;
}
| 2,761
|
C++
|
.cpp
| 62
| 31.467742
| 94
| 0.505404
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
755,102
|
traj_calc.cpp
|
GrossfieldLab_loos/Packages/User/traj_calc.cpp
|
/*
traj_calc.cpp
(c) 2011 Tod D. Romo, Grossfield Lab
Department of Biochemistry
University of Rochster School of Medicine and Dentistry
C++ template for writing a tool that performs a calculation on a trajectory
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2011 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// ----------------------------------------------------------------
// ***EDIT***
// The following code is for implementing tool-specific
// options if the tool requires them. If not, this section can be
// deleted.
double option1;
int option2;
// The following conditional prevents this class from appearing in the
// Doxygen documentation for LOOS:
//
// @cond TOOLS_INTERNAL
class ToolOptions : public opts::OptionsPackage {
public:
// Change these options to reflect what your tool needs
void addGeneric(po::options_description& o) {
o.add_options()
("option1", po::value<double>(&option1)->default_value(0.0), "Tool Option #1")
("option2", po::value<int>(&option2)->default_value(42), "Tool option #2");
}
// The print() function returns a string that describes what all the
// options are set to (for logging purposes)
string print() const {
ostringstream oss;
oss << boost::format("option1=%f, option2=%d") % option1 % option2;
return(oss.str());
}
};
// @endcond
// ----------------------------------------------------------------
// ***EDIT***
void calculate(const AtomicGroup& structure) {
// Do something here with an atom...
}
int main(int argc, char *argv[]) {
// Store the invocation information for logging later
string header = invocationHeader(argc, argv);
// Build up the command-line options for this tool by instantiating
// the appropriate OptionsPackage objects...
// Basic options should be used by all tools. It provides help,
// verbosity, and the ability to read options from a config file
opts::BasicOptions* bopts = new opts::BasicOptions;
// This tool can operate on a subset of atoms. The BasicSelection
// object provides the "--selection" option.
opts::BasicSelection* sopts = new opts::BasicSelection;
// The BasicTrajectory object handles specifying a trajectory as
// well as a "--skip" option that lets the tool skip the first
// number of frames (i.e. equilibration). It creates a pTraj object
// that is already primed for reading...
opts::BasicTrajectory* tropts = new opts::BasicTrajectory;
// ***EDIT***
// Tool-specific options can be included here...
ToolOptions* topts = new ToolOptions;
// ***EDIT***
// All of the OptionsPackages are combined via the AggregateOptions
// object. First instantiate it, then add the desired
// OptionsPackage objects. The order is important. We recommend
// you progress from general (Basic and Selection) to more specific
// (model) and finally the tool options.
opts::AggregateOptions options;
options.add(bopts).add(sopts).add(tropts).add(topts);
// Parse the command-line. If an error occurred, help will already
// be displayed and it will return a FALSE value.
if (!options.parse(argc, argv))
exit(-1);
// Pull the model from the options object (it will include coordinates)
AtomicGroup model = tropts->model;
// Pull out the trajectory...
pTraj traj = tropts->trajectory;
// Select the desired atoms to operate over...
AtomicGroup subset = selectAtoms(model, sopts->selection);
// Now iterate over all frames in the trajectory (excluding the skip
// region)
while (traj->readFrame()) {
// Update the coordinates ONLY for the subset of atoms we're
// interested in...
traj->updateGroupCoords(subset);
// ***EDIT***
// Now calculate something with the AtomicGroup
calculate(subset);
}
// ***EDIT***
// Output results...
}
| 4,728
|
C++
|
.cpp
| 111
| 39.234234
| 84
| 0.710624
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,103
|
model_calc.cpp
|
GrossfieldLab_loos/Packages/User/model_calc.cpp
|
/*
model_calc.cpp
(c) 2011 Tod D. Romo, Grossfield Lab
Department of Biochemistry
University of Rochster School of Medicine and Dentistry
C++ template for writing a tool that performs a calculation on a model
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2011 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// ----------------------------------------------------------------
// ***EDIT***
// The following code is for implementing tool-specific
// options if the tool requires them. If not, this section can be
// deleted.
double option1;
int option2;
// The following conditional prevents this class from appearing in the
// Doxygen documentation for LOOS:
//
// @cond TOOLS_INTERNAL
class ToolOptions : public opts::OptionsPackage {
public:
// Change these options to reflect what your tool needs
void addGeneric(po::options_description& o) {
o.add_options()
("option1", po::value<double>(&option1)->default_value(0.0), "Tool Option #1")
("option2", po::value<int>(&option2)->default_value(42), "Tool option #2");
}
// The print() function returns a string that describes what all the
// options are set to (for logging purposes)
string print() const {
ostringstream oss;
oss << boost::format("option1=%f, option2=%d") % option1 % option2;
return(oss.str());
}
};
// @endcond
// ----------------------------------------------------------------
int main(int argc, char *argv[]) {
// Store the invocation information for logging later
string header = invocationHeader(argc, argv);
// Build up the command-line options for this tool by instantiating
// the appropriate OptionsPackage objects...
// Basic options should be used by all tools. It provides help,
// verbosity, and the ability to read options from a config file
opts::BasicOptions* bopts = new opts::BasicOptions;
// This tool can operate on a subset of atoms. The BasicSelection
// object provides the "--selection" option.
opts::BasicSelection* sopts = new opts::BasicSelection;
// ModelWithCoords handles reading in a model and optionally drawing
// the coordinates from another file (for example, using a PSF file
// with a PDB)
opts::ModelWithCoords* mopts = new opts::ModelWithCoords;
// ***EDIT***
// Tool-specific options can be included here...
ToolOptions* topts = new ToolOptions;
// ***EDIT***
// All of the OptionsPackages are combined via the AggregateOptions
// object. First instantiate it, then add the desired
// OptionsPackage objects. The order is important. We recommend
// you progress from general (Basic and Selection) to more specific
// (model) and finally the tool options.
opts::AggregateOptions options;
options.add(bopts).add(sopts).add(mopts).add(topts);
// Parse the command-line. If an error occurred, help will already
// be displayed and it will return a FALSE value.
if (!options.parse(argc, argv))
exit(-1);
// Pull the model from the options object (it will include coordinates)
AtomicGroup model = mopts->model;
// Select the desired atoms to operate over...
AtomicGroup subset = selectAtoms(model, sopts->selection);
// ***EDIT***
// Now iterate over all atoms in the subset and perform some
// computation...
for (AtomicGroup::iterator atom = subset.begin(); atom != subset.end(); ++atom) {
// Perform some calculation...
// calculateSomething(*atom)
}
// ***EDIT***
// output results
}
| 4,371
|
C++
|
.cpp
| 101
| 39.980198
| 84
| 0.710601
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,104
|
traj_transform.cpp
|
GrossfieldLab_loos/Packages/User/traj_transform.cpp
|
/*
traj_transform.cpp
(c) 2011 Tod D. Romo, Grossfield Lab
Department of Biochemistry
University of Rochster School of Medicine and Dentistry
C++ template for writing a tool that transforms a subset of a trajectory
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2011 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// ----------------------------------------------------------------
// ***EDIT***
// The following code is for implementing tool-specific
// options if the tool requires them. If not, this section can be
// deleted.
double option1;
int option2;
// The following conditional prevents this class from appearing in the
// Doxygen documentation for LOOS:
//
// @cond TOOLS_INTERNAL
class ToolOptions : public opts::OptionsPackage {
public:
// Change these options to reflect what your tool needs
void addGeneric(po::options_description& o) {
o.add_options()
("option1", po::value<double>(&option1)->default_value(0.0), "Tool Option #1")
("option2", po::value<int>(&option2)->default_value(42), "Tool option #2");
}
// The print() function returns a string that describes what all the
// options are set to (for logging purposes)
string print() const {
ostringstream oss;
oss << boost::format("option1=%f, option2=%d") % option1 % option2;
return(oss.str());
}
};
// @endcond
// ----------------------------------------------------------------
int main(int argc, char *argv[]) {
// Store the invocation information for logging later
string header = invocationHeader(argc, argv);
// Build up the command-line options for this tool by instantiating
// the appropriate OptionsPackage objects...
// Basic options should be used by all tools. It provides help,
// verbosity, and the ability to read options from a config file
opts::BasicOptions* bopts = new opts::BasicOptions;
// Require an output prefix
opts::OutputPrefix* oopts = new opts::OutputPrefix;
// This tool can operate on a subset of atoms. The BasicSelection
// object provides the "--selection" option.
opts::BasicSelection* sopts = new opts::BasicSelection;
// The BasicTrajectory object handles specifying a trajectory as
// well as a "--skip" option that lets the tool skip the first
// number of frames (i.e. equilibration). It creates a pTraj object
// that is already primed for reading...
opts::BasicTrajectory* tropts = new opts::BasicTrajectory;
// ***EDIT***
// Tool-specific options can be included here...
ToolOptions* topts = new ToolOptions;
// ***EDIT***
// All of the OptionsPackages are combined via the AggregateOptions
// object. First instantiate it, then add the desired
// OptionsPackage objects. The order is important. We recommend
// you progress from general (Basic and Selection) to more specific
// (model) and finally the tool options.
opts::AggregateOptions options;
options.add(bopts).add(oopts).add(sopts).add(tropts).add(topts);
// Parse the command-line. If an error occurred, help will already
// be displayed and it will return a FALSE value.
if (!options.parse(argc, argv))
exit(-1);
// Pull the model from the options object (it will include coordinates)
AtomicGroup model = tropts->model;
// Pull out the trajectory...
pTraj traj = tropts->trajectory;
// Select the desired atoms to operate over...
AtomicGroup subset = selectAtoms(model, sopts->selection);
// Extract the output prefix
string prefix = oopts->prefix;
// Set-up the DCD writer
DCDWriter outdcd(prefix + ".dcd");
// Now iterate over all frames in the trajectory (excluding the skip
// region).
// Track whether we're on the first frame or not, for generating a
// PDB that corresponds to this trajectory...
bool first_frame = true;
while (traj->readFrame()) {
// Update the coordinates ONLY for the subset of atoms we're
// interested in...
traj->updateGroupCoords(subset);
// ***EDIT***
// Perform some transformation here
// Write out the frame to the DCD
outdcd.writeFrame(subset);
// If this is the first frame, then also write it out as a PDB
if (first_frame) {
first_frame = false;
// Note: the atomids must be renumbered to be sequential. This
// can also break connectivity, so we prune the connectivity
// first, then renumber. We also work with a *copy* of the
// subset so that we don't alter the one used for reading in the
// trajectory.
AtomicGroup frame_copy = subset.copy();
frame_copy.pruneBonds();
frame_copy.renumber();
// Now convert to a PDB
PDB pdb = PDB::fromAtomicGroup(frame_copy);
pdb.remarks().add(header);
string output_pdbname = prefix + ".pdb";
ofstream ofs(output_pdbname.c_str());
if (!ofs) {
cerr << "Error: unable to open output file for PDB\n";
exit(-10);
}
ofs << pdb;
}
}
}
| 5,853
|
C++
|
.cpp
| 137
| 38.686131
| 84
| 0.698604
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,105
|
simple_model_transform.cpp
|
GrossfieldLab_loos/Packages/User/simple_model_transform.cpp
|
/*
simple_model_transform.cpp
(c) 2011 Tod D. Romo, Grossfield Lab
Department of Biochemistry
University of Rochster School of Medicine and Dentistry
C++ template for writing a tool that transforms a model, writing it
out as a PDB to stdout
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2011 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
int main(int argc, char *argv[]) {
// How the tool was invoked, for logging purposes...
string header = invocationHeader(argc, argv);
// **EDIT***
// Verify correct number of command-line arguments
if (argc != 3) {
cerr << "Usage- simple_model_transform model-name selection\n";
}
// Handle command-line arguments
int arg_index = 1;
// Read in the model
AtomicGroup model = createSystem(argv[arg_index++]);
// Select a subset of it
AtomicGroup subset = selectAtoms(model, argv[arg_index++]);
// Prune the bonds-list (if present)
subset.pruneBonds();
// ***EDIT***
// Iterate over all atoms in the subset, performing some computation
for (AtomicGroup::iterator atom = subset.begin(); atom != subset.end(); ++atom) {
// Do something
// performTransformation(*atom);
}
// Convert the subset into a PDB
PDB pdb = PDB::fromAtomicGroup(subset);
// Insert the logging information into the remarks at the start of the PDB
pdb.remarks().add(header);
// Write the PDB to stdout
cout << pdb;
}
| 2,227
|
C++
|
.cpp
| 56
| 36.160714
| 83
| 0.732493
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,106
|
test_mmcif_2.cpp
|
GrossfieldLab_loos/Packages/User/test_mmcif_2.cpp
|
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2023 Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace loos;
int main(int argc, char *argv[]) {
std::string filename = argv[1];
MMCIF mmcif_system(filename);
std::cerr << "size = " << mmcif_system.size() << std::endl;
std::cerr << " centroids: " << "\t"
<< mmcif_system.centroid() << std::endl;
//AtomicGroup ligand = selectAtoms(mmcif_system, std::string("resname=='LIG'"));
//std::cerr << "ligand size = " << ligand.size() << std::endl;
//std::cerr << *(ligand[0]) << std::endl;
AtomicGroup system = createSystem(filename);
std::cerr << "size = " << system.size() << std::endl;
std::cerr << "centroid from ag = " << system.centroid() << std::endl;
return 0;
}
| 1,530
|
C++
|
.cpp
| 32
| 43.9375
| 84
| 0.695914
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
755,107
|
simple_model_calc.cpp
|
GrossfieldLab_loos/Packages/User/simple_model_calc.cpp
|
/*
simple_model_calc.cpp
(c) 2011 Tod D. Romo, Grossfield Lab
Department of Biochemistry
University of Rochster School of Medicine and Dentistry
C++ template for writing a tool that performs a calculation on a model with minimal
command-line options
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2011 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
int main(int argc, char *argv[]) {
// How the tool was invoked, for logging purposes...
string header = invocationHeader(argc, argv);
// ***EDIT***
// Verify correct number of command-line arguments
if (argc != 3) {
cerr << "Usage- simple_model_calc model-name selection\n";
}
// Handle command-line arguments
int arg_index = 1;
// Read in the model
AtomicGroup model = createSystem(argv[arg_index++]);
// Select a subset of it
AtomicGroup subset = selectAtoms(model, argv[arg_index++]);
// ***EDIT***
// Iterate over all atoms in the subset, performing some computation
for (AtomicGroup::iterator atom = subset.begin(); atom != subset.end(); ++atom) {
// Do something
// calculateSomething(*atom)
}
// ***EDIT***
// Show results...
}
| 1,975
|
C++
|
.cpp
| 50
| 35.84
| 85
| 0.730242
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,108
|
hcontacts.cpp
|
GrossfieldLab_loos/Packages/HydrogenBonds/hcontacts.cpp
|
/*
hcontacts.cpp
Constructs a matrix representing time series for multiple for inter and/or intra-molecular hbonds
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include "hcore.hpp"
using namespace std;
using namespace loos;
using namespace HBonds;
namespace po = boost::program_options;
namespace opts = loos::OptionsFramework;
typedef vector<AtomicGroup> vGroup;
typedef pair<SimpleAtom, SimpleAtom> Bond;
typedef vector<Bond> vBond;
bool inter_bonds, intra_bonds;
double putative_threshold;
double length_low, length_high, max_angle;
bool use_periodicity;
string donor_selection, acceptor_selection;
string model_name, traj_name;
// @cond TOOLS_INTERNAL
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tHydrogen bond contacts for a trajectory as a matrix\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool creates a matrix that represents a time series of the state of all\n"
"possible hydrogen bonds for a given set of donor/acceptor selections. Each element\n"
"of the matrix is either a 1 (hydrogen bond present) or a 0 (hydrogen bond absent).\n"
"Each column of the matrix is a possible hydrogen bond and each row of the matrix\n"
"is a time-step (frame) from the trajectory.\n"
"\tThe donors and acceptors are determined by the selections given. The donor selection\n"
"must select only hydrogen atoms (names beginning with an 'H'). A search for all possible\n"
"hydrogen bond pairs is conducted at the start of the program, where any acceptor atom\n"
"within a cutoff distance of any donor hydrogen is a pair that is tracked. This search\n"
"is conducted on a per-molecule basis, as determined by the --inter and --intra flags.\n"
"If --inter=1, then intermolecular contacts are searched (i.e. any donor in one molecule\n"
"vs all possible acceptors in all other molecules). If --intra=1, then intramolecular\n"
"contacts are searched (i.e. any donor/acceptor atom in the same molecule). This search\n"
"requires both connectivity and coordinates to be present. If the model does not provide\n"
"coordinates (e.g. a PSF file), then the coordinates will be taken from the first frame\n"
"of the trajectory.\n"
"\tThe metadata at the top of the ASCII matrix output lists all of the possible hydrogen-\n"
"bond pairs that are tracked. The first number is the column (0-based index) in the\n"
"matrix representing that bond. To plot the column in Octave/gnuplot, add 1 to the column\n"
"index. The first column of the matrix is the frame number from the trajectory for the\n"
"corresponding row of the matrix.\n"
"\n"
"EXAMPLES\n"
"\n"
"\thcontacts model.pdb sim.dcd 'resname == \"ARG\" && name =~ \"^HH\" && segid =~ \"PE\\d+\"'\\\n"
"\t 'segid =~ \"PE\\d+\" && name =~ \"^O\"' >bonds.asc\n"
"This example searches for all contacts between any ARG atom beginnig with 'HH' in\n"
"any segment that is PE and a number (i.e. PE0, PE1, PE11, ...) and any atom in the\n"
"same set of segments that begins with an O. By default, only intermolecular hydrogen-\n"
"bonds are considered. The default bond constraints of angle <= 30 and 1.5 <= d <= 3.0 are\n"
"used. The initial search distance cutoff is 10.0 Angstroms.\n"
"\n"
"\thcontacts --search=30 model.pdb sim.dcd \\\n"
"\t 'resname == \"ARG\" && name =~ \"^HH\" && segid =~ \"PE\\d+\"'\\\n"
"\t 'segid =~ \"PE\\d+\" && name =~ \"^O\"' >bonds.asc\n"
"This example is the same as above, but the initial search for possible bonds uses a\n"
"cutoff of 30 Angstroms.\n"
"\n"
"SEE ALSO\n"
"\thbonds, hmatrix, hcorrelation\n";
return(msg);
}
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("search", po::value<double>(&putative_threshold)->default_value(10.0), "Threshold for initial bond search")
("blow", po::value<double>(&length_low)->default_value(1.5), "Low cutoff for bond length")
("bhi", po::value<double>(&length_high)->default_value(3.0), "High cutoff for bond length")
("angle", po::value<double>(&max_angle)->default_value(30.0), "Max bond angle deviation from linear")
("periodic", po::value<bool>(&use_periodicity)->default_value(false), "Use periodic boundary")
("inter", po::value<bool>(&inter_bonds)->default_value(true), "Inter-molecular bonds")
("intra", po::value<bool>(&intra_bonds)->default_value(false), "Intra-molecular bonds");
}
void addHidden(po::options_description& o) {
o.add_options()
("donor", po::value<string>(&donor_selection), "donor selection")
("acceptor", po::value<string>(&acceptor_selection), "acceptor selection");
}
void addPositional(po::positional_options_description& opts) {
opts.add("donor", 1);
opts.add("acceptor", 1);
}
bool check(po::variables_map& map) {
if (!(inter_bonds || intra_bonds)) {
cerr << "Error- must specify at least some kind of bond (inter/intra) to calculate.\n";
return(true);
}
return(false);
}
string help() const {
return("donor-selection acceptor-selection");
}
string print() const {
ostringstream oss;
oss << boost::format("search=%f,inter=%d,intra=%d,blow=%f,bhi=%f,angle=%f,periodic=%d,acceptor=\"%s\",donor=\"%s\"")
% putative_threshold
% inter_bonds
% intra_bonds
% length_low
% length_high
% max_angle
% use_periodicity
% acceptor_selection
% donor_selection;
return(oss.str());
}
};
// @endcond
// Given a vector of molecules, apply selection to each return a vector of subsets
vGroup splitSelection(const vGroup& molecules, const string& selection) {
vGroup results;
for (vGroup::const_iterator i = molecules.begin(); i != molecules.end(); ++i) {
AtomicGroup subset;
try {
subset = selectAtoms(*i, selection);
}
catch (...) { // Ignore exceptions
;
}
if (!subset.empty())
results.push_back(subset);
}
if (results.empty()) {
cerr << "Error- The selection '" << selection << "' resulted in nothing being selected.\n";
exit(-1);
}
return(results);
}
// Build up a vector of Bonds by looking for any donor/acceptor pair that's within a threshold
// distance
vBond findPotentialBonds(const AtomicGroup& donors, const AtomicGroup& acceptors, const AtomicGroup& system) {
vBond bonds;
for (AtomicGroup::const_iterator j = donors.begin(); j != donors.end(); ++j) {
GCoord u = (*j)->coords();
for (AtomicGroup::const_iterator i = acceptors.begin(); i != acceptors.end(); ++i) {
if (u.distance((*i)->coords()) <= putative_threshold) {
// Manually build simple atoms
SimpleAtom new_donor(*j, system.sharedPeriodicBox(), use_periodicity);
string name = (*j)->name();
if (name[0] != 'H') {
cerr << boost::format("Error- atom %s was given as a donor, but donors can only be hydrogens.\n") % name;
exit(-10);
}
vector<int> bond_list = (*j)->getBonds();
if (bond_list.size() != 1) {
cerr << "Error- The following hydrogen atom has more than one bond to it...woops...\n";
cerr << *j;
exit(-10);
}
pAtom pa = system.findById(bond_list[0]);
if (pa == 0) {
cerr << boost::format("Error- cannot find atomid %d in system.\n") % bond_list[0];
exit(-10);
}
new_donor.attach(pa);
SimpleAtom new_acceptor(*i, system.sharedPeriodicBox(), use_periodicity);
Bond new_bond(new_donor, new_acceptor);
bonds.push_back(new_bond);
}
}
}
return(bonds);
}
ostringstream& formatBond(ostringstream& oss, const uint i, const Bond& bond) {
pAtom a = bond.first.rawAtom();
pAtom b = bond.second.rawAtom();
oss << boost::format("# %d : %d-%s-%s-%d-%s => %d-%s-%s-%d-%s")
% i
% a->id() % a->name() % a->resname() % a->resid() % a->segid()
% b->id() % b->name() % b->resname() % b->resid() % b->segid();
return(oss);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::BasicTrajectory* tropts = new opts::BasicTrajectory;
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(tropts).add(topts);
if (! options.parse(argc, argv))
exit(-1);
AtomicGroup model = tropts->model;
pTraj traj = tropts->trajectory;
if (use_periodicity && !traj->hasPeriodicBox()) {
cerr << "Error- trajectory has no periodic box information\n";
exit(-1);
}
// Get coords if required...
if (!model.hasCoords()) {
traj->readFrame();
traj->updateGroupCoords(model);
if (tropts->skip > 0)
traj->readFrame(tropts->skip - 1);
else
traj->rewind();
}
vGroup mols = model.splitByMolecule();
// First, build list of pairs we will search for...
vGroup raw_donors = splitSelection(mols, donor_selection);
vGroup raw_acceptors = splitSelection(mols, acceptor_selection);
vBond bond_list;
for (uint j=0; j<raw_donors.size(); ++j) {
if (intra_bonds) {
vBond bonds = findPotentialBonds(raw_donors[j], raw_acceptors[j], model);
copy(bonds.begin(), bonds.end(), back_inserter(bond_list));
}
if (inter_bonds) {
for (uint i=0; i<raw_acceptors.size(); ++i) {
if (j == i)
continue;
vBond bonds = findPotentialBonds(raw_donors[j], raw_acceptors[i], model);
copy(bonds.begin(), bonds.end(), back_inserter(bond_list));
}
}
}
// Generate the metadata for the output...
ostringstream oss;
oss << hdr << endl;
for (uint i=0; i<bond_list.size(); ++i) {
formatBond(oss, i+1, bond_list[i]);
if (i < bond_list.size()-1)
oss << endl;
}
loos::Math::Matrix<uint> M(traj->nframes() - tropts->skip, bond_list.size()+1);
uint j = 0;
while (traj->readFrame()) {
traj->updateGroupCoords(model);
M(j, 0) = j + tropts->skip;
for (uint i=0; i<bond_list.size(); ++i)
M(j, i+1) = bond_list[i].first.hydrogenBond(bond_list[i].second);
++j;
}
writeAsciiMatrix(cout, M, oss.str());
}
| 11,281
|
C++
|
.cpp
| 262
| 38.038168
| 120
| 0.661065
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,109
|
hbonds.cpp
|
GrossfieldLab_loos/Packages/HydrogenBonds/hbonds.cpp
|
/*
hbonds
Find putative hydrogen-bonds based on user-specified criteria (angle and distance)
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include "hcore.hpp"
using namespace std;
using namespace loos;
using namespace HBonds;
namespace po = boost::program_options;
namespace opts = loos::OptionsFramework;
typedef vector<string> veString;
typedef vector<double> veDouble;
typedef vector<veDouble> veveDouble;
typedef vector<uint> veUint;
typedef vector<veUint> veveUint;
typedef Math::Matrix<double, Math::RowMajor> Matrix;
// --------------- GLOBALS
double length_low, length_high;
double max_angle;
bool use_periodicity;
bool verbose;
bool use_stderr;
vector<string> acceptor_names;
vector<string> acceptor_selections;
string donor_selection;
string model_name;
vector<string> traj_names;
uint skip = 0;
// ---------------
// @cond TOOLS_INTERNAL
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tHydrogen bond occupancy for a trajectory\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool computes the occupancy of putative hydrogen bonds (defined by\n"
"a simple distance and angle criteria). The 'donor' selection must have one\n"
"hydrogen present and the 'acceptor' should have no hydrogens. Multiple acceptors\n"
"may be given on the command line. These are specified by using multiple sets of\n"
"options, i.e. -N name -S selection where name is the label for the acceptor and\n"
"selection is the corresponding LOOS selection string. There must be at least\n"
"one name/selection pair. The occupancy calculation can also be performed over\n"
"multiple trajectories by specifying more than one on the command line.\n"
"\n"
"EXAMPLES\n"
"\n"
"\thbonds -N 'Carbonyl' -S 'name == \"O1\" && resname == \"PALM\"' \\\n"
"\t 'resid == 4 && name == \"HE1\"' model.psf traj.dcd\n"
"This example uses the palmitoyl carbonyl oxygen as the acceptor and the HE1 hydrogen from\n"
"residue 4 as the donor.\n"
"\n"
"\thbonds -N 'Carbonyl' -S 'name == \"O1\" && resname == \"PALM\"' \\\n"
"\t -N 'Phosphate' -S 'name == \"OP1\" && resname == \"PEGL\"' \\\n"
"\t 'resid == 4 && name == \"HE1\"' model.psf traj.dcd\n"
"This example uses the palmitoyl carbonyl oxygen as above, but also looks for hydrogen\n"
"bonds with the OP1 phosphate oxygen in residue PEGL. The same donor as above is used.\n"
"\n"
"\thbonds --blow 2 --bhi 4 --angle 20 -N 'Carbonyl' \\\n"
"\t -S 'name == \"O1\" && resname == \"PALM\"' 'resid == 4 && name == \"HE1\"' \\\n"
"\t model.psf traj.dcd\n"
"This example is the same as the first, however the criteria for hydrogen bonds are now\n"
"that they cannot be shorter than 2 angstroms nor longer than 4 angstroms, and the angle\n"
"cannot be more than 20 degrees from linear.\n"
"\n"
"SEE ALSO\n"
"\thmatrix, hcorrelation\n";
return(msg);
}
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("skip,k", po::value<uint>(&skip)->default_value(0), "Number of frames to skip")
("stderr", po::value<bool>(&use_stderr)->default_value(false), "Report stderr rather than stddev")
("blow", po::value<double>(&length_low)->default_value(1.5), "Low cutoff for bond length")
("bhi", po::value<double>(&length_high)->default_value(3.0), "High cutoff for bond length")
("angle", po::value<double>(&max_angle)->default_value(30.0), "Max bond angle deviation from linear")
("periodic", po::value<bool>(&use_periodicity)->default_value(false), "Use periodic boundary")
("name,N", po::value< vector<string> >(&acceptor_names), "Name of an acceptor selection (required)")
("acceptor,S", po::value< vector<string> >(&acceptor_selections), "Acceptor selection (required)");
}
void addHidden(po::options_description& o) {
o.add_options()
("donor", po::value<string>(&donor_selection), "donor selection")
("model", po::value<string>(&model_name), "model")
("trajs", po::value< vector<string> >(&traj_names), "Trajectories");
}
void addPositional(po::positional_options_description& opts) {
opts.add("donor", 1);
opts.add("model", 1);
opts.add("trajs", -1);
}
bool postConditions(po::variables_map& map) {
if (acceptor_selections.empty()) {
cerr << "Error- must provide at least one acceptor name and selection.\n";
return(false);
}
if (acceptor_selections.size() != acceptor_names.size()) {
cerr << "Error- must provide one name for each acceptor selection.\n";
return(false);
}
return(true);
}
string help() const {
return("donor model traj [traj ...]");
}
string print() const {
ostringstream oss;
oss << boost::format("skip=%d,stderr=%d,blow=%f,bhi=%f,angle=%f,periodic=%d,names=\"%s\",acceptors=\"%s\",donor=\"%s\",model=\"%s\",trajs=\"%s\"")
% skip
% use_stderr
% length_low
% length_high
% max_angle
% use_periodicity
% vectorAsStringWithCommas(acceptor_names)
% vectorAsStringWithCommas(acceptor_selections)
% donor_selection
% model_name
% vectorAsStringWithCommas(traj_names);
return(oss.str());
}
};
// @endcond
veDouble rowAverage(const Matrix& M) {
uint m = M.rows();
uint n = M.cols();
veDouble avg;
for (uint j=0; j<m; ++j) {
double x = 0.0;
for (uint i=0; i<n; ++i)
x += M(j, i);
avg.push_back(x/n);
}
return(avg);
}
veDouble rowStd(const Matrix& M, const veDouble& avg) {
uint m = M.rows();
uint n = M.cols();
if (n < 3)
return(veDouble(m, 0.0));
veDouble stddev;
for (uint j=0; j<m; ++j) {
double x = 0.0;
for (uint i=0; i<n; ++i) {
double d = M(j, i) - avg[j];
x += d*d;
}
stddev.push_back(sqrt(x/(n-1.0)));
}
return(stddev);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
SimpleAtom::innerRadius(length_low);
SimpleAtom::outerRadius(length_high);
SimpleAtom::maxDeviation(max_angle);
cout << "# " << hdr << endl;
cout << "# " << vectorAsStringWithCommas(options.print()) << endl;
AtomicGroup model = createSystem(model_name);
SAGroup donors = SimpleAtom::processSelection(donor_selection, model, use_periodicity);
vector<SAGroup> acceptors;
for (uint i=0; i<acceptor_selections.size(); ++i) {
SAGroup acceptor = SimpleAtom::processSelection(acceptor_selections[i], model, use_periodicity);
cout << boost::format("# Group %d size is %d\n") % i % acceptor.size();
acceptors.push_back(acceptor);
}
acceptor_names.push_back("Unbound/Other");
uint n = traj_names.size() * donors.size();
uint m = acceptor_selections.size();
Matrix M(m+1, n);
if (verbose)
cerr << "Processing- ";
for (uint k = 0; k<traj_names.size(); ++k) {
if (verbose)
cerr << traj_names[k] << " ";
pTraj traj = createTrajectory(traj_names[k], model);
if (skip >= traj->nframes()) {
cerr << boost::format("Error- trajectory '%s' only has %d frames in it, but we are skipping %d frames...\n")
% traj_names[k]
% traj->nframes()
% skip;
exit(-20);
}
BondMatrix B(m, donors.size());
for (uint t = skip; t<traj->nframes(); ++t) {
traj->readFrame(t);
traj->updateGroupCoords(model);
for (uint i=0; i<donors.size(); ++i) {
for (uint j=0; j<acceptors.size(); ++j) {
AtomicGroup found = donors[i].findHydrogenBonds(acceptors[j], true);
if (! found.empty())
B(j, i) += 1;
}
}
}
for (uint i=0; i<donors.size(); ++i) {
double sum = 0.0;
for (uint j=0; j<m; ++j) {
double fraction = static_cast<double>(B(j, i)) / traj->nframes();
sum += fraction;
M(j, k * donors.size() + i) = fraction;
}
M(m, k * donors.size() + i) = (sum > 1.0) ? 0.0 : (1.0 - sum);
}
}
if (verbose)
cerr << endl;
veDouble averages = rowAverage(M);
veDouble standards = rowStd(M, averages);
for (uint i=0; i<averages.size(); ++i)
cout << boost::format("%-3d %-20s %.4f %.4f\n")
% i
% acceptor_names[i]
% averages[i]
% (standards[i] / (use_stderr ? sqrt(donors.size() * traj_names.size()) : 1.0));
}
| 9,501
|
C++
|
.cpp
| 245
| 34.163265
| 150
| 0.648637
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,110
|
hmatrix.cpp
|
GrossfieldLab_loos/Packages/HydrogenBonds/hmatrix.cpp
|
/*
hmatrix.cpp
Writes out a matrix representing hbonds over time
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include "hcore.hpp"
using namespace std;
using namespace loos;
using namespace HBonds;
namespace po = boost::program_options;
namespace opts = loos::OptionsFramework;
// --------------- GLOBALS
double length_low, length_high;
double max_angle;
bool use_periodicity;
string donor_selection, acceptor_selection;
string model_name;
string traj_name;
uint currentTimeStep = 0;
// ---------------
// @cond TOOLS_INTERNAL
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tHydrogen bond state for a trajectory as a matrix\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool creates a matrix representing the state of putative hydrogen bonds\n"
"(1 = present, 0 = absent). Each row of the matrix is one frame (time-point) of\n"
"the trajectory. Each column corresponds to a possible h-bond acceptor. Only\n"
"one donor may be specified. Note that the donor is specified by selecting the\n"
"donated hydrogen. Criteria for putative hydrogen-bonds are an inner and outer\n"
"distance cutoff and an angle deviation from linear (in degrees) cutoff.\n"
"\n"
"EXAMPLES\n"
"\n"
"\thmatrix model.psf sim.dcd 'segid == \"PE1\" && resid == 4 && name == \"HE1\"'\\\n"
"\t 'name == \"O1\" && resname == \"PALM\"'\n"
"This example looks for hbonds between the HE1 hydrogen of residue 4 in the PE1 segment and\n"
"any palmitoyl carbonyl oxygen, O1.\n"
"\n"
"\thmatrix --blow 2.0 --bhi 4.0 --angle 25.0 model.psf sim.dcd \\\n"
"\t 'segid == \"PE1\" && resid == 4 && name == \"HE1\"'\\\n"
"\t 'name == \"O1\" && resname == \"PALM\"'\n"
"This example is the same as the above one, but with the hydrogen bond criteria changed\n"
"to greater than or equal to 2.0 angstroms and less than or equal to 4.0 angstroms, with\n"
"an angle of less than or equal to 25.0 degrees.\n"
"\n"
"SEE ALSO\n"
"\thbonds, hcorrelation\n";
return(msg);
}
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("blow", po::value<double>(&length_low)->default_value(1.5), "Low cutoff for bond length")
("bhi", po::value<double>(&length_high)->default_value(3.0), "High cutoff for bond length")
("angle", po::value<double>(&max_angle)->default_value(30.0), "Max bond angle deviation from linear")
("periodic", po::value<bool>(&use_periodicity)->default_value(false), "Use periodic boundary");
}
void addHidden(po::options_description& o) {
o.add_options()
("donor", po::value<string>(&donor_selection), "donor selection")
("acceptor", po::value<string>(&acceptor_selection), "acceptor selection");
}
void addPositional(po::positional_options_description& opts) {
opts.add("donor", 1);
opts.add("acceptor", 1);
}
string help() const {
return("donor-selection acceptor-selection");
}
string print() const {
ostringstream oss;
oss << boost::format("blow=%f,bhi=%f,angle=%f,periodic=%d,acceptor=\"%s\",donor=\"%s\"")
% length_low
% length_high
% max_angle
% use_periodicity
% acceptor_selection
% donor_selection;
return(oss.str());
}
};
// @endcond
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::BasicTrajectory* tropts = new opts::BasicTrajectory;
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(tropts).add(topts);
if (! options.parse(argc, argv))
exit(-1);
AtomicGroup model = tropts->model;
pTraj traj = tropts->trajectory;
if (use_periodicity && !traj->hasPeriodicBox()) {
cerr << "Error- trajectory has no periodic box information\n";
exit(-1);
}
SimpleAtom::innerRadius(length_low);
SimpleAtom::outerRadius(length_high);
SimpleAtom::maxDeviation(max_angle);
SAGroup donors = SimpleAtom::processSelection(donor_selection, model, use_periodicity);
if (donors.size() != 1) {
cerr << "Error- only specify one donor atom (the attached hydrogen)\n";
exit(-1);
}
SAGroup acceptors = SimpleAtom::processSelection(acceptor_selection, model, use_periodicity);
BondMatrix bonds = donors[0].findHydrogenBondsMatrix(acceptors, traj, model);
writeAsciiMatrix(cout, bonds, hdr);
}
| 5,391
|
C++
|
.cpp
| 133
| 36.586466
| 107
| 0.696463
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,111
|
hcorrelation.cpp
|
GrossfieldLab_loos/Packages/HydrogenBonds/hcorrelation.cpp
|
/*
hcorrelation.cpp
Computes time-correlation for hydrogen bonds...
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include "hcore.hpp"
using namespace std;
using namespace loos;
using namespace HBonds;
namespace po = boost::program_options;
namespace opts = loos::OptionsFramework;
typedef vector<double> vecDouble;
typedef vector<vecDouble> vecvecDouble;
typedef vector<string> vString;
// --------------- GLOBALS
double length_low, length_high;
double max_angle;
bool use_periodicity;
bool use_stderr;
string donor_selection, acceptor_selection;
string model_name;
vString traj_names;
uint maxtime;
uint skip;
bool any_hydrogen;
// ---------------
// ---------------
// @cond TOOLS_INTERNAL
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tHydrogen bond correlation times\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool generates the auto-correlation of putative hydrogen bonds for a trajectory.\n"
"Given a donor (hydrogen atom) and a set of acceptors, a matrix is constructed for\n"
"the trajectory where each row corresponds to a frame in the trajectory and each column\n"
"corresponds to a potential acceptor. If there is a hydrogen bond present, subject to\n"
"distance range and angle cutoff, then a 1 is placed in the matrix, otherwise a 0.\n"
"An auto-correlation is then calculated for each column. Only columns where there is\n"
"at least one hydrogen-bond present are included. If the any-hydrogen flag is set (--any=1),\n"
"then the state of the hydrogen bond at each time point is the union of all possible\n"
"acceptors. This is useful for asking what the correlation is between a donor and -any-\n"
"possible acceptor.\n"
"\tThis process is repeated for all possible donors and over all trajectories. The\n"
"correlation time-series is then averaged together, so what is written out is the average\n"
"correlation at a given time, over all donors and all trajectories. The maximum correlation\n"
"time is set automatically based on the shortest trajectory. However, it may be explicitly\n"
"set with the --maxtime T option.\n"
"\n"
"EXAMPLES\n"
"\n"
"\thcorrelation 'segid == \"PE1\" && resid == 4 && name == \"HE1\"' \\\n"
"\t 'name == \"O1\" && (resname == \"PALM\"' model.psf sim.dcd\n"
"This example uses the HE1 hydrogen of residue 4 in segment PE1 as the donor, and the O1\n"
"palmitoyl carnonyl oxygen as the acceptor. The average correlation over all carbonyl\n"
"oxygens is written out.\n"
"\n"
"\thcorrelation --any=1 'segid == \"PE1\" && resid == 4 && name == \"HE1\"'\\\n"
"\t 'name == \"O1\" && (resname == \"PALM\"' model.psf sim.dcd\n"
"This example is the same as above, however the correlation is for the peptide hydrogen (HE1)\n"
"hydrogen bonding to -any- palmitoyl carbonyl.\n"
"\n"
"\thcorrelation --blow=2.0 --bhi=4.0 --angle=25.0 --any=1 \\\n"
"\t 'segid == \"PE1\" && resid == 4 && name == \"HE1\"' \\\n"
"\t 'name == \"O1\" && (resname == \"PALM\"' model.psf sim.dcd\n"
"This example is the same as above, but with the hydrogen-bond criteria changed to be\n"
"2.0 <= distance <= 4.0 and the angle <= 25.0 degrees.\n"
"\n"
"SEE ALSO\n"
"\thmatrix, hbonds\n";
return(msg);
}
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("blow", po::value<double>(&length_low)->default_value(1.5), "Low cutoff for bond length")
("bhi", po::value<double>(&length_high)->default_value(3.0), "High cutoff for bond length")
("angle", po::value<double>(&max_angle)->default_value(30.0), "Max bond angle deviation from linear")
("periodic", po::value<bool>(&use_periodicity)->default_value(false), "Use periodic boundary")
("maxtime", po::value<uint>(&maxtime)->default_value(0), "Max time for correlation (0 = auto-size)")
("any", po::value<bool>(&any_hydrogen)->default_value(false), "Correlation for ANY hydrogen bound")
("stderr", po::value<bool>(&use_stderr)->default_value(0), "Report standard error rather than standard deviation");
}
void addHidden(po::options_description& o) {
o.add_options()
("donor", po::value<string>(&donor_selection), "donor selection")
("acceptor", po::value<string>(&acceptor_selection), "acceptor selection")
("model", po::value<string>(&model_name), "model")
("trajs", po::value< vector<string> >(&traj_names), "Trajectories");
}
void addPositional(po::positional_options_description& opts) {
opts.add("donor", 1);
opts.add("acceptor", 1);
opts.add("model", 1);
opts.add("trajs", -1);
}
bool check(po::variables_map& vm)
{
return(
donor_selection.empty()
|| acceptor_selection.empty()
|| model_name.empty()
|| traj_names.empty()
);
}
string help() const {
return("donor-selection acceptor-selection model traj [traj ...]");
}
string print() const {
ostringstream oss;
oss << boost::format("skip=%d,stderr=%d,blow=%f,bhi=%f,angle=%f,periodic=%d,maxtime=%d,any=%d,acceptor=\"%s\",donor=\"%s\",model=\"%s\",trajs=\"%s\"")
% skip
% use_stderr
% length_low
% length_high
% max_angle
% use_periodicity
% maxtime
% any_hydrogen
% acceptor_selection
% donor_selection
% model_name
% vectorAsStringWithCommas(traj_names);
return(oss.str());
}
};
// @endcond
vecDouble average(const vecvecDouble& A) {
uint n = A.size();
uint m = A[0].size();
vecDouble avg(m,0.0);
for (uint j=0; j<m; ++j)
for (uint i=0; i<n; ++i)
avg[j] += A[i][j];
for (uint j=0; j<m; ++j)
avg[j] /= n;
return(avg);
}
vecDouble stddev(const vecvecDouble& A, const vecDouble& avg) {
uint n = A.size();
uint m = A[0].size();
vecDouble std(m, 0.0);
if (n <= 3)
return(std);
for (uint j=0; j<m; ++j)
for (uint i=0; i<n; ++i) {
double d = A[i][j] - avg[j];
std[j] += d*d;
}
for (uint j=0; j<m; ++j)
std[j] = sqrt(std[j]/(n-1));
return(std);
}
uint findMinSize(const AtomicGroup& model, const vString& names) {
uint n = numeric_limits<uint>::max();
for (vString::const_iterator i = names.begin(); i != names.end(); ++i) {
pTraj traj = createTrajectory(*i, model);
if (traj->nframes() < n)
n = traj->nframes();
}
return(n);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions opts;
opts.add(bopts).add(topts);
if (! opts.parse(argc, argv))
exit(-1);
AtomicGroup model = createSystem(model_name);
SimpleAtom::innerRadius(length_low);
SimpleAtom::outerRadius(length_high);
SimpleAtom::maxDeviation(max_angle);
SAGroup donors = SimpleAtom::processSelection(donor_selection, model, use_periodicity);
SAGroup acceptors = SimpleAtom::processSelection(acceptor_selection, model, use_periodicity);
vecvecDouble correlations;
back_insert_iterator<vecvecDouble> corr_appender(correlations);
if (maxtime == 0)
maxtime = findMinSize(model, traj_names) / 2;
cerr << boost::format("Using %d as max time for correlation.\n") % maxtime;
for (vString::const_iterator ci = traj_names.begin(); ci != traj_names.end(); ++ci) {
cerr << "Processing " << *ci << endl;
pTraj traj = createTrajectory(*ci, model);
for (SAGroup::iterator j = donors.begin(); j != donors.end(); ++j) {
if (skip > 0)
traj->readFrame(skip-1);
BondMatrix bonds = j->findHydrogenBondsMatrix(acceptors, traj, model);
if (any_hydrogen) {
TimeSeries<double> ts;
for (uint j=0; j<bonds.rows(); ++j) {
double val = 0.0;
for (uint i=0; i<bonds.cols(); ++i)
if (bonds(j, i) != 0) {
val = 1.0;
break;
}
ts.push_back(val);
}
TimeSeries<double> tcorr = ts.correl(maxtime);
vecDouble vtmp;
copy(tcorr.begin(), tcorr.end(), back_inserter(vtmp));
correlations.push_back(vtmp);
} else {
for (uint i=0; i<bonds.cols(); ++i) {
bool found = false;
for (uint j=0; j<bonds.rows(); ++j)
if (bonds(j, i) != 0) {
found = true;
break;
}
if (found) {
TimeSeries<double> ts;
for (uint j=0; j<bonds.rows(); ++j)
ts.push_back(bonds(j, i));
TimeSeries<double> tcorr = ts.correl(maxtime);
vecDouble vtmp;
copy(tcorr.begin(), tcorr.end(), back_inserter(vtmp));
correlations.push_back(vtmp);
}
}
}
}
}
cerr << boost::format("Found %d time-correlations.\n") % correlations.size();
vecDouble avg = average(correlations);
vecDouble std = stddev(correlations, avg);
double scaling = 1.0;
if (use_stderr)
scaling = sqrt(correlations.size());
cout << "# " << hdr << endl;
cout << "# Found " << correlations.size() << " time-correlations." << endl;
cout << "# Using " << ( use_stderr ? "stderr" : "stddev") << endl;
for (uint j=0; j<avg.size(); ++j)
cout << j << "\t" << avg[j] << "\t" << (std[j] / scaling) << endl;
}
| 10,465
|
C++
|
.cpp
| 258
| 34.813953
| 154
| 0.636554
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,112
|
hcore.cpp
|
GrossfieldLab_loos/Packages/HydrogenBonds/hcore.cpp
|
/*
Core code for hbonds tools
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/format.hpp>
#include "hcore.hpp"
using namespace loos;
using namespace HBonds;
double SimpleAtom::inner = 0.0;
double SimpleAtom::outer = 3.5;
double SimpleAtom::deviation = 20.0;
// Reports distance^2 between hydrogen and heavy atom
// D-H ... X
// |-----|
double SimpleAtom::distance2(const SimpleAtom& s) const
{
double d;
if (usePeriodicity)
d = atom->coords().distance2(s.atom->coords(), sbox.box());
else
d = atom->coords().distance2(s.atom->coords());
return(d);
}
// Returns angle between atoms in degrees...
//
// D-H ... X
// \---/
double SimpleAtom::angle(const SimpleAtom& s) const {
loos::GCoord left, middle, right;
if (isHydrogen) {
if (s.isHydrogen)
throw(std::runtime_error("Cannot take the angle between two hydrogens"));
left = attached_to->coords();
middle = atom->coords();
right = s.atom->coords();
} else {
if (!s.isHydrogen)
throw(std::runtime_error("Cannot take the angle between two non-hydrogens"));
left = atom->coords();
middle = s.atom->coords();
right = s.attached_to->coords();
}
if (usePeriodicity) {
loos::GCoord box = sbox.box();
left.reimage(box);
middle.reimage(box);
right.reimage(box);
}
return(loos::Math::angle(left, middle, right));
}
// Converts a selection into a vector of SimpleAtoms. All new
// SimpleAtom's get assigned the use_periodicity flag
std::vector<SimpleAtom> SimpleAtom::processSelection(const std::string& selection, const loos::AtomicGroup& system, const bool use_periodicity) {
std::vector<SimpleAtom> processed;
// We don't want to force model to be sorted (esp since it's const)
// So, create a lightweight copy but use the same pAtoms...
loos::AtomicGroup searchable(system);
searchable.sort();
loos::AtomicGroup model = selectAtoms(system, selection);
for (loos::AtomicGroup::const_iterator i= model.begin(); i != model.end(); ++i) {
SimpleAtom new_atom(*i, system.sharedPeriodicBox(), use_periodicity);
std::string n = (*i)->name();
if (n[0] == 'H') {
new_atom.isHydrogen = true;
std::vector<int> bond_list = (*i)->getBonds();
if (bond_list.size() == 0)
throw(ErrorWithAtom(*i, "Detected a hydrogen bond that has no connectivity"));
if (bond_list.size() != 1)
throw(ErrorWithAtom(*i, "Detected a hydrogen bond that has more than one atom bound"));
loos::pAtom pa = searchable.findById(bond_list[0]);
if (pa == 0)
throw(ErrorWithAtom(*i, "Cannot find atom hydrogen is bound too"));
new_atom.attached_to = pa;
}
processed.push_back(new_atom);
}
return(processed);
}
// Check for a hdyrogen bond between two SimpleAtom's
bool SimpleAtom::hydrogenBond(const SAtom& o) const {
double dist = distance2(o);
double angl = angle(o);
if (dist >= inner && dist <= outer && fmod(fabs(angl - 180.0), 360.0) <= deviation)
return(true);
return(false);
}
// Returns an AtomicGroup containing the atoms that are hydrogen
// bonded to self. If findFirstOnly is true, than the first hydrogen
// bond found causes the function to return... (i.e. it may be a
// small optimization in performance)
loos::AtomicGroup SimpleAtom::findHydrogenBonds(const std::vector<SimpleAtom>& group, const bool findFirstOnly) {
loos::AtomicGroup results;
for (SAGroup::const_iterator i = group.begin(); i != group.end(); ++i) {
bool b = hydrogenBond(*i);
if (b) {
results.append(i->atom);
if (findFirstOnly)
break;
}
}
return(results);
}
// Returns a vector of flags indicating which SimpleAtoms form a
// hydrogen bond to self.
std::vector<uint> SimpleAtom::findHydrogenBondsVector(const std::vector<SimpleAtom>& group) {
std::vector<uint> results;
for (SAGroup::const_iterator i = group.begin(); i != group.end(); ++i)
results.push_back(hydrogenBond(*i));
return(results);
}
// Returns a matrix of flags indicating which SimpleAtoms form a
// hydrogen bond to self of a trajectory
BondMatrix SimpleAtom::findHydrogenBondsMatrix(const std::vector<SimpleAtom>& group, loos::pTraj& traj, loos::AtomicGroup& model, const uint maxt) const {
if (maxt > traj->nframes()) {
std::cerr << boost::format("Error- row clip (%d) exceeds trajectory size (%d)\n") % maxt % traj->nframes();
exit(-10);
}
BondMatrix bonds(maxt, group.size());
for (uint t = 0; t < maxt; ++t) {
traj->readFrame(t);
traj->updateGroupCoords(model);
for (uint i = 0; i<group.size(); ++i)
bonds(t, i) = hydrogenBond(group[i]);
}
return(bonds);
}
bool SimpleAtom::divineHydrogen(const std::string& name) {
if (name[0] == 'H')
return(true);
return(false);
}
| 5,625
|
C++
|
.cpp
| 146
| 34.582192
| 154
| 0.695967
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,113
|
eigenflucc.cpp
|
GrossfieldLab_loos/Packages/ElasticNetworks/eigenflucc.cpp
|
/*
eigenflucc
Predict isotropic B-factors from a set of eigenpairs...
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
using namespace std;
using namespace loos;
namespace po = boost::program_options;
// --------------- GLOBALS
bool verbose;
bool pca_input;
vector<uint> modes;
string eigvals_name, eigvecs_name, pdb_name;
string out_name;
double scale;
string selection;
const double kB = 6.950356e-9; // \AA^{-1} K
void fullHelp() {
//string msg =
cout << "\n"
"SYNOPSIS\n"
"\n"
"Predict isotropic B-factors from a set of eigenpairs\n"
"\n"
"DESCRIPTION\n"
"\n"
"Given the results of a network model or a simulation PCA\n"
"this tool will calculate the isotropic B-factors from the\n"
"eigenpairs. \n"
"\n"
"There are two modes of output:\n"
"\t- A list of B-factors numbered sequentially\n"
"\t- An updated PDB file containing the B-factors\n"
"\t NOTE: Make sure the same selection string used to\n"
"\t compute the ENM is used to ensure the correct\n"
"\t mapping of the B-factors.\n"
"\n"
//
"EXAMPLES\n"
"\n"
"eigenflucc anm_s.asc anm_U.asc > b_factors\n"
"\tCompute the B-factors of 'anm' and stream them to the\n"
"\tfile 'b_factors'. This outputs a sequential list of\n"
"\tof the values (may be more convenient for plotting).\n"
"\n"
"eigenflucc -p1 model.pdb -s 'name==\"CA\"' anm_s.asc anm_U.asc > b_factors\n"
"\tSame as above, but in addition we make a new pdb\n"
"\twhere the B-factors are modified based on our result.\n"
"\tThe original model.pdb is unaltered, but model-ef.pdb\n"
"\twill contain our results. In this case, the selection\n"
"\tstring includes all CA's, so they will be updated in\n"
"\tthe file output. \n"
"\n"
"eigenflucc -p1 model.pdb -o1 model_new_b-factors.pdb -S2 -s 'name==\"CA\"' \\\n"
" anm_s.asc anm_U.asc > b_factors\n"
"\tSame as previous, except the output pdb file is named\n"
"\tby the string \"model_new_b-factors.pdb\" and the\n"
"\tresults are scale by a factor of 2.\n"
"\n"
"eigenflucc -m1:3 -P1 pca_s.asc pca_U.asc > b_factors\n"
"\tComputes the B-factors from a PCA result. In\n"
"\taddtion, only the first 3 modes (or principal\n"
"\tcomponents) are used for the calculation. Only\n"
"\the sequential list is output (However a new PDB\n"
"\tfile can be written if desired).\n"
"\n"
"\n";
}
void parseArgs(int argc, char *argv[]) {
try {
po::options_description generic("Allowed options");
generic.add_options()
("help", "Produce this help message")
("fullhelp", "Get extended help")
("verbose,v", po::value<bool>(&verbose)->default_value(false), "Verbose output")
("selection,s", po::value<string>(&selection)->default_value("name == 'CA'"), "Selection used to make the ENM (only when altering a PDB)")
("pdb,p", po::value<string>(&pdb_name), "Alter the B-factors in a PDB")
("outpdb,o", po::value<string>(&out_name), "Filename to output PDB to")
("modes,m", po::value< vector<string> >(), "Modes to use (default is all)")
("scale,S", po::value<double>(&scale)->default_value(1.0), "Scaling factor to apply to eigenvalues")
("pca,P", po::value<bool>(&pca_input)->default_value(false), "Eigenpairs come from PCA, not ENM");
po::options_description hidden("Hidden options");
hidden.add_options()
("eigvals", po::value<string>(&eigvals_name), "Eigenvalues filename")
("eigvecs", po::value<string>(&eigvecs_name), "Eigenvectors filename");
po::options_description command_line;
command_line.add(generic).add(hidden);
po::positional_options_description p;
p.add("eigvals", 1);
p.add("eigvecs", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(command_line).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help") || vm.count("fullhelp") || !(vm.count("eigvals") && vm.count("eigvecs"))) {
cout << "Usage- " << argv[0] << " [options] eigenvalues eigenvectors\n";
cout << generic;
if (vm.count("fullhelp"))
fullHelp();
exit(0);
}
if (vm.count("modes")) {
vector<string> mode_list = vm["modes"].as< vector<string> >();
modes = parseRangeList<uint>(mode_list);
}
if (!pdb_name.empty())
if (out_name.empty())
out_name = findBaseName(pdb_name) + "-ef.pdb";
}
catch(exception& e) {
cerr << "Error - " << e.what() << endl;
exit(-1);
}
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
cout << "# " << hdr << endl;
parseArgs(argc, argv);
DoubleMatrix eigvals;
readAsciiMatrix(eigvals_name, eigvals);
DoubleMatrix eigvecs;
readAsciiMatrix(eigvecs_name, eigvecs);
if (modes.empty())
for (uint i=0; i<eigvals.rows(); ++i)
modes.push_back(i);
uint n = modes.size();
uint m = eigvecs.rows();
// V = m x n matrix of eigenvectors
DoubleMatrix V(m, n);
for (uint i=0; i<n; ++i)
for (uint j=0; j<m; ++j)
V(j, i) = eigvecs(j, modes[i]);
// Make a copy and scale by the appropriate eigenvalue,
// remembering that eigenvalues are inverted for ENM,
// or squaring and not inverting in the case of PCA
DoubleMatrix VS = V.copy();
for (uint i=0; i<n; ++i) {
double e = eigvals[modes[i]];
double s = (pca_input) ? (scale * e * e): (scale / e);
for (uint j=0; j<m; ++j)
VS(j, i) *= s;
}
// U = Covariance matrix
DoubleMatrix U = loos::Math::MMMultiply(VS,V,false,true);
// B-factors come from trace of diagonal 3x3 superblocks
vector<double> B;
double prefactor = 8.0 * M_PI * M_PI / 3.0;
for (uint i=0; i<m; i += 3) {
double b = prefactor * (U(i,i) + U(i+1, i+1) + U(i+2, i+2));
B.push_back(b);
cout << boost::format("%-8d %g\n") % (i/3) % b;
}
if (!pdb_name.empty()) {
AtomicGroup model = createSystem(pdb_name);
AtomicGroup subset = selectAtoms(model, selection);
if ((unsigned int)subset.size() != B.size()) {
cerr << boost::format("Error- selection has %d atoms, but %d were expected.\n") % subset.size() % B.size();
exit(-10);
}
for (uint i=0; i<B.size(); ++i)
subset[i]->bfactor(B[i]);
PDB pdb = PDB::fromAtomicGroup(model);
pdb.remarks().add(hdr);
ofstream ofs(out_name.c_str());
ofs << pdb;
}
}
| 7,320
|
C++
|
.cpp
| 185
| 34.978378
| 144
| 0.645763
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,114
|
side-nodes.cpp
|
GrossfieldLab_loos/Packages/ElasticNetworks/side-nodes.cpp
|
/*
side-nodes
(c) 2010 Tod D. Romo, Grossfield Lab
Department of Biochemistry
University of Rochster School of Medicine and Dentistry
Usage:
side-nodes selection model >output.pdb
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
pAtom findMatch(const pAtom& probe, const AtomicGroup& grp) {
for (AtomicGroup::const_iterator i = grp.begin(); i != grp.end(); ++i)
if ((*i)->name() == probe->name() && (*i)->id() == probe->id()
&& (*i)->resname() == probe->resname() && (*i)->resid() == probe->resid()
&& (*i)->segid() == probe->segid())
return(*i);
pAtom null;
return(null);
}
int main(int argc, char *argv[]) {
if (argc == 1) {
cout << "Usage- side-nodes selection model [psf] >output.pdb\n";
exit(0);
}
string hdr = invocationHeader(argc, argv);
int k = 1;
string selection(argv[k++]);
AtomicGroup model = createSystem(argv[k++]);
AtomicGroup subset = selectAtoms(model, selection);
if (argc > k) {
AtomicGroup structure = createSystem(argv[k++]);
for (AtomicGroup::iterator i = subset.begin(); i != subset.end(); ++i) {
pAtom match = findMatch(*i, structure);
if (!match) {
cerr << "ERROR- no match found for atom " << **i << endl;
exit(-1);
}
if (!match->checkProperty(Atom::massbit)) {
cerr << "ERROR- Atom has no mass: " << *match << endl;
exit(-1);
}
(*i)->mass(match->mass());
}
}
vector<AtomicGroup> residues = subset.splitByResidue();
AtomicGroup cg_sites;
int currid = model.maxId();
for (vector<AtomicGroup>::iterator vi = residues.begin(); vi != residues.end(); ++vi) {
// First, pick off the CA
AtomicGroup CA = vi->select(AtomNameSelector("CA"));
if (CA.empty()) {
cerr << "Error- cannot find CA.\n" << *vi;
exit(-10);
}
CA[0]->occupancy(CA[0]->mass());
cg_sites += CA[0];
AtomicGroup sidechain = vi->select(NotSelector(BackboneSelector()));
if (sidechain.empty()) {
cerr << "Warning- No sidechain atoms for:\n" << *vi;
continue;
}
GCoord c = sidechain.centerOfMass();
pAtom pa(new Atom(++currid, "CGS", c));
pa->resid(CA[0]->resid());
pa->resname(CA[0]->resname());
pa->segid(CA[0]->segid());
double m = sidechain.totalMass();
pa->occupancy(m);
cg_sites += pa;
}
PDB pdb = PDB::fromAtomicGroup(cg_sites);
pdb.remarks().add(hdr);
cout << pdb;
}
| 3,309
|
C++
|
.cpp
| 91
| 31.593407
| 89
| 0.647114
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,115
|
anm.cpp
|
GrossfieldLab_loos/Packages/ElasticNetworks/anm.cpp
|
/*
anm
(c) 2008 Tod D. Romo, Grossfield Lab
Department of Biochemistry
University of Rochster School of Medicine and Dentistry
Computes the anisotropic network model for a structure. It does
this by building a hessian for the structure, then computing the SVD
of it and the corresponding pseudo-inverse (ignoring the 6 lowest
modes).
Usage:
anm [selection string] radius model-name output-prefix
Examples:
anm 'resid >= 10 && resid <= 50 && name == "CA"' foo.pdb foo
This creates the following files:
foo_H.asc == The hessian
foo_U.asc == Left singular vectors
foo_s.asc == Singular values
foo_V.asc == Right singular vectors
foo_Hi.asc == Pseudo-inverse of H
foo_model.pdb == PDB model used for the ANM calculation
Notes:
o The default selection (if none is specified) is to pick CA's
o The output is in ASCII format suitable for use with Matlab/Octave/Gnuplot
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008,2009 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <limits>
#include "hessian.hpp"
#include "enm-lib.hpp"
#include "anm-lib.hpp"
using namespace std;
using namespace loos;
using namespace ENM;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// Globals... Icky poo!
string prefix;
int verbosity;
bool debug;
string spring_desc;
string bound_spring_desc;
string fullHelpMessage() {
string s =
"\n"
"SYNOPSIS\n"
"\n"
"Compute the anisotropic network model for a structure.\n"
"\n"
"DESCRIPTION\n"
"\n"
"An anisotropic network model predicts the motions of a structure\n"
"using a harmonic contact (spring) potential. (See Atilgan et al. 2001)\n"
"It does this by building a hessian for the structure, then computing\n"
"the SVD of it and the corresponding pseudo-inverse (ignoring the 6\n"
"lowest modes).\n"
"\n"
"This creates the following files:\n"
"\tfoo_H.asc - The hessian\n"
"\tfoo_U.asc - Left singular vectors\n"
"\tfoo_s.asc - Singular values\n"
"\tfoo_V.asc - Right singular vectors\n"
"\tfoo_Hi.asc - Pseudo-inverse of H\n"
"\tfoo_model.pdb - Model used for calculation\n"
"\n"
"\n"
"* Spring Constant Control *\n"
"Contacts between beads in an ANM are connected by a single potential\n"
"which is described by a hookean spring. The stiffness of each connection\n"
"can be modified using various definitions of the spring constant.\n"
"The spring constant used is controlled by the --spring option.\n"
"If only the name for the spring function is given, then the default\n"
"parameters are used. Alternatively, the name may include a\n"
"comma-separated list of parameters to be passed to the spring\n"
"function, i.e. --spring=distance,15.0\n\n"
"Available spring functions:\n";
vector<string> names = springNames();
for (vector<string>::const_iterator i = names.begin(); i != names.end(); ++i)
s = s + "\t" + *i + "\n";
s +=
"\n\n"
"* Adding \"Connectivity\" *\n"
"ANM also supports construction of spring connections based on\n"
"pseudo-connectivity. This allows beads neighboring in sequence\n"
"to be connected by a separate \"bound\" spring, chosen using the\n"
"--bound option. In this case the other or \"non-bound\" spring is\n"
"chosen with the --spring option.\n"
"\n"
"\n\n"
"EXAMPLES\n\n"
"anm --selection 'resid >= 10 && resid <= 50 && name == \"CA\"' foo.pdb foo\n"
"\tCompute the ANM for residues #10 through #50 with a 15 Angstrom cutoff\n"
"\ti.e. construct contacts using only the CA's that are within 15 Angstroms\n"
"\n"
"anm -S=exponential,-1.3 foo.pdb foo\n"
"\tCompute an ANM using an spring function where the magnitude of\n"
"\tthe connection decays exponentially with distance at a rate of\n"
"\texp(-1.3*r) where r is the distance between contacts. Note:\n"
"\tin this case all beads are connected - which can eliminate\n"
"\tan error in the numeric eigendecomposition.\n"
"\n"
"anm --bound=constant,100 --spring=exponential,-1.3 foo.pdb foo\n"
"\tSimilar to the example above, but using connectivity. Here\n"
"\tresidues that are adjacent in sequence are connected by\n"
"\tsprings with a constant stiffness of \"100\" and all other\n"
"\tresidues are connected by springs that decay exponentially\n"
"\twith distance\n"
"\n";
return(s);
}
// @cond TOOLS_INTERNAL
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("debug", po::value<bool>(&debug)->default_value(false), "Turn on debugging (output intermediate matrices)")
("spring,S", po::value<string>(&spring_desc)->default_value("distance"),"Spring function to use")
("bound", po::value<string>(&bound_spring_desc), "Bound spring");
}
string print() const {
ostringstream oss;
oss << boost::format("debug=%d, spring='%s', bound='%s'") % debug % spring_desc % bound_spring_desc;
return(oss.str());
}
};
// @endcond
loos::Math::Matrix<int> buildConnectivity(const AtomicGroup& model) {
uint n = model.size();
loos::Math::Matrix<int> M(n, n);
for (uint j=0; j<n-1; ++j)
for (uint i=j; i<n; ++i)
if (i == j)
M(j, i) = 1;
else {
M(j, i) = model[j]->isBoundTo(model[i]);
M(i, j) = M(j, i);
}
return(M);
}
int main(int argc, char *argv[]) {
string header = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::BasicSelection* sopts = new opts::BasicSelection("name == 'CA'");
opts::ModelWithCoords* mopts = new opts::ModelWithCoords;
ToolOptions* topts = new ToolOptions;
opts::RequiredArguments* ropts = new opts::RequiredArguments("prefix", "output-prefix");
opts::AggregateOptions options;
options.add(bopts).add(sopts).add(mopts).add(topts).add(ropts);
if (!options.parse(argc, argv))
exit(-1);
AtomicGroup model = mopts->model;
AtomicGroup subset = selectAtoms(model, sopts->selection);
verbosity = bopts->verbosity;
prefix = ropts->value("prefix");
if (verbosity > 0)
cerr << boost::format("Selected %d atoms from %s\n") % subset.size() % mopts->model_name;
PDB pdb = PDB::fromAtomicGroup(subset);
pdb.remarks().add(header);
string pdb_name = prefix + "_model.pdb";
ofstream pdb_out(pdb_name.c_str());
if (!pdb_out) {
cerr << "Error- unable to open " << pdb_name << " for output.\n";
exit(-1);
}
pdb_out << pdb;
pdb_out << "END \n";
pdb_out.close();
// Determine which kind of scaling to apply to the Hessian...
vector<SpringFunction*> springs;
SpringFunction* spring = 0;
spring = springFactory(spring_desc);
springs.push_back(spring);
vector<SuperBlock*> blocks;
SuperBlock* blocker = new SuperBlock(spring, subset);
blocks.push_back(blocker);
// Handle Decoration (if necessary)
if (!bound_spring_desc.empty()) {
if (! model.hasBonds()) {
cerr << "Error- cannot use bound springs unless the model has connectivity\n";
exit(-10);
}
loos::Math::Matrix<int> M = buildConnectivity(subset);
SpringFunction* bound_spring = springFactory(bound_spring_desc);
springs.push_back(bound_spring);
BoundSuperBlock* decorator = new BoundSuperBlock(blocker, bound_spring, M);
blocks.push_back(decorator);
blocker = decorator;
}
ANM anm(blocker);
anm.debugging(debug);
anm.prefix(prefix);
anm.meta(header);
anm.verbosity(verbosity);
anm.solve();
// Write out the LSVs (or eigenvectors)
writeAsciiMatrix(prefix + "_U.asc", anm.eigenvectors(), header, false);
writeAsciiMatrix(prefix + "_s.asc", anm.eigenvalues(), header, false);
writeAsciiMatrix(prefix + "_Hi.asc", anm.inverseHessian(), header, false);
for (vector<SuperBlock*>::iterator i = blocks.begin(); i != blocks.end(); ++i)
delete *i;
for (vector<SpringFunction*>::iterator i = springs.begin(); i != springs.end(); ++i)
delete *i;
}
| 9,271
|
C++
|
.cpp
| 217
| 36.912442
| 114
| 0.662465
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
755,116
|
enmovie.cpp
|
GrossfieldLab_loos/Packages/ElasticNetworks/enmovie.cpp
|
/*
enmovie
Elastic Network MOde VIsualizEr
Usage:
enmovie [options] model-name eigenvector-matrix output-name
Notes:
use the "--help" option for more information about how to run...
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <iterator>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <cassert>
using namespace std;
using namespace loos;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
typedef Math::Matrix<double> Matrix;
// --------------------------------------------------------------------------------
string vec_name;
vector<int> cols;
vector<double> scales;
double global_scale = 1.0;
bool uniform;
bool invert = false;
string model_name;
string map_name;
string selection;
string avgname;
bool autoscale, square;
double autolength;
string svals_file;
int verbosity = 0;
int offset = 0;
int nsteps = 100;
string supersel;
bool tag = false;
bool positive = false;
bool negative = false;
// @cond TOOLS_INTERNAL
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("mode,M", po::value< vector<string> >(&strings), "Modes to use")
("autoscale,A", po::value<bool>(&autoscale)->default_value(true), "Automatically scale vectors")
("autolength,L", po::value<double>(&autolength)->default_value(2.0), "Length of average vector in Angstroms")
("svals,S", po::value<string>(&svals_file), "Scale columns by singular values from file")
("pca", "Vectors are from PCA (sets square=1, invert=0, offset=0)")
("enm", "Vectors are from ENM (sets square=0, invert=1, offset=6)")
("superset,U", po::value<string>(&supersel)->default_value("all"), "Superset to use for frames in the output")
("tag,T", po::value<bool>(&tag)->default_value(false), "Tag ENM atoms with 'E' alt-loc")
("avg", po::value<string>(&avgname), "Use this model for average structure coordinates")
("square", po::value<bool>(&square)->default_value(true), "square the singular values")
("invert", po::value<bool>(&invert)->default_value(false), "Invert singular values (ENM)")
("scale", po::value< vector<double> >(&scales), "Scale the requested columns")
("global", po::value<double>(&global_scale)->default_value(1.0), "Global scaling")
("uniform", po::value<bool>(&uniform)->default_value(false), "Scale all elements uniformly")
("map", po::value<string>(&map_name), "Use a map file to map LSV/eigenvectors to atomids")
("offset", po::value<int>(&offset), "Added to mode indices to select columns in eigenvector matrix")
("positive", po::value<bool>(&positive)->default_value(false), "Only move along positive eigenvector direction")
("negative", po::value<bool>(&negative)->default_value(false), "Only move along negative eigenvector direction");
}
bool postConditions(po::variables_map& vm) {
if (vm.count("enm")) {
square = false;
invert = true;
offset = 6;
} else if (vm.count("pca")) {
square = true;
invert = false;
offset = 0;
}
if (strings.empty())
cols.push_back(0);
else
cols = parseRangeList<int>(strings);
for (uint i=0; i<cols.size(); ++i)
cols[i] += offset;
if (!scales.empty()) {
if (scales.size() != cols.size()) {
cerr << "ERROR - You must have the same number of scalings as columns or rely on the global scaling\n";
return(false);
}
} else {
for (uint i=0; i<cols.size(); ++i)
scales.push_back(1.0);
}
// Turn off since that's the default behavior
if (negative && positive)
negative = positive = false;
return(true);
}
string print() const {
ostringstream oss;
oss << boost::format("columns='%s', global=%f, uniform=%d, map='%s', autoscale=%d, autolength=%f, svals='%s', square=%d, invert=%d, offset=%d, tag=%d, superset='%s', avg='%s', positive=%d, negative=%d")
% vectorAsStringWithCommas<string>(strings)
% global_scale
% uniform
% map_name
% autoscale
% autolength
% svals_file
% square
% invert
% offset
% tag
% supersel
% avgname
% positive
% negative;
oss << "scale='";
copy(scales.begin(), scales.end(), ostream_iterator<double>(oss, ","));
oss << "'";
return(oss.str());
}
vector<string> strings;
};
// @endcond
string fullHelpMessage(void){
string msg =
"\n"
"SYNOPSIS\n"
"\n"
"\tCreate a representation of motion along the mode(s) of an ENM\n"
"\n"
"DESCRIPTION\n"
"\n"
"It is often informative to visualize the modes of motion predicted\n"
"by an ENM in addition to plotting eigenvectors. enmovie creates a dcd\n"
"and an accompanying pdb for this purpose. A 100 frame trajectory is \n"
"made and the beads follow a given eigenvector(s).\n"
"\n"
"* PCA vs ENM *\n"
"Enmovie should use different options depending on whether the eigenvectors come\n"
"from a PCA or an ENM. The --enm and --pca flags configure porcupine to expect\n"
"the appropriate input. If neither flag is given, then PCA is assumed.\n"
"For PCA results, the first mode is in the first column. LOOS\n"
"calculates a PCA using the singular value decomposition, so the 'eigenvalues' are\n"
"actually singular values and need to be squared. For typical ENMs, the first 6\n"
"eigenvectors correspond to rigid-body motion and are zero, and hence skipped.\n"
"In addition, the magnitude of the fluctuations are the inverse of the eigenvalues.\n"
"\n"
"* Scaling and Autoscaling *\n"
"There are several different ways the individual vectors can be scaled. The default\n"
"is to automatically determine a scaling such that the largest average displacement\n"
"is 2 Angstroms. If multiple modes are being used, then the corresponding eigenvector\n"
"can be used so the relative lengths are correct. When used with autoscaling, the\n"
"the relative lengths are maintained. In addition, an explicit scaling can be used\n"
"for each mode. If autoscaling or eigenvectors are used, then this is applied -after-\n"
"both of those. Finally, a global scaling can be applied. To see the scaling used\n"
"turn on verbose output (-v1). For more details about exactly what scaling is used,\n"
"set verbosity greater than 1 (-v2).\n"
"\n"
"In general, the default options should be fine for visualization. If you are using\n"
"more than one mode, then include the eigenvectors to preserve the relative scalings\n"
"between the modes.\n"
"\n"
"* Supersets *\n"
"Some visualization programs require more atoms than what the PCA/ENM used in order\n"
"to get the structure correct (such as ribbons representations). Including all atoms\n"
"can solve this problem. Alternatively, sometimes extra atoms are required to provide\n"
"context to the region of interest, such as the extracellular loops in GPCRs. You can\n"
"control what atoms are written to the trajectory with the superset selection. This\n"
"lets you add back in atoms that were excluded by the PCA/ENM. The catch is that they\n"
"will not move in the trajectory, resulting in distorted bonds/connections. The default\n"
"is to include all atoms in the output. If you want only the PCA/ENM region, then use\n"
"the same selection for the superset as the vector selection.\n"
"\n"
"EXAMPLES\n"
"\n"
"\tenmovie model.pdb pca_U.asc\n"
"This example uses the first mode, assumes a PCA result,\n"
"and autoscales the vectors. Creates output.pdb and output.dcd and\n"
"the trajectory has 100 frames.\n"
"\n"
"\tenmovie --pca -S pca_s.asc -M 0:3 -p modes model.pdb pca_U.asc\n"
"This example again uses the first three modes, autoscales, and also\n"
"scales each mode by the corresponding singular value. It explicitly uses\n"
"a PCA result. It creates modes.pdb and modes.dcd with 100 frames.\n"
"\n"
"\tenmovie --enm -S enm_s.asc -M 0:3 -p modes model.pdb enm_U.asc\n"
"This example is the same as above, but expects an ENM result (inverting the\n"
"eigenvalues, and skipping the first 6 eigenpairs.\n"
"\n"
"\tenmovie -S pca_s.asc -M 0,3,7 -L 3 -p modes model.pdb pca_U.asc\n"
"A PCA result is assumed, the first, fourth, and eighth mode are used, autoscaling\n"
"is turned on with a length of 3 Angstroms. The singular values are also included.\n"
"The output prefix is modes."
"\n"
"\tenmovie --enm -S enm_s.asc -M 0,1 -A 0 -p modes --global 50 model.pdb enm_U.asc\n"
"An ENM result is expected and the first two modes are used. Autoscaling is disabled.\n"
"Each mode is scaled by the corresponding eigenvalue (inverted, since this is an ENM).\n"
"A global scaling of 50 is applied to all modes.\n"
"\n"
"\tenmovie --pca -S pca_s.asc -M 0:3 -p modes -U 'name == \"CA\"' model.pdb pca_U.asc\n"
"This example again uses the first three modes, autoscales, and also\n"
"scales each mode by the corresponding singular value. It explicitly uses\n"
"a PCA result. It creates modes.pdb and modes.dcd with 100 frames.\n"
"The default selection is to use CAs for the eigenvectors, and the -U option\n"
"causes the output trajectory to only include CAs.\n"
"\n"
"\tenmovie -p pca_mode1 -t xtc model.pdb pca_U.asc\n"
"This example uses the first mode, assumes a PCA result,\n"
"and autoscales the vectors. Creates pca_mode1.pdb and pca_mode1.xtc and\n"
"the trajectory has 100 frames.\n"
"\n"
"SEE ALSO\n"
"\n"
"\tsvd, big-svd, svdcolmap, anm, gnm, vsa, porcupine\n"
;
return(msg);
}
string generateSegid(const uint n) {
stringstream s;
s << boost::format("P%03d") % n;
return(s.str());
}
// Accept a map file mapping the vectors (3-tuples in the rows) back
// onto the appropriate atoms
vector<int> readMap(const string& name) {
ifstream ifs(name.c_str());
if (!ifs) {
cerr << "Error- cannot open " << name << endl;
exit(-1);
}
string line;
uint lineno = 0;
vector<int> atomids;
while (!getline(ifs, line).eof()) {
stringstream ss(line);
int a, b;
if (!(ss >> a >> b)) {
cerr << "ERROR - cannot parse map at line " << lineno << " of file " << name << endl;
exit(-10);
}
atomids.push_back(b);
}
return(atomids);
}
// Fake the mapping, i.e. each vector corresponds to each atom...
vector<int> fakeMap(const AtomicGroup& g) {
AtomicGroup::const_iterator ci;
vector<int> atomids;
for (ci = g.begin(); ci != g.end(); ++ci)
atomids.push_back((*ci)->id());
return(atomids);
}
// Record the atomid's for each atom in the selected subset. This
// allows use to map vectors back onto the correct atoms when they
// were computed from a subset...
vector<int> inferMap(const AtomicGroup& g, const string& sel) {
AtomicGroup subset = selectAtoms(g, sel);
vector<int> atomids;
AtomicGroup::iterator ci;
for (ci = subset.begin(); ci != subset.end(); ++ci)
atomids.push_back((*ci)->id());
return(atomids);
}
double subvectorSize(const Matrix& U, const vector<double>& scaling, const uint j) {
GCoord c;
for (uint i=0; i<cols.size(); ++i) {
GCoord v(U(j, i), U(j+1, i), U(j+2, i));
c += scaling[i] * v;
}
return(c.length());
}
vector<double> determineScaling(const Matrix& U) {
uint n = cols.size();
vector<double> scaling(n, 1.0);
vector<double> svals(n, 1.0);
// First, handle singular values, if given
if (!svals_file.empty()) {
Matrix S;
readAsciiMatrix(svals_file, S);
if (verbosity > 1)
cerr << "Read singular values from file " << svals_file << endl;
if (S.cols() != 1) {
cerr << boost::format("Error- singular value file is %d x %d, but it should be a %d x 1\n") % S.rows() % S.cols() % U.rows();
exit(-2);
}
for (uint i = 0; i<n; ++i) {
scaling[i] = S[cols[i]];
if (square)
scaling[i] *= scaling[i];
if (invert && scaling[i] != 0.0)
scaling[i] = 1.0 / scaling[i];
svals[i] = scaling[i];
}
}
double avg = 0.0;
if (autoscale) {
for (uint i=0; i<U.rows(); i += 3)
avg += subvectorSize(U, scaling, i);
avg /= U.rows()/3.0;
for (uint i=0; i<n; ++i)
scaling[i] *= autolength / avg;
}
// Incorporate additional scaling...
if (verbosity > 1) {
cerr << "Average subvector size was " << avg << endl;
cerr << boost::format("%4s %4s %15s %15s\n") % "col" % "mode" % "sval" % "scale";
cerr << boost::format("%4s %4s %15s %15s\n") % "----" % "----" % "---------------" % "---------------";
}
for (uint i=0; i<n; ++i) {
scaling[i] *= scales[i] * global_scale;
if (verbosity > 1)
cerr << boost::format("%4d %4d %15.5f %15.5f\n") % cols[i] % (cols[i]-offset) % svals[i] % scaling[i];
else if (verbosity > 0)
cerr << boost::format("Scaling column %d by %f\n") % cols[i] % scaling[i];
}
return(scaling);
}
void copyCoordinates(AtomicGroup& target, const AtomicGroup& source) {
for (uint i=0; i<source.size(); ++i) {
pAtom atom = target.findById(source[i]->id());
if (atom == 0) {
cerr << "Error- could not find atomid " << source[i]->id() << " in the superset.\n";
cerr << source[i] << endl;
exit(-10);
}
atom->coords(source[i]->coords());
}
}
AtomicGroup renumberAndMapBonds(const AtomicGroup& model, const AtomicGroup& subset) {
AtomicGroup renumbered = subset.copy();
if (!renumbered.hasBonds()) {
renumbered.renumber();
return(renumbered);
}
AtomicGroup sorted = model.copy();
sorted.sort();
vector<int> idmap(model.size());
for (uint i=0; i<renumbered.size(); ++i)
idmap[renumbered[i]->index()] = i;
renumbered.pruneBonds();
for (uint i=0; i<renumbered.size(); ++i) {
if (! renumbered[i]->hasBonds())
continue;
vector<int> bondlist = renumbered[i]->getBonds();
vector<int> newbonds(bondlist.size());
for (uint j=0; j<bondlist.size(); ++j) {
pAtom a = sorted.findById(bondlist[j]);
if (a == 0) {
cerr << "Error- could not find atom id " << bondlist[j] << " in model\n";
exit(-2);
}
newbonds[j] = idmap[a->index()]+1;
}
renumbered[i]->setBonds(newbonds);
}
renumbered.renumber();
return(renumbered);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::OutputPrefix* popts = new opts::OutputPrefix("output");
opts::OutputTrajectoryTypeOptions* otopts = new opts::OutputTrajectoryTypeOptions;
opts::BasicSelection* sopts = new opts::BasicSelection("name == 'CA'");
opts::ModelWithCoords* mopts = new opts::ModelWithCoords;
ToolOptions* topts = new ToolOptions;
opts::RequiredArguments *ropts = new opts::RequiredArguments;
ropts->addArgument("lsv", "left-singular-vector-file");
opts::AggregateOptions options;
options.add(bopts).add(popts).add(otopts).add(sopts).add(mopts).add(topts).add(ropts);
if (!options.parse(argc, argv)) {
cerr << "***WARNING***\n";
cerr << "The interface to enmovie has changed significantly\n";
cerr << "and is not compatible with previous versions. See the\n";
cerr << "help info above, or the --fullhelp guide.\n";
exit(-1);
}
verbosity = bopts->verbosity;
// First, read in the LSVs
Matrix U;
readAsciiMatrix(ropts->value("lsv"), U);
uint m = U.rows();
vector<double> scalings = determineScaling(U);
// Read in the average structure...
AtomicGroup avg = mopts->model;
if (! avgname.empty()) {
AtomicGroup avgcoords = createSystem(avgname);
copyCoordinates(avg, avgcoords);
}
AtomicGroup superset = selectAtoms(mopts->model, supersel);
vector<int> atomids;
if (map_name.empty()) {
if (sopts->selection.empty())
atomids = fakeMap(avg);
else
atomids = inferMap(avg, sopts->selection);
} else
atomids = readMap(map_name);
// Double check size of atomid map
if (atomids.size() * 3 != m) {
cerr << boost::format("Error - The vector-to-atom map (provided or inferred) has %d atoms, but expected %d.\n") %
atomids.size() % (m / 3);
exit(-1);
}
pTrajectoryWriter traj = otopts->createTrajectory(popts->prefix);
// We'll step along the Eigenvectors using a sin wave as a final scaling...
bool doublesided = !(negative || positive);
double delta = (doublesided ? 2.0 : 1.0)*PI/nsteps;
double phase = negative ? PI : 0.0;
// Loop over requested number of frames...
for (int frameno=0; frameno<nsteps; frameno++) {
double k = sin(delta * frameno + phase);
// Have to make a copy of the atoms since we're computing a
// displacement from the model structure...
AtomicGroup frame = superset.copy();
AtomicGroup frame_subset = selectAtoms(frame, sopts->selection);
// Loop over all requested modes...
for (uint j = 0; j<cols.size(); ++j) {
// Loop over all atoms...
for (uint i=0; i<frame_subset.size(); i++) {
GCoord c = frame_subset[i]->coords();
// This gets the displacement vector for the ith atom of the
// ci'th mode...
GCoord d( U(i*3, cols[j]), U(i*3+1, cols[j]), U(i*3+2, cols[j]) );
if (uniform)
d /= d.length();
c += k * scalings[j] * d;
// Stuff those coords back into the Atom object...
frame_subset[i]->coords(c);
if (tag)
frame_subset[i]->chainId("E");
}
}
if (frameno == 0) {
// Write out the selection, converting it to a PDB
string outpdb(popts->prefix + ".pdb");
ofstream ofs(outpdb.c_str());
PDB pdb;
AtomicGroup structure = renumberAndMapBonds(avg, frame);
pdb = PDB::fromAtomicGroup(structure);
pdb.remarks().add(hdr);
ofs << pdb;
}
// Now that we've displaced the frame, add it to the growing trajectory...
traj->writeFrame(frame);
}
}
| 19,178
|
C++
|
.cpp
| 459
| 36.647059
| 206
| 0.649704
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,117
|
vsa-lib.cpp
|
GrossfieldLab_loos/Packages/ElasticNetworks/vsa-lib.cpp
|
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "vsa-lib.hpp"
using namespace std;
using namespace loos;
namespace ENM {
boost::tuple<DoubleMatrix, DoubleMatrix> VSA::eigenDecomp(DoubleMatrix& A, DoubleMatrix& B) {
DoubleMatrix AA = A.copy();
DoubleMatrix BB = B.copy();
f77int itype = 1;
char jobz = 'V';
char uplo = 'U';
char range = 'I';
f77int n = AA.rows();
f77int lda = n;
f77int ldb = n;
double vl = 0.0;
double vu = 0.0;
f77int il = 7;
f77int iu = n;
char dpar = 'S';
double abstol = 2.0 * dlamch_(&dpar);
//double abstol = -1.0;
f77int m;
DoubleMatrix W(n, 1);
DoubleMatrix Z(n, n);
f77int ldz = n;
f77int lwork = -1;
f77int info;
double *work = new double[1];
f77int *iwork = new f77int[5*n];
f77int *ifail = new f77int[n];
dsygvx_(&itype, &jobz, &range, &uplo, &n, AA.get(), &lda, BB.get(), &ldb, &vl, &vu, &il, &iu, &abstol, &m, W.get(), Z.get(), &ldz, work, &lwork, iwork, ifail, &info);
if (info != 0) {
cerr << "ERROR- dsygvx returned " << info << endl;
exit(-1);
}
lwork = work[0];
if (verbosity_ > 1)
std::cerr << "dsygvx requested " << work[0] /(1024.0*1024.0) << " MB\n";
delete[] work;
work = new double[lwork];
dsygvx_(&itype, &jobz, &range, &uplo, &n, AA.get(), &lda, BB.get(), &ldb, &vl, &vu, &il, &iu, &abstol, &m, W.get(), Z.get(), &ldz, work, &lwork, iwork, ifail, &info);
if (info != 0) {
cerr << "ERROR- dsygvx returned " << info << endl;
exit(-1);
}
if (m != n-6) {
cerr << "ERROR- only got " << m << " eigenpairs instead of " << n-6 << endl;
exit(-10);
}
vector<uint> indices = sortedIndex(W);
W = permuteRows(W, indices);
Z = permuteColumns(Z, indices);
boost::tuple<DoubleMatrix, DoubleMatrix> result(W, Z);
return(result);
}
// Mass-weight eigenvectors
DoubleMatrix VSA::massWeight(DoubleMatrix& U, DoubleMatrix& M) {
// First, compute the cholesky decomp of M (i.e. it's square-root)
DoubleMatrix R = M.copy();
char uplo = 'U';
f77int n = M.rows();
f77int lda = n;
f77int info;
dpotrf_(&uplo, &n, R.get(), &lda, &info);
if (info != 0) {
cerr << "ERROR- dpotrf() returned " << info << endl;
exit(-1);
}
if (debugging_)
writeAsciiMatrix(prefix_ + "_R.asc", R, meta_, false);
// Now multiply M * U
DoubleMatrix UU = U.copy();
f77int m = U.rows();
n = U.cols();
double alpha = 1.0;
f77int ldb = m;
#if defined(__linux__) || defined(__CYGWIN__) || defined(__FreeBSD__)
char side = 'L';
char notrans = 'N';
char diag = 'N';
dtrmm_(&side, &uplo, ¬rans, &diag, &m, &n, &alpha, R.get(), &lda, UU.get(), &ldb);
#else
cblas_dtrmm(CblasColMajor, CblasLeft, CblasUpper, CblasNoTrans, CblasNonUnit, m, n, alpha, R.get(), lda, UU.get(), ldb);
#endif
normalizeColumns(UU);
return(UU);
}
void VSA::solve() {
if (verbosity_ > 1)
std::cerr << "Building hessian...\n";
buildHessian();
uint n = hessian_.cols();
uint l = subset_size_ * 3;
DoubleMatrix Hss = submatrix(hessian_, Math::Range(0,l), Math::Range(0,l));
DoubleMatrix Hee = submatrix(hessian_, Math::Range(l, n), Math::Range(l, n));
DoubleMatrix Hse = submatrix(hessian_, Math::Range(0,l), Math::Range(l, n));
DoubleMatrix Hes = submatrix(hessian_, Math::Range(l, n), Math::Range(0, l));
if (debugging_) {
writeAsciiMatrix(prefix_ + "_H.asc", hessian_, meta_, false);
writeAsciiMatrix(prefix_ + "_Hss.asc", Hss, meta_, false);
writeAsciiMatrix(prefix_ + "_Hee.asc", Hee, meta_, false);
writeAsciiMatrix(prefix_ + "_Hse.asc", Hse, meta_, false);
}
if (verbosity_ > 1)
std::cerr << "Inverting environment hessian...\n";
DoubleMatrix Heei = Math::invert(Hee);
// Build the effective Hessian
if (verbosity_ > 1)
std::cerr << "Computing effective hessian...\n";
Hssp_ = Hss - Hse * Heei * Hes;
if (debugging_)
writeAsciiMatrix(prefix_ + "_Hssp.asc", Hssp_, meta_, false);
// Shunt in the event of using unit masses... We can use the SVD to
// to get the eigenpairs from Hssp
if (masses_.rows() == 0) {
Timer<> t;
if (verbosity_ > 0)
std::cerr << "Calculating SVD of effective hessian...\n";
t.start();
boost::tuple<DoubleMatrix, DoubleMatrix, DoubleMatrix> svdresult = svd(Hssp_);
t.stop();
if (verbosity_ > 0)
std::cerr << "SVD took " << loos::timeAsString(t.elapsed()) << std::endl;
eigenvecs_ = boost::get<0>(svdresult);
eigenvals_ = boost::get<1>(svdresult);
reverseColumns(eigenvecs_);
reverseRows(eigenvals_);
return;
}
// Build the effective mass matrix
DoubleMatrix Ms = submatrix(masses_, Math::Range(0, l), Math::Range(0, l));
DoubleMatrix Me = submatrix(masses_, Math::Range(l, n), Math::Range(l, n));
if (verbosity_ > 1)
std::cerr << "Computing effective mass matrix...\n";
Msp_ = Ms + Hse * Heei * Me * Heei * Hes;
if (debugging_) {
writeAsciiMatrix(prefix_ + "_Ms.asc", Ms, meta_, false);
writeAsciiMatrix(prefix_ + "_Me.asc", Me, meta_, false);
writeAsciiMatrix(prefix_ + "_Msp.asc", Msp_, meta_, false);
}
// Run the eigen-decomposition...
boost::tuple<DoubleMatrix, DoubleMatrix> eigenpairs;
Timer<> t;
if (verbosity_ > 0)
std::cerr << "Computing eigendecomposition...\n";
t.start();
eigenpairs = eigenDecomp(Hssp_, Msp_);
t.stop();
if (verbosity_ > 0)
std::cerr << "Eigendecomposition took " << loos::timeAsString(t.elapsed()) << std::endl;
eigenvals_ = boost::get<0>(eigenpairs);
DoubleMatrix Us = boost::get<1>(eigenpairs);
// Need to mass-weight the eigenvectors so they're orthogonal in R3...
eigenvecs_ = massWeight(Us, Msp_);
}
};
| 6,740
|
C++
|
.cpp
| 172
| 33.761628
| 170
| 0.61593
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,118
|
psf-masses.cpp
|
GrossfieldLab_loos/Packages/ElasticNetworks/psf-masses.cpp
|
/*
psf-masses
Takes masses from a PSF file and places them into the occupancy field of a PDB.
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace loos;
using namespace std;
pAtom findMatch(const pAtom& probe, const AtomicGroup& grp) {
for (AtomicGroup::const_iterator i = grp.begin(); i != grp.end(); ++i)
if ((*i)->name() == probe->name() && (*i)->id() == probe->id()
&& (*i)->resname() == probe->resname() && (*i)->resid() == probe->resid()
&& (*i)->segid() == probe->segid())
return(*i);
pAtom null;
return(null);
}
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\n"
"Places masses from a PSF file into the occupancy field of a PDB\n"
"\n"
"DESCRIPTION\n"
"\n"
"Places masses from a PSF file into a PDB file using the occupancy\n"
"column. This is useful for ENMs like VSA, which can account for\n"
"varying masses on the beads. The LOOS VSA tool can read masses from\n"
"the occupancy column with the -o1 option.\n"
"\n"
"Note: The psf and pdb must contain the same atoms.\n"
"\n"
//
"EXAMPLES\n"
"\n"
"psf-masses model.psf model.pdb > newmodel.pdb \n"
"\tGiven model.psf and model.pdb put the masses from the\n"
"\tpsf file in a PDB called newmodel.pdb. The other info\n"
"\tis obtained from model.pdb\n"
"\n"
"SEE ALSO\n"
"\n"
"Packages/ElasticNetworks/heavy-ca - \n"
"\tThis tool will sum the masses of a residue using\n"
"\tthe value in the occupancy field and place the total\n"
"\tmass on the CA for use in an ENM.\n"
"\n"
"\n";
return(msg);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
cerr << "Usage- psf-masses model.psf model.pdb >newmodel.pdb\n";
cerr << fullHelpMessage();
exit(0);
}
string hdr = invocationHeader(argc, argv);
AtomicGroup source = createSystem(argv[1]);
AtomicGroup target = createSystem(argv[2]);
for (AtomicGroup::iterator i = target.begin(); i != target.end(); ++i) {
pAtom match = findMatch(*i, source);
if (!match) {
cerr << "ERROR- no match found for atom " << **i << endl;
exit(-1);
}
if (!match->checkProperty(Atom::massbit)) {
cerr << "ERROR- Atom has no mass: " << *match << endl;
exit(-1);
}
(*i)->occupancy(match->mass());
}
PDB pdb = PDB::fromAtomicGroup(target);
pdb.remarks().add(hdr);
cout << pdb;
}
| 3,264
|
C++
|
.cpp
| 91
| 31.472527
| 81
| 0.661033
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,119
|
heavy-ca.cpp
|
GrossfieldLab_loos/Packages/ElasticNetworks/heavy-ca.cpp
|
/*
heavy-ca
Given a PDB where masses are stored in the occupancy field, reduce
the structure to CA's only where the mass of the CA is the sum of
the mass of all atoms in the corresponding residue...
Usage- heavy-ca selection model >output
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace loos;
using namespace std;
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\n"
"Store whole residue mass in CA occupancy field\n"
"\n"
"DESCRIPTION\n"
"\n"
"Given a PDB where masses are stored in the occupancy field, reduce\n"
"the structure to CA's only where the mass of the CA is the sum of\n"
"the mass of all atoms in the corresponding residue.\n"
"\n"
"Note: The selection string in this tool is used to decide which\n"
" residues to sum the mass of. So 'name==\"CA\"' will return\n"
" a mass of 12 in the occupancy field. \n"
"\n"
//
"EXAMPLES\n"
"\n"
"heavy-ca 'segid==\"PROT\"' model.pdb > newmodel.pdb'\n"
"\tMasses in the occupancy field of model.pdb are \n"
"\tsummed over each residue in segid PROT and placed\n"
"\ton the CA in newmodel.pdb.\n"
"\n"
"heavy-ca 'segid==\"PROT\" && !(hydrogen)' model.pdb > newmodel.pdb'\n"
"\tSame as above, but hydrogen atoms are excluded \n"
"\tfrom the summation.\n"
"\n"
"SEE ALSO\n"
"\n"
"Packages/ElasticNetworks/psf-masses - \n"
"\tThis tool will take the masses from a PSF file\n"
"\tand place them in the occupancy field of a PDB\n"
"\n"
"\n";
return(msg);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
cerr << "Usage- heavy-ca selection pdb >output\n";
cerr << fullHelpMessage();
exit(0);
}
string hdr = invocationHeader(argc, argv);
string selection(argv[1]);
AtomicGroup structure = createSystem(argv[2]);
AtomicGroup model = selectAtoms(structure, selection);
vector<AtomicGroup> residues = model.splitByResidue();
AtomicGroup heavy;
for (vector<AtomicGroup>::iterator j = residues.begin(); j != residues.end(); ++j) {
AtomicGroup grp = (*j).select(AtomNameSelector("CA"));
if (grp.empty()) {
cerr << "ERROR- could not find a CA in the following residue:\n";
cerr << *j;
exit(-1);
}
pAtom ca = grp[0];
double mass = 0.0;
for (AtomicGroup::iterator i = (*j).begin(); i != (*j).end(); ++i)
mass += (*i)->occupancy();
ca->occupancy(mass);
heavy.append(ca);
}
PDB outpdb = PDB::fromAtomicGroup(heavy);
outpdb.remarks().add(hdr);
cout << outpdb;
}
| 3,415
|
C++
|
.cpp
| 94
| 32.042553
| 86
| 0.677832
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,120
|
spring_functions.cpp
|
GrossfieldLab_loos/Packages/ElasticNetworks/spring_functions.cpp
|
/*
Spring Functions from Elastic Network Tools in LOOS
(c) 2010 Tod D. Romo, Grossfield Lab, URMC
*/
#include "spring_functions.hpp"
namespace ENM {
std::vector<std::string> splitCommaSeparatedList(const std::string& s){
std::vector<std::string> holder;
std::string::size_type prev =s.find_first_not_of(",", 0);
std::string::size_type pos = s.find_first_of(",", prev);
while (pos != std::string::npos || prev != std::string::npos){
holder.push_back(s.substr(prev, pos-prev));
prev = s.find_first_not_of(",", pos);
pos = s.find_first_of(",", prev);
}
return(holder);
}
/** Factory function for spring constants. The spring description is
* the name of the spring function with an optional comma-separated
* list of parameters to pass to it, i.e.
* distance
* distance,15.0
* hca,1,2,3,4,5
*
* Will throw in the event of an error.
*/
SpringFunction* springFactory(const std::string& spring_desc) {
std::vector<std::string> list = splitCommaSeparatedList(spring_desc);
SpringFunction *spring = 0;
if (list[0] == "distance")
spring = new DistanceCutoff;
else if (list[0] == "weighted")
spring = new DistanceWeight;
else if (list[0] == "exponential")
spring = new ExponentialDistance;
else if (list[0] == "hca" || spring_desc == "HCA")
spring = new HCA;
else if (list[0] == "constant")
spring = new ConstBonded;
else
throw(BadSpringFunction("Bad Spring Function Name"));
if (list.size() > 1) {
if (list.size() < spring->paramSize())
throw(BadSpringParameter("Too few spring parameters"));
std::vector<double> params;
for (uint i=1; i <= spring->paramSize(); ++i)
params.push_back(loos::parseStringAs<double>(list.at(i)));
spring->setParams(params);
if (!spring->validParams())
throw(BadSpringParameter("Bad Spring Parameter"));
}
return(spring);
}
// Returns a list of names for spring functions. Needs to match
// what's checked for above...
std::vector<std::string> springNames() {
std::vector<std::string> names;
names.push_back("distance");
names.push_back("weighted");
names.push_back("exponential");
names.push_back("hca");
return(names);
}
};
| 2,332
|
C++
|
.cpp
| 64
| 31.140625
| 73
| 0.642857
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,121
|
vsa.cpp
|
GrossfieldLab_loos/Packages/ElasticNetworks/vsa.cpp
|
/*
vsa
Usage:
vsa [options] subset environment model output_prefix
See:
Woodcock et al, J Chem Phys (2008) 129:214109
Haffner & Zheng, J Chem Phys (2009) 130:194111
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <limits>
#include "hessian.hpp"
#include "enm-lib.hpp"
#include "vsa-lib.hpp"
using namespace std;
using namespace loos;
using namespace ENM;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// Globals...
double normalization = 1.0;
double threshold = 1e-10;
string hdr;
string subsystem_selection, environment_selection, model_name, prefix;
int verbosity = 0;
bool debug = false;
bool occupancies_are_masses;
string psf_file;
string spring_desc;
bool nomass;
string fullHelpMessage() {
string s =
"\n"
"SYNOPSIS\n"
"\n"
"Compute the vibrational subsystem analysis version of the\n"
"anisotropic network model. (See Woodcock et al.)\n"
"\n"
"DESCRIPTION\n"
"\n"
"Computes the VSA network model given a subsystem and an\n"
"environment selection. The output consists of several different\n"
"ASCII formatted matrices (that can be read by Matlab/Octave) and\n"
"depends on whether or not masses are included in the\n"
"calculation. If debugging is turned on (--debug), then the\n"
"intermediate matrices are written out:\n"
"\tfoo_H.asc - Composite Hessian\n"
"\tfoo_Hss.asc - Subsystem Hessian\n"
"\tfoo_Hee.asc - Environment Hessian\n"
"\tfoo_Hse.asc - Subsystem-Environment Hessian\n"
"\tfoo_Heei.asc - Inverted Environment Hessian\n"
"\tfoo_Hssp.asc - Effective Subsystem Hessian\n"
"\tfoo_Ms.asc - Subsystem mass (optional)\n"
"\tfoo_Me.asc - Environment mass (optional)\n"
"\tfoo_Msp.asc - Effective subsystem mass (optional)\n"
"\tfoo_R.asc - Cholesky decomposition of Msp (optional)\n"
"\n\n"
"* Unit Subsystem Mass, Zero Environment Mass *\n\n"
"Here, the effective subsystem Hessian is created and a Singular\n"
"Value Decomposition used to solve the eigenproblem:\n"
"\tfoo_U.asc = Subsystem eigenvectors\n"
"\tfoo_s.asc = Subsystem eigenvalues\n"
"\n\n"
"* Subsystem and Environment Mass *\n\n"
"The generalized eigenvalue problem is solved creating the\n"
"following matrices:\n"
"\tfoo_s.asc = Subsystem eigenvalues (mass-weighted)\n"
"\tfoo_U.asc = Subsystem eigenvectors (mass-weighted)\n"
"\n\n"
"* Spring Constant Control *\n\n"
"The spring constant used is controlled by the --spring option.\n"
"If only the name for the spring function is given, then the default\n"
"parameters are used. Alternatively, the name may include a\n"
"comma-separated list of parameters to be passed to the spring\n"
"function, i.e. --spring=distance,15.0\n\n"
"Available spring functions:\n";
vector<string> names = springNames();
for (vector<string>::iterator i = names.begin(); i != names.end(); ++i)
s = s + "\t" + *i + "\n";
s +=
"\n\n"
"* Mass Control *\n\n"
"VSA, by default, assumes that masses will be present. These can\n"
"come from one of two sources. If \"--psf foo.psf\" is given,\n"
"then the masses will be assigned using the \"foo.psf\" file. This\n"
"assumes that the atoms are in the same order between the PSF file\n"
"and the structure file given on the command line. Alternatively,\n"
"the occupancy field of the PDB can be used with the\n"
"\"--occupancies 1\" option. See the psf-masses tool for one way to\n"
"copy masses into a PDB's occupancies.\n"
"\n"
"To disable masses (i.e. use unit masses for the subsystem and\n"
"zero masses for the environment), use the \"--nomass 1\" option.\n"
"\n\n"
"EXAMPLES \n\n"
"\n"
"vsa --occupancies 1 foo.pdb 'segid == \"TRAN\" && name == \"CA\"'\\\n"
" 'segid != \"TRAN\" && name == \"CA\"' foo_vsa\n"
"\tCompute the VSA for a transmembrane region based on segid with the\n"
"\tmasses stored in the occupancy field of the PDB. Here the enviroment\n"
"\tcontains all other CA's in the system.\n"
"\n"
"vsa --psf foo.psf foo.pdb \"`cat selection` && name == 'CA'\" \\\n"
" \"not (`cat selection`) && name == 'CA'\" foo_vsa\n"
"\tCompute the VSA for a transmembrane region where the selection\n"
"\tis stored in a file and masses are taken from a PSF file.\n"
"\n"
"vsa --nomass 1 foo.pdb 'name == \"CA\"' 'name =~ \"^(C|O|N)$\"' foo_vsa\n"
"\tCompute the mass-less VSA with CAs as the subsystem and all other\n"
"\tbackbone atoms as the environment.\n"
"\n"
"vsa --nomass 1 --spring hca foo.pdb 'name == \"CA\"' 'name =~ \"^(C|O|N)$\"' foo_vsa\n"
"\tThe same example as above, but using the HCA spring constants.\n";
return(s);
}
// @cond TOOLS_INTERNAL
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("psf", po::value<string>(&psf_file), "Take masses from the specified PSF file")
("debug", po::value<bool>(&debug)->default_value(false), "Turn on debugging (output intermediate matrices)")
("occupancies", po::value<bool>(&occupancies_are_masses)->default_value(false), "Atom masses are stored in the PDB occupancy field")
("nomass", po::value<bool>(&nomass)->default_value(false), "Disable mass as part of the VSA solution")
("spring,S", po::value<string>(&spring_desc)->default_value("distance"), "Spring method and arguments");
}
string print() const {
ostringstream oss;
oss << boost::format("psf='%s', debug=%d, occupancies=%d, nomass=%d, spring='%s'")
% psf_file
% debug
% occupancies_are_masses
% nomass
% spring_desc;
return(oss.str());
}
};
// @endcond
int main(int argc, char *argv[]) {
hdr = invocationHeader(argc, argv);
// Build up options
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::ModelWithCoords* mopts = new opts::ModelWithCoords;
ToolOptions* topts = new ToolOptions;
opts::RequiredArguments* ropts = new opts::RequiredArguments;
ropts->addArgument("subsystem", "subsystem-selection");
ropts->addArgument("environment", "environment-selection");
ropts->addArgument("prefix", "output-prefix");
opts::AggregateOptions options;
options.add(bopts).add(mopts).add(topts).add(ropts);
if (!options.parse(argc, argv))
exit(-1);
// Extract values
AtomicGroup model = mopts->model;
verbosity = bopts->verbosity;
subsystem_selection = ropts->value("subsystem");
environment_selection = ropts->value("environment");
prefix = ropts->value("prefix");
// Ugly way of handling multiple methods for getting masses into the equation...
if (verbosity > 0)
cerr << "Assigning masses...\n";
// Get masess from somewhere, or rely on the defaults provided by
// Atom (i.e. should be 1)
if (! psf_file.empty())
massFromPSF(model, psf_file);
else if (occupancies_are_masses)
massFromOccupancy(model);
else if (!nomass)
cerr << "WARNING- using default masses\n";
// Partition the model for building the composite Hessian
AtomicGroup subsystem = selectAtoms(model, subsystem_selection);
AtomicGroup environment = selectAtoms(model, environment_selection);
AtomicGroup composite = subsystem + environment;
if (verbosity > 1) {
cerr << "Subsystem size is " << subsystem.size() << endl;
cerr << "Environment size is " << environment.size() << endl;
}
// Determine which kind of scaling to apply to the Hessian...
SpringFunction* spring = 0;
spring = springFactory(spring_desc);
SuperBlock* blocker = new SuperBlock(spring, composite);
VSA vsa(blocker, subsystem.size());
vsa.prefix(prefix);
vsa.meta(hdr);
vsa.debugging(debug);
vsa.verbosity(verbosity);
if (!nomass) {
DoubleMatrix M = getMasses(composite);
vsa.setMasses(M);
}
vsa.solve();
writeAsciiMatrix(prefix + "_U.asc", vsa.eigenvectors(), hdr, false);
writeAsciiMatrix(prefix + "_s.asc", vsa.eigenvalues(), hdr, false);
// Be good...
delete spring;
delete blocker;
}
| 8,979
|
C++
|
.cpp
| 212
| 38.29717
| 138
| 0.691256
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,122
|
gnm.cpp
|
GrossfieldLab_loos/Packages/ElasticNetworks/gnm.cpp
|
/*
gnm
Computes the gaussian normal mode (elastic network model)
decomposition for a structure. Does this by building the Kirchoff
matrix given a PDB and a selection, then computes the SVD of the
matrix and finally the pseudo-inverse.
Usage:
gnm [selection-string] radius model-name output-prefix
Examples:
gnm 'resid >= 10 && resid <= 50 && name == "CA"' 7.0 foo.pdb foo
This will create the following files:
foo_K.asc == Kirchoff matrix
foo_U.asc == Left singular vectors
foo_s.asc == singular values
foo_V.asc == Right singular vectors
foo_Ki.asc == Pseudo-inverse of K
Notes:
o The default selection (if none is specified) is to pick CA's
o The output is in ASCII format suitable for use with Matlab/Octave/Gnuplot
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
using namespace std;
using namespace loos;
namespace po = boost::program_options;
typedef Math::Matrix<double, Math::ColMajor> Matrix;
// Globals... Fah!
string selection;
string model_name;
string prefix;
double cutoff;
void fullHelp() {
//string msg =
cout << "\n"
"\n"
"SYNOPSIS\n"
"\n"
"Compute the normal modes of a guassian network model\n"
"\n"
"DESCRIPTION\n"
"Computes the gaussian normal mode analysis of an ENM\n"
"This is done by building the Kirchoff matrix given a PDB\n"
"and a selection, then computing the SVD of the matrix and\n"
"finally computing the pseudo-inverse.\n"
"See: Bahar, et al., Folding and Design 2, 173-181, (1997).\n"
"\n"
"This will create the following files:\n"
"\tfoo_K.asc - Kirchoff matrix\n"
"\tfoo_U.asc - Left singular vectors\n"
"\tfoo_s.asc - singular values\n"
"\tfoo_V.asc - Right singular vectors\n"
"\tfoo_Ki.asc - Pseudo-inverse of K\n"
"\n"
"Notes:\n"
"- The default selection (if none is specified) is to pick CA's\n"
"- The output is ASCII format suitable for use with Matlab/Octave/Gnuplot\n"
//
"\n"
"EXAMPLES\n"
"\n"
"gnm -c8.2 -s 'resid >= 10 && resid <= 50 && name == \"CA\"' model.pdb foo\n"
"\tCompute the GNM of model.pdb for residues #10 through #50 with\n"
"\tan 8.2 Angstrom cutoff i.e. construct contacts using only the CA's\n"
"\tthat are within 8.2 Angstroms. Write out the files to foo_X.asc\n"
"\t\n"
"SEE ALSO\n"
"\n"
"Packages/ElasticNetworks/anm - \n"
"The anisotropic version of this tool. Here eigenvectors predicting\n"
"the direction of movements are written out as well.\n"
"\t\n"
"Packages/ElasticNetworks/vsa - \n"
"This is an extension of the ANM method mentioned above that splits\n"
"the calculation into two parts - a subsystem and an environment.\n"
"These eigendecompositions of these two parts are performed separately\n"
"and the environment can then be 'subtracted' off the subsystem.\n"
"\n";
}
void parseOptions(int argc, char *argv[]) {
try {
po::options_description generic("Allowed options");
generic.add_options()
("help", "Produce this help message")
("fullhelp", "Get extended help")
("selection,s", po::value<string>(&selection)->default_value("name == 'CA'"), "Which atoms to use for the network")
("cutoff,c", po::value<double>(&cutoff)->default_value(7.0), "Cutoff distance for node contact");
po::options_description hidden("Hidden options");
hidden.add_options()
("model", po::value<string>(&model_name), "Model filename")
("prefix", po::value<string>(&prefix), "Output prefix");
po::options_description command_line;
command_line.add(generic).add(hidden);
po::positional_options_description p;
p.add("model", 1);
p.add("prefix", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(command_line).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help") || vm.count("fullhelp") || !(vm.count("model") && vm.count("prefix"))) {
cerr << "Usage- gnm [options] model-name output-prefix\n";
cerr << generic;
if (vm.count("fullhelp"))
fullHelp();
exit(-1);
}
}
catch(exception& e) {
cerr << "Error - " << e.what() << endl;
exit(-1);
}
}
// This is the Kirchoff normalization constant (see Bahar, Atilgan,
// and Erman. Folding & Design 2:173)
double normalization = 1.0;
Matrix kirchoff(AtomicGroup& group, const double cutoff) {
int n = group.size();
Matrix M(n, n);
double r2 = cutoff * cutoff;
for (int j=1; j<n; j++)
for (int i=0; i<j; i++)
if (group[i]->coords().distance2(group[j]->coords()) <= r2)
M(i, j) = M(j, i) = -normalization;
for (int j=0; j<n; j++) {
double sum = 0;
for (int i=0; i<n; i++) {
if (i == j)
continue;
sum += M(j, i);
}
M(j, j) = -sum;
}
return(M);
}
int main(int argc, char *argv[]) {
string header = invocationHeader(argc, argv);
parseOptions(argc, argv);
AtomicGroup model = createSystem(model_name);
AtomicGroup subset = selectAtoms(model, selection);
cout << boost::format("Selected %d atoms from %s\n") % subset.size() % model_name;
Timer<WallTimer> timer;
cerr << "Computing Kirchoff matrix - ";
timer.start();
Matrix K = kirchoff(subset, cutoff);
timer.stop();
cerr << "done.\n" << timer << endl;
writeAsciiMatrix(prefix + "_K.asc", K, header);
boost::tuple<DoubleMatrix, DoubleMatrix, DoubleMatrix> result = svd(K);
Matrix U = boost::get<0>(result);
Matrix S = boost::get<1>(result);
Matrix Vt = boost::get<2>(result);
uint n = S.rows();
reverseRows(S);
reverseColumns(U);
reverseRows(Vt);
// Write out the LSV (or eigenvectors)
writeAsciiMatrix(prefix + "_U.asc", U, header);
writeAsciiMatrix(prefix + "_s.asc", S, header);
// Now go ahead and compute the pseudo-inverse...
// Vt = Vt * diag(1./diag(S))
// Remember, Vt is stored col-major but transposed, hence the
// somewhat funky indices...
//
// Note: We have to toss the first term (see Chennubhotla et al (Phys Biol 2(2005:S173-S180))
for (uint i=1; i<n; i++) {
double s = 1.0/S[i];
for (uint j=0; j<n; j++)
Vt(i, j) *= s;
}
Matrix Ki = MMMultiply(Vt, U, true, true);
writeAsciiMatrix(prefix + "_Ki.asc", Ki, header);
}
| 7,202
|
C++
|
.cpp
| 189
| 33.740741
| 121
| 0.665804
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,123
|
enm-lib.cpp
|
GrossfieldLab_loos/Packages/ElasticNetworks/enm-lib.cpp
|
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "enm-lib.hpp"
using namespace std;
using namespace loos;
namespace ENM {
// Map masses from one group onto another... Minimal error checking...
void copyMasses(AtomicGroup& target, const AtomicGroup& source) {
if (target.size() != source.size()) {
cerr << "ERROR- groups have different sizes in copyMasses... (maybe your PSF doesn't match the model?)\n";
exit(-1);
}
for (uint i=0; i<target.size(); ++i) {
if (source[i]->name() != target[i]->name()) {
cerr << "ERROR- atom mismatch at position " << i << endl;
exit(-1);
}
target[i]->mass(source[i]->mass());
}
}
// Copy the masses from a PSF onto a group
void massFromPSF(AtomicGroup& grp, const string& name) {
AtomicGroup psf = createSystem(name);
copyMasses(grp, psf);
}
// The masses are stored in the occupancy field of a PDB...
void massFromOccupancy(AtomicGroup& grp) {
for (AtomicGroup::iterator i = grp.begin(); i != grp.end(); ++i)
(*i)->mass((*i)->occupancy());
}
// Build the 3n x 3n diagonal mass matrix for a group
DoubleMatrix getMasses(const AtomicGroup& grp) {
uint n = grp.size();
DoubleMatrix M(3*n,3*n);
for (uint i=0, k=0; i<n; ++i, k += 3) {
M(k,k) = grp[i]->mass();
M(k+1,k+1) = grp[i]->mass();
M(k+2,k+2) = grp[i]->mass();
}
return(M);
}
void ElasticNetworkModel::buildHessian() {
uint n = blocker_->size();
loos::DoubleMatrix H(3*n,3*n);
for (uint i=1; i<n; ++i) {
for (uint j=0; j<i; ++j) {
loos::DoubleMatrix B = blocker_->block(j, i);
for (uint x = 0; x<3; ++x)
for (uint y = 0; y<3; ++y) {
H(i*3 + y, j*3 + x) = -B(y, x);
H(j*3 + x, i*3 + y) = -B(x ,y);
}
}
}
// Now handle the diagonal...
for (uint i=0; i<n; ++i) {
loos::DoubleMatrix B(3,3);
for (uint j=0; j<n; ++j) {
if (j == i)
continue;
for (uint x=0; x<3; ++x)
for (uint y=0; y<3; ++y)
B(y,x) += H(j*3 + y, i*3 + x);
}
for (uint x=0; x<3; ++x)
for (uint y=0; y<3; ++y)
H(i*3 + y, i*3 + x) = -B(y,x);
}
hessian_ = H;
}
};
| 3,068
|
C++
|
.cpp
| 85
| 30.270588
| 112
| 0.596396
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,124
|
gridscale.cpp
|
GrossfieldLab_loos/Packages/DensityTools/gridscale.cpp
|
/*
gridscale.cpp
Applies a constant scaling to a grid...
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <DensityGrid.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
if (argc != 2) {
cerr << "Usage- gridscale scale-value <in-grid >out-grid\n";
cerr << "\nScales the density values in the grid by the specified value.\n";
cerr << "Requires a double-precision floating point grid.\n";
exit(-1);
}
double konst = strtod(argv[1], 0);
DensityGrid<double> grid;
cin >> grid;
grid.scale(konst);
grid.addMetadata(hdr);
cout << grid;
}
| 1,515
|
C++
|
.cpp
| 40
| 34.85
| 80
| 0.745205
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,125
|
contained.cpp
|
GrossfieldLab_loos/Packages/DensityTools/contained.cpp
|
/*
contained.cpp
Tracks the number of atoms within a blob over time...
usage:
contained model trajectory selection grid
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/tuple/tuple.hpp>
#include <limits>
#include <list>
#include <DensityGrid.hpp>
#include <DensityTools.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\n"
"\tCount the number of atoms that are within density for an int-grid.\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool generates a time-series representing the number of atoms\n"
"that are within density for each frame in a trajectory. Density is\n"
"defined as any non-zero grid element.\n"
"\nEXAMPLES\n"
"\tblobid --threshold 1 <foo.grid >foo_id.grid\n"
"\tpick_blob_blob --model foo.pdb --selection 'resid == 65' <foo_id.grid >foo_picked.grid\n"
"\tcontained --selection 'name == \"OH2\"' foo_picked.grid\n"
"This example first segments (thresholds) the density at 1.0, and then finds the blob\n"
"closest to residue 65. The number of water oxygens at each time-step in the trajectory\n"
"that are within this blob near residue 65 is written out.\n"
"\n"
"NOTES\n\n"
"\tThis tool only works with integer grids (i.e. a grid that has already been\n"
"segmented into blobs), NOT raw density.\n"
"SEE ALSO\n\n"
"\tblobid, pick_blob\n";
return(msg);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions *basic_opts = new opts::BasicOptions(fullHelpMessage());
opts::BasicSelection *basic_selection = new opts::BasicSelection;
opts::TrajectoryWithFrameIndices *basic_traj = new opts::TrajectoryWithFrameIndices;
opts::RequiredArguments *ropts = new opts::RequiredArguments;
ropts->addArgument("grid", "grid-name");
opts::AggregateOptions options;
options.add(basic_opts).add(basic_selection).add(basic_traj).add(ropts);
if (!options.parse(argc, argv)) {
exit(0);
}
AtomicGroup model = basic_traj->model;
pTraj traj = basic_traj->trajectory;
AtomicGroup subset = selectAtoms(model, basic_selection->selection);
vector<uint> frames = basic_traj->frameList();
cout << "# " << hdr << endl;
cout << "# frame n\n";
DensityGrid<int> grid;
string grid_name = ropts->value("grid");
ifstream ifs(grid_name.c_str());
if (!ifs) {
cerr << "Error- cannot open " << grid_name << endl;
exit(-1);
}
ifs >> grid;
for (vector<uint>::iterator i = frames.begin(); i != frames.end(); ++i) {
traj->readFrame(*i);
traj->updateGroupCoords(subset);
long n = 0;
for (AtomicGroup::iterator j = subset.begin(); j != subset.end(); ++j) {
DensityGridpoint point = grid.gridpoint((*j)->coords());
if (!grid.inRange(point))
continue;
if (grid(point) != 0)
++n;
}
cout << *i << " " << n << endl;
}
}
| 3,796
|
C++
|
.cpp
| 98
| 34.969388
| 96
| 0.702592
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,126
|
water-count.cpp
|
GrossfieldLab_loos/Packages/DensityTools/water-count.cpp
|
/*
water-count.cpp
usage:
water-count prefix >output.asc
Description:
Counts the number of waters that are inside the protein at each
timepoint and writes this out as a vector. In other words, it
just sums the rows for each column of the water matrix.
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
using namespace std;
using namespace loos;
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
if (argc != 2) {
cerr << "Usage - water-count prefix >output.asc\n";
cerr << "\nGiven a matrix of water classifications from water-inside,\n";
cerr << "counts the number of waters that are inside the\n";
cerr << "protein at each timepoint and writes this out as a 1-column\n";
cerr << "matrix.\n\n";
cerr << "See also water-inside.\n";
exit(-1);
}
string prefix(argv[1]);
Math::Matrix<double> V;
readAsciiMatrix(prefix + ".vol", V);
Math::Matrix<int> M;
readAsciiMatrix(prefix + ".asc", M);
uint m = M.rows();
uint n = M.cols();
if (V.rows() != M.cols()) {
cerr << "ERROR - mismatch in volume and water matrix\n";
exit(-10);
}
cout << "# " << hdr << endl;
cout << "# frame\tcount\tvolume\n";
for (uint i=0; i<n; ++i) {
long cnt = 0;
for (uint j=0; j<m; ++j)
cnt += M(j,i);
cout << i << "\t" << cnt << "\t" << V(i,0) << endl;
}
}
| 2,234
|
C++
|
.cpp
| 60
| 33.383333
| 77
| 0.68345
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,127
|
water-hist.cpp
|
GrossfieldLab_loos/Packages/DensityTools/water-hist.cpp
|
/*
water-hist.cpp
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <loos.hpp>
#include <DensityGrid.hpp>
#include <water-hist-lib.hpp>
#include <DensityTools.hpp>
#include <DensityOptions.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
// @cond TOOLS_INTERAL
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"Generate a 3D histogram of internal waters for a trajectory\n"
"\n"
"DESCRIPTION\n"
"\n"
"\twater-hist generates a 3-dimensional histogram for a given selection\n"
"over the coarse of a trajectory. This tool was originally designed\n"
"for tracking water internal to a membrane protein, however any group\n"
"of atoms can be substituted for \"water\" (e.g. ligand) and \"protein\".\n"
"\n"
"The tool first requires that you specify what atoms will be integrated.\n"
"This is the \"water\" selection. Next, you need to define what is considered\n"
"\"internal\" to the protein, filtering which waters will be considered.\n"
"This is typically done by defining a \"protein\" selection and a mode for\n"
"filtering: axis, box, radius, or grid. The axis mode takes the first\n"
"principal component for the protein and picks all waters that are within\n"
"a given radius of that axis. The box mode uses the bounding box for the\n"
"protein selection (i.e. any water that is within this box). The radius\n"
"mode picks waters that are within a given radius of any protein atom.\n"
"Finally, the grid mode takes a grid mask and picks any waters that are\n"
"within the masked gridpoints.\n"
"\n"
"The resultant density histogram can be scaled by an estimate of the\n"
"bulk solvent density by using the --scale option along with either\n"
"--bulk or --brange. The former uses the average density for any Z-plane\n"
"that is sufficiently far from 0 (i.e. |Z| >= k) whereas the latter explicitly\n"
"takes a Z-range to average over. Note that you must explicitly rescale\n"
"the density by using the --scale=1 option, otherwise the estimated bulk\n"
"solvent density will be printed only.\n"
"\n"
"For visualization purposes, it you are using a membrane-protein system\n"
"and the axis mode for filtering out waters, you may end up with a plug\n"
"of bulk water at the protein/solvent interface. To make it more clear\n"
"that there is a layer of bulk solvent, use the --bulked option. This\n"
"adds water back into the histogram based on the Z-coordinate and the\n"
"bounding box of the protein (with an optional padding)\n"
"\n"
"Water-hist treats each atom as a single grid point (based on nearest)\n"
"grid-coordinate. This means that even though a water should cover\n"
"multiple grid-points based on the grid resolution and water radius,\n"
"only one grid point will be used. For visualization then, the\n"
"grid should be smoothed out. This can be done via the \"gridgauss\"\n"
"tool which convolves the grid with a gaussian kernel. Finally,\n"
"the grid needs to be converted to an X-Plor electron density format\n"
"using \"grid2xplor\". This can then be read into PyMol, VMD, or other\n"
"visualization tools.\n"
"\n"
"These tools can be chained together via Unix pipes,\n"
" water-hist model.pdb model.dcd | gridgauss 10 3 1 1 | grid2xplor >water.xplor\n"
"\n"
"For more details about available options, see the help information for the\n"
"respective tool.\n"
"\n"
"\n"
"EXAMPLES\n"
"\n"
"\twater-hist --radius=15 --bulk=25 --scale=1 b2ar.pdb b2ar.dcd | gridgauss 10 3 1 1 |\\\n"
"\t grid2xplor >b2ar_water.xplor\n"
"Internal water for a GPCR with a bulk estimate, converted to Xplor EDM.\n"
"\n"
"\twater-hist --bulk=25 --scale=1 --bulked=20,-25:30 b2ar.pdb b2ar.dcd |\\\n"
"\t gridgauss 4 2 | grid2xplor >b2ar_water.xplor\n"
"Internal water for a GPCR with the bulk solvent layer added back, converted to Xplor EDM.\n"
"The bulk water is for any water with Z < -25 or Z > 30 and within the bounding box\n"
"of the protein with a 20 angstrom pad.\n"
"\n"
"\twater-hist --radius=20 --prot='resid > 10 && resid < 25' --mode=radius |\\\n"
"\t gridgauss 4 2 | grid2xplor >binding.xplor\n"
"All water within a given radius of a binding pocket, converted to Xplor EDM.\n"
"\n"
"\twater-hist --gridres=0.5 b2ar.pdb b2ar.dcd | gridgauss 10 3 1 1 |\\\n"
"\t grid2xplor >b2ar_water.xplor\n"
"Higher resolution grid, converted to Xplor EDM.\n"
"\n"
"\twater-hist --prot='resname == \"PEGL\"' --water='resname === \"PEGL\"'\\\n"
"\t --mode=box membrane.pdb membrane.dcd >membrane.grid\n"
"All lipid head-group density, written as LOOS grid.\n"
"\n"
"\twater-hist --water='resname == \"CAU\"' --mode=box b2ar.pdb b2ar.dcd >b2ar.grid\n"
"Ligand (carazolol) Density, written as LOOS grid.\n"
"\n"
"\twater-hist b2ar.pdb b2ar.dcd | gridgauss 10 3 1 1 | gridautoscale | grid2xplor >b2ar.xplor\n"
"Smoothed grid, automatically scaled so that a density of 1.0 is bulk water.\n"
"This is specific to membrane systems where the membrane normal is parallel to\n"
"the Z-axis.\n"
"\n"
"NOTES\n"
"\n"
"When using the --bulked option, the extents of the grid are adjusted to be\n"
"the bounding box of the protein plus the bulked pad PLUS the global pad.\n"
"Be careful not to make the volume too large.\n"
"\n"
"SEE ALSO\n"
"\tgridgauss, grid2xplor, gridstat, gridslice, blobid, pick_blob, gridautoscale\n";
return(msg);
}
class WaterHistogramOptions : public opts::OptionsPackage {
public:
WaterHistogramOptions() :
grid_resolution(1.0),
count_empty_voxels(false),
rescale_density(false),
bulk_zclip(0.0),
bulk_zmin(0.0), bulk_zmax(0.0)
{ }
void addGeneric(po::options_description& opts) {
opts.add_options()
("gridres", po::value<double>(&grid_resolution)->default_value(grid_resolution), "Grid resolution")
("empty", po::value<bool>(&count_empty_voxels)->default_value(count_empty_voxels), "Count empty voxels in bulk density estimate")
("bulk", po::value<double>(&bulk_zclip)->default_value(bulk_zclip), "Bulk water is defined as |Z| >= k")
("brange", po::value<string>(), "Bulk water (--brange a,b) is defined as a <= z < b")
("scale", po::value<bool>(&rescale_density)->default_value(rescale_density), "Scale density by bulk estimate")
("clamp", po::value<string>(), "Clamp the bounding box [(x,y,z),(x,y,z)]");
}
bool postConditions(po::variables_map& map) {
if (map.count("clamp")) {
GCoord clamp_min, clamp_max;
string s = map["clamp"].as<string>();
stringstream ss(s);
if (!(ss >> clamp_min)) {
cerr << "Error- cannot parse lower bounds for box-clamp\n";
return(false);
}
clamped_box.push_back(clamp_min);
int c = ss.get();
if (c != ',') {
cerr << "Error- cannot parse box-clamp\n";
return(false);
}
if (!(ss >> clamp_max)) {
cerr << "Error- cannot parse upper bounds for box-clamp\n";
return(false);
}
clamped_box.push_back(clamp_max);
cerr << "Warning- clamping grid to " << clamp_min << " -> " << clamp_max << endl;
}
if (map.count("brange")) {
string s = map["brange"].as<string>();
istringstream iss(s);
if (!(iss >> bulk_zmin)) {
cerr << "Error- brange format is low,high\n";
return(false);
}
char c;
iss >> c;
if (c != ',') {
cerr << "Error- brange format is low,high\n";
return(false);
}
if (!(iss >> bulk_zmax)) {
cerr << "Error- brange format is low,high\n";
return(false);
}
}
return(true);
}
string print() const {
ostringstream oss;
oss << boost::format("gridres=%f, empty=%d, bulk_zclip=%d, scale=%d, bulk_zmin=%d, bulk_zmax=%d")
% grid_resolution
% count_empty_voxels
% bulk_zclip
% rescale_density
% bulk_zmin
% bulk_zmax;
if (!clamped_box.empty())
oss << boost::format(", clamp=[%s,%s]")
% clamped_box[0]
% clamped_box[1];
return(oss.str());
}
public:
double grid_resolution;
bool count_empty_voxels;
bool rescale_density;
double bulk_zclip;
double bulk_zmin, bulk_zmax;
vector<GCoord> clamped_box;
};
// @endcond
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
// Build up possible options
opts::BasicOptions* basopts = new opts::BasicOptions(fullHelpMessage());
opts::TrajectoryWithFrameIndices* tropts = new opts::TrajectoryWithFrameIndices;
opts::BasicWater* watopts = new opts::BasicWater;
WaterHistogramOptions *xopts = new WaterHistogramOptions;
opts::AggregateOptions options;
options.add(basopts).add(tropts).add(watopts).add(xopts);
if (!options.parse(argc, argv))
exit(-1);
AtomicGroup model = tropts->model;
pTraj traj = tropts->trajectory;
vector<uint> indices = tropts->frameList();
AtomicGroup protein = selectAtoms(model, watopts->prot_string);
AtomicGroup water = selectAtoms(model, watopts->water_string);
if (basopts->verbosity >= 1)
cerr << "Filter(s): " << watopts->filter_func->name() << endl;
// Handle rescaling density by using a bulk-water density estimator
BulkEstimator* est;
if (xopts->rescale_density) {
// Double-check the clip
traj->readFrame(indices[0]);
traj->updateGroupCoords(protein);
vector<GCoord> bdd = protein.boundingBox();
if (xopts->bulk_zclip != 0.0) {
if (xopts->bulk_zclip <= bdd[1].z())
cerr << "***WARNING: the z-clip for bulk solvent overlaps the protein***\n";
ZClipEstimator* myest = new ZClipEstimator(water, traj, indices, xopts->bulk_zclip, xopts->grid_resolution);
myest->countZero(xopts->count_empty_voxels);
est = myest;
} else if (xopts->bulk_zmin != 0.0 || xopts->bulk_zmax != 0.0) {
ZSliceEstimator* myest = new ZSliceEstimator(water, traj, indices, xopts->bulk_zmin, xopts->bulk_zmax, xopts->grid_resolution);
est = myest;
} else
est = new NullEstimator();
} else
est = new NullEstimator();
cerr << *est << endl;
WaterHistogrammer wh(protein, water, est, watopts->filter_func);
if (!xopts->clamped_box.empty()) {
wh.setGrid(xopts->clamped_box[0]-watopts->pad, xopts->clamped_box[1]+watopts->pad, xopts->grid_resolution);
} else
wh.setGrid(traj, indices, xopts->grid_resolution, watopts->pad);
wh.accumulate(traj, indices);
long ob = wh.outOfBounds();
if (ob)
cerr << "***WARNING*** There were " << ob << " out of bounds waters\n";
DensityGrid<double> grid = wh.grid();
cerr << boost::format("Grid = %s x %s @ %s\n") % grid.minCoord() % grid.maxCoord() % grid.gridDims();
if (xopts->rescale_density) {
double d = est->bulkDensity();
double s = est->stdDev(d);
cerr << boost::format("Bulk density estimate = %f, std = %f\n") % d % s;
if (xopts->rescale_density) {
cerr << "Rescaling grid by bulk estimate...\n";
grid.scale(1.0 / d);
stringstream ss;
ss << boost::format("water-hist: bulk density estimate = %f, std = %f") % d % s;
grid.addMetadata(ss.str());
}
}
grid.addMetadata(hdr);
grid.addMetadata(vectorAsStringWithCommas(options.print()));
cout << grid;
}
| 12,393
|
C++
|
.cpp
| 279
| 39.422939
| 135
| 0.669322
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,128
|
grid2xplor.cpp
|
GrossfieldLab_loos/Packages/DensityTools/grid2xplor.cpp
|
/*
grid2xplor.cpp
Converts a grid (with a number of types) into an Xplor map...
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <DensityGrid.hpp>
#include <xplor-edm-writer.hpp>
namespace opts = loos::OptionsFramework;
namespace po = boost::program_options;
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
// @cond TOOLS_INTERNAL
enum GridType { CHAR, INT, FLOAT, DOUBLE };
GridType gtype;
double scaling;
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\n"
"\tConvert a LOOS grid into an ASCII XPLOR/CNS electron density map\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool converts a LOOS density grid into an XPLOR/CNS formatted electron density map\n"
"that can be use for visualization in PyMol, VMD, Coot, etc. By default, the grid is\n"
"assumed to contain double-precision floating point data (i.e. what is normally written\n"
"out by the various LOOS tools). Different data types can be converted by specifying\n"
"what the grid contains on the command-line.\n"
"\nEXAMPLES\n"
"\tgrid2xplor <foo.grid >foo.xplor\n"
"This converts a typical LOOS grid into an XPLOR density map\n\n"
"\tgrid2xplor --type int <foo_id.grid >foo.xplor\n"
"This converts an int-grid (from blobid, for example) into a density map\n";
return(msg);
}
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("type", po::value<string>(&type)->default_value("double"), "Set the grid type (char, int, float, double)")
("scale", po::value<double>(&scaling)->default_value(1.0), "Scale the grid data");
}
bool postConditions(po::variables_map& map) {
if (type == "double")
gtype = DOUBLE;
else if (type == "float")
gtype = FLOAT;
else if (type == "int")
gtype = INT;
else if (type == "char")
gtype = CHAR;
else {
cerr << "Error- unknown grid type " << type << endl;
return(false);
}
return(true);
}
string help() const {
return(" <foo.grid >foo.xplor");
}
string print() const {
ostringstream oss;
oss << boost::format("type='%s',scale='%f'") % type % scaling;
return(oss.str());
}
private:
string type;
};
template<typename T>
DensityGrid<double> scaleGrid(DensityGrid<T>& g, const double scale) {
DensityGridpoint dims = g.gridDims();
long k = dims[0] * dims[1] * dims[2];
DensityGrid<double> out(g.minCoord(), g.maxCoord(), g.gridDims());
for (long i = 0; i<k; i++)
out(i) = g(i) * scale;
out.metadata(g.metadata());
return(out);
}
// @endcond
int main(int argc, char *argv[]) {
string header = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
ToolOptions* topts = new ToolOptions();
opts::AggregateOptions options;
options.add(bopts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
DensityGrid<double> edm;
if (gtype == CHAR) {
DensityGrid<char> grid;
cin >> grid;
edm = scaleGrid(grid, scaling);
} else if (gtype == INT) {
DensityGrid<int> grid;
cin >> grid;
edm = scaleGrid(grid, scaling);
} else if (gtype == FLOAT) {
DensityGrid<float> grid;
cin >> grid;
edm = scaleGrid(grid, scaling);
} else if (gtype == DOUBLE) {
DensityGrid<double> grid;
cin >> grid;
edm = scaleGrid(grid, scaling);
} else {
cerr << "ERROR- bad grid type internally...\n";
exit(-2);
}
edm.addMetadata(header);
GCoord min = edm.minCoord();
GCoord max = edm.maxCoord();
DensityGridpoint dim = edm.gridDims();
cerr << "Read in a grid of size " << dim << endl;
cerr << "Grid range is from " << min << " to " << max << endl;
writeXplorEDM<double>(cout, edm);
}
| 4,717
|
C++
|
.cpp
| 136
| 30.875
| 113
| 0.684977
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,129
|
water-autocorrel.cpp
|
GrossfieldLab_loos/Packages/DensityTools/water-autocorrel.cpp
|
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2014, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
if (argc == 1) {
cerr << "Usage- " << argv[0] << " water_matrix [max-t] >output.asc\n";
exit(-1);
}
int k = 1;
string matname(argv[k++]);
uint max_t = 0;
if (k != argc)
max_t = strtoul(argv[k++], 0, 10);
Math::Matrix<int> M;
cerr << "Reading matrix...\n";
readAsciiMatrix(matname, M);
uint m = M.rows();
uint n = M.cols();
if (max_t == 0)
max_t = n/10;
cerr << boost::format("Water matrix is %d x %d\n") % m % n;
cerr << "Processing- ";
vector< TimeSeries<double> > waters;
for (uint j=0; j<m; ++j) {
if (j % 250 == 0)
cerr << '.';
vector<double> tmp(n, 0);
bool flag = false;
for (uint i=0; i<n; ++i) {
tmp[i] = M(j, i);
if (tmp[i])
flag = true;
}
if (flag) {
TimeSeries<double> wtmp(tmp);
waters.push_back(wtmp.correl(max_t));
}
}
uint nwaters = waters.size();
cerr << boost::format(" done\nFound %d unique waters inside\n") % nwaters;
cout << "# " << hdr << endl;
for (uint j=0; j<max_t; ++j) {
vector<double> tmp(nwaters, 0);
for (uint i=0; i<nwaters; ++i)
tmp[i] = waters[i][j];
dTimeSeries dtmp(tmp);
cout << j << '\t' << dtmp.average() << '\t' << dtmp.stdev() << '\t' << dtmp.sterr() << endl;
}
}
| 2,244
|
C++
|
.cpp
| 66
| 30.121212
| 96
| 0.637332
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,130
|
blob_stats.cpp
|
GrossfieldLab_loos/Packages/DensityTools/blob_stats.cpp
|
/*
blob_stats.cpp
Gather statistics on blobs...
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <boost/tuple/tuple.hpp>
#include <algorithm>
#include <sstream>
#include <limits>
#include <DensityGrid.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
int countBlobs(const DensityGrid<int>& grid) {
DensityGridpoint dims = grid.gridDims();
long k = dims[0] * dims[1] * dims[2];
int n = 0;
for (long i=0; i<k; i++)
if (grid(i) > n)
n = grid(i);
return(n);
}
vector<int> sizeBlobs(const DensityGrid<int>& grid) {
int n = countBlobs(grid);
vector<int> sizes(n+1, 0);
DensityGridpoint dims = grid.gridDims();
long k = dims[0] * dims[1] * dims[2];
for (long i=0; i<k; i++)
sizes[grid(i)] += 1;
return(sizes);
}
vector<GCoord> blobCentroids(const int n, const DensityGrid<int>& grid) {
vector<GCoord> centers(n+1, GCoord(0,0,0));
vector<int> counts(n+1, 0);
DensityGridpoint dims = grid.gridDims();
for (int k=0; k<dims[2]; k++)
for (int j=0; j<dims[1]; j++)
for (int i=0; i<dims[0]; i++) {
DensityGridpoint point(i,j,k);
GCoord u = grid.gridToWorld(point);
int id = grid(point);
centers[id] += u;
counts[id] += 1;
}
for (int i=0; i<= n; i++)
centers[i] /= counts[i];
return(centers);
}
int main(int argc, char *argv[]) {
DensityGrid<int> grid;
if (argc != 1) {
cerr <<
"Usage- blob_stats <foo.grid\n"
"\n"
"Print out basic information about blobs in a grid (requires an integer grid)\n"
"See also blobid, and pick_blob\n";
exit(-1);
}
cin >> grid;
cout << "Read in grid with dimensions " << grid.gridDims() << endl;
cout << "Grid extents (real-space) is " << grid.minCoord() << " x " << grid.maxCoord() << endl;
GCoord range = grid.maxCoord() - grid.minCoord();
cout << "Grid range is " << range << endl;
vector<int> sizes = sizeBlobs(grid);
int n = sizes.size();
vector<GCoord> centers = blobCentroids(n, grid);
GCoord delta = grid.gridDelta();
double voxel_volume = 1.0 / delta[0];
for (int i=1; i<3; i++)
voxel_volume *= (1.0 / delta[i]);
cout << boost::format("Voxel volume = %8.6g\n") % voxel_volume;
cout << boost::format("%6s %12s %12s\t%s\n")
% "Id"
% "Voxels"
% "Size (in A^3)"
% "Centroid (in A)";
cout << boost::format("%-6s %-12s %-12s\t%s\n")
% "------"
% "------------"
% "------------"
% "------------------------------";
for (uint i = 0; i < sizes.size(); ++i) {
cout << boost::format("%6d %12d %12.6g\t") % i % sizes[i] % (sizes[i] * voxel_volume);
cout << centers[i] << endl;
}
}
| 3,509
|
C++
|
.cpp
| 103
| 30.514563
| 97
| 0.64069
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,131
|
gridstat.cpp
|
GrossfieldLab_loos/Packages/DensityTools/gridstat.cpp
|
/*
gridstat.cpp
Simple grid statistics...
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <DensityGrid.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
double avgDens(DensityGrid<double>& grid) {
long i, n = grid.maxGridIndex();
double avg = 0.0;
for (i=0; i<n; i++)
avg += grid(i);
return(avg/n);
}
double zavgDens(DensityGrid<double>& grid) {
long n = grid.maxGridIndex();
long m = 0;
double avg = 0.0;
for (long i=0; i<n; ++i) {
double d = grid(i);
if (d > 0.0) {
avg += d;
++m;
}
}
avg /= m;
return(avg);
}
double stdDens(DensityGrid<double>& grid, const double avg) {
long i, n = grid.maxGridIndex();
double std = 0.0;
for (i=0; i<n; i++)
std += (grid(i) - avg) * (grid(i) - avg);
return(sqrt(std/(n-1.0)));
}
double zstdDens(DensityGrid<double>& grid, const double avg) {
long i, n = grid.maxGridIndex();
double std = 0.0;
long m = 0;
for (i=0; i<n; i++)
if (grid(i) > 0.0) {
std += (grid(i) - avg) * (grid(i) - avg);
++m;
}
return(sqrt(std/(m-1.0)));
}
double maxDens(DensityGrid<double>& grid) {
long i, n = grid.maxGridIndex();
double max = 0.0;
for (i=0; i<n; i++)
if (grid(i) > max)
max = grid(i);
return(max);
}
void quickHist(DensityGrid<double>& grid, const double x, const int nbins) {
long *bins = new long[nbins];
double delta = x / nbins;
for (int i=0; i<nbins; i++)
bins[i] = 0;
long n = grid.maxGridIndex();
for (long i=0; i<n; i++) {
int k = static_cast<int>(grid(i) / delta);
assert(k <= nbins && k >= 0);
if (k == nbins)
k = nbins - 1;
++bins[k];
}
cout << "Quick histogram\n";
cout << "---------------\n";
for (int i=0; i<nbins; i++) {
cout << setprecision(6) << setw(10) << i*delta << "\t" << setprecision(4) << static_cast<double>(i)/nbins << "\t";
cout << setw(10) << bins[i] << "\t" << setprecision(4) << static_cast<double>(bins[i]) / n << endl;
}
delete[] bins;
}
void zAverage(DensityGrid<double>& grid, const int nbins) {
DensityGridpoint dims = grid.gridDims();
int chunk_size = dims[2] / nbins;
long volume = chunk_size * dims[1] * dims[0];
cout << endl;
cout << "Z-slice averages\n";
cout << "----------------\n";
int kk = 0;
for (int k = 0; k<nbins; k++) {
// Calculate z-range...
DensityGridpoint bottom(0,0,k*chunk_size);
DensityGridpoint top(0,0,chunk_size*(k+1));
GCoord wbottom = grid.gridToWorld(bottom);
GCoord wtop = grid.gridToWorld(top);
double avg = 0.0;
for (int sk = 0; sk < chunk_size && sk+kk < dims[2]; sk++, kk++)
for (int j=0; j<dims[1]; j++)
for (int i=0; i<dims[0]; i++)
avg += grid(kk, j, i);
avg /= volume;
cout << kk << "\t" << wbottom.z() << "\t" << wtop.z() << "\t" << avg << endl;
}
if (kk < dims[2]) {
DensityGridpoint bottom(0,0,kk);
GCoord wbottom = grid.gridToWorld(bottom);
double avg = 0.0;
volume = 0;
for (; kk < dims[2]; kk++)
for (int j=0; j<dims[1]; j++)
for (int i=0; i<dims[0]; i++, volume++)
avg += grid(kk, j, i);
DensityGridpoint top(0,0,kk);
GCoord wtop = grid.gridToWorld(top);
avg /= volume;
cout << kk << "\t" << wbottom.z() << "\t" << wtop.z() << "\t" << avg << endl;
cout << "Warning- last row adjusted\n";
}
}
double rmsdDens(DensityGrid<double>& grid, const double avg) {
double rms = 0.0;
for (long i=0; i<grid.maxGridIndex(); ++i) {
double d = grid(i) - avg;
rms += d*d;
}
rms /= grid.maxGridIndex();
return(sqrt(rms));
}
int main(int argc, char *argv[]) {
if (argc != 3) {
cerr <<
"Usage- gridstat bins zbins <file.grid\n"
"\n"
"Displays some basic statistics about the density in a grid.\n"
"Bins is the number of bins for histogramming the density values.\n"
"Zbins is the number of bins in Z (really, K) to calculate density\n"
"statistics (useful for membrane systems).\n"
"Requires a double-precision floating point grid\n";
exit(-1);
}
double nbins = strtod(argv[1], 0);
double zbins = strtod(argv[2], 0);
DensityGrid<double> grid;
cin >> grid;
cout << "Read in grid of size " << grid.gridDims() << endl;
cout << "Range is " << grid.minCoord() << " to " << grid.maxCoord() << endl;
double gavg = avgDens(grid);
double grmsd = rmsdDens(grid, gavg);
double gzavg = zavgDens(grid);
double gstd = stdDens(grid, gavg);
double gzstd = zstdDens(grid, gzavg);
double gmax = maxDens(grid);
cout << "\n\n* Grid Density Statistics *\n";
cout << "Grid density is " << gavg << " (" << gstd << ")\n";
cout << "Grid rmsd is " << grmsd << endl;
cout << "Grid non-zero avg is " << gzavg << " (" << gzstd << ")\n";
cout << "Max density is " << gmax << endl << endl;
quickHist(grid, gmax, nbins);
zAverage(grid, zbins);
}
| 5,755
|
C++
|
.cpp
| 173
| 29.369942
| 118
| 0.613583
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,132
|
grid2ascii.cpp
|
GrossfieldLab_loos/Packages/DensityTools/grid2ascii.cpp
|
/*
grid2ascii
Convert a grid into a serialized ascii representation
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <DensityGrid.hpp>
#include <boost/format.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
int main(int argc, char *argv[]) {
DensityGrid<double> grid;
if (argc != 1) {
cerr << "Usage- grid2ascii <foo.grid >foo.asc\n"
"\n"
"Converts a LOOS grid to an ASCII representation. Requires a double precision\n"
"floating point grid.\n";
exit(-1);
}
cin >> grid;
DensityGridpoint dim = grid.gridDims();
GCoord min = grid.minCoord();
GCoord max = grid.maxCoord();
cout << boost::format("Read in grid of size %s\n") % dim;
cout << boost::format("Grid range from %s x %s\n") % min % max;
for (int k=0; k<dim.z(); ++k)
for (int j=0; j<dim.y(); ++j)
for (int i=0; i<dim.x(); ++i)
cout << boost::format("(%d,%d,%d) = %f\n") % k % j % i % grid(k,j,i);
}
| 1,800
|
C++
|
.cpp
| 46
| 35.586957
| 87
| 0.703405
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,133
|
blobid.cpp
|
GrossfieldLab_loos/Packages/DensityTools/blobid.cpp
|
/*
blobid.cpp
Flood-fills a grid to identify blobs...
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <limits>
#include <DensityTools.hpp>
#include <DensityGrid.hpp>
#include <GridUtils.hpp>
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
double lower, upper;
// @cond TOOLS_INTERNAL
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\n"
"\tIdentify blobs in a density grid.\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tblobid identifies blobs by density values either in a range or above a threshold.\n"
"An edm grid (see for example water-hist) is expected for input.\n"
"Blobid then uses a flood-fill to determine how many separate blobs\n"
"meet the threshold/range criteria. A new grid is then written out\n"
"which identifies the separate blobs.\n"
"\nEXAMPLES\n"
"\tblobid --threshold 1 <foo.grid >foo_id.grid\n"
"Here we include all blobs above the threshold 1. foo_grid is a density\n"
"grid that has been created previously. For example a smoothed water \n"
"histogram grid may be used: \n"
"\twater-hist --radius=15 --bulk=25 --scale=1 b2ar.pdb b2ar.dcd |\\\n"
"\t grid2gauss 4 2 > foo_grid\n"
"The resulting blobs are then written to the grid \"foo_id\"\n"
"\n\n";
return(msg);
}
class ToolOptions : public opts::OptionsPackage {
void addGeneric(po::options_description& o) {
o.add_options()
("lower", po::value<double>(), "Sets the lower threshold for segmenting the grid")
("upper", po::value<double>(), "Sets the upper threshold for segmenting the grid")
("threshold", po::value<double>(), "Sets the threshold for segmenting the grid.");
}
bool postConditions(po::variables_map& vm) {
if (vm.count("threshold")) {
lower = vm["threshold"].as<double>();
upper = numeric_limits<double>::max();
} else {
if (!(vm.count("lower-threshold") && vm.count("upper-threshold"))) {
cerr << "Error- you must specify either a treshold or a threshold range.\n";
return(false);
}
lower = vm["lower-threshold"].as<double>();
upper = vm["upper-threshold"].as<double>();
}
return(true);
}
string print() const {
ostringstream oss;
oss << boost::format("lower=%f, upper=%f") % lower % upper;
return(oss.str());
}
};
// @endcond
int fill(const DensityGridpoint seed, const int val, DensityGrid<double>& data_grid, DensityGrid<int>& blob_grid, const double low, const double high) {
vector<DensityGridpoint> blob = floodFill(seed, data_grid, val, blob_grid, ThresholdRange<double>(low, high));
return(blob.size());
}
boost::tuple<int, int, int, double> findBlobs(DensityGrid<double>& data_grid, DensityGrid<int>& blob_grid, const double low, const double high) {
DensityGridpoint dims = data_grid.gridDims();
int id = 1;
int min = numeric_limits<int>::max();
int max = numeric_limits<int>::min();
double avg = 0.0;
for (int k=0; k<dims[2]; k++) {
for (int j=0; j<dims[1]; j++)
for (int i=0; i<dims[0]; i++) {
DensityGridpoint point(i,j,k);
if (blob_grid(point) == 0 && (data_grid(point) >= low && data_grid(point) <= high)) {
int n = fill(point, id++, data_grid, blob_grid, low, high);
if (n < min)
min = n;
if (n > max)
max = n;
avg += n;
}
}
}
avg /= (id-1);
boost::tuple<int, int, int, double> res(id-1, min, max, avg);
return(res);
}
int main(int argc, char *argv[]) {
string header = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
DensityGrid<double> data;
cin >> data;
cerr << "Read in grid with size " << data.gridDims() << endl;
DensityGrid<int> blobs(data.minCoord(), data.maxCoord(), data.gridDims());
boost::tuple<int, int, int, double> stats = findBlobs(data, blobs, lower, upper);
cerr << boost::format("Found %d blobs in range %6.4g to %6.4g\n") % boost::get<0>(stats) % lower % upper;
cerr << boost::format("Min blob size = %d, max blob size = %d, avg blob size = %6.4f\n")
% boost::get<1>(stats)
% boost::get<2>(stats)
% boost::get<3>(stats);
cout << blobs;
}
| 5,262
|
C++
|
.cpp
| 133
| 35.669173
| 152
| 0.681102
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,134
|
water-extract.cpp
|
GrossfieldLab_loos/Packages/DensityTools/water-extract.cpp
|
/*
water-extract.cpp
usage:
water-extract [options] model trajectory >output.pdb
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2011, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iterator>
#include <boost/format.hpp>
#include <boost/program_options.hpp>
#include <loos.hpp>
#include <DensityGrid.hpp>
#include <DensityTools.hpp>
#include <DensityOptions.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* basopts = new opts::BasicOptions;
opts::TrajectoryWithFrameIndices* tropts = new opts::TrajectoryWithFrameIndices;
opts::BasicWater* watopts = new opts::BasicWater;
opts::AggregateOptions options;
options.add(basopts).add(tropts).add(watopts);
if (!options.parse(argc, argv))
exit(-1);
AtomicGroup model = tropts->model;
pTraj traj = tropts->trajectory;
vector<uint> frames = tropts->frameList();
AtomicGroup subset = selectAtoms(model, watopts->prot_string);
AtomicGroup waters = selectAtoms(model, watopts->water_string);
AtomicGroup liquid;
uint current_id = 1;
for (vector<uint>::iterator t = frames.begin(); t != frames.end(); ++t) {
traj->readFrame(*t);
traj->updateGroupCoords(model);
vector<int> mask = watopts->filter_func->filter(waters, subset);
for (uint j=0; j<mask.size(); ++j)
if (mask[j]) {
pAtom atom(new Atom(*(waters[j])));
atom->id(current_id);
atom->resid(current_id++);
atom->segid("WATER");
liquid.append(atom);
}
}
PDB pdb = PDB::fromAtomicGroup(liquid);
pdb.remarks().add(hdr);
cout << pdb;
}
| 2,453
|
C++
|
.cpp
| 64
| 34.59375
| 82
| 0.72989
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,135
|
gridautoscale.cpp
|
GrossfieldLab_loos/Packages/DensityTools/gridautoscale.cpp
|
/*
gridautoscale.cpp
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2012, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <DensityGrid.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
typedef DensityGrid<double> Grid;
double findPeakDensitySlice(const Grid& grid, const int nbins) {
DensityGridpoint dims = grid.gridDims();
int chunk_size = dims[2] / nbins;
long volume = chunk_size * dims[1] * dims[0];
double max_avg_density = 0.0;
int kk = 0;
for (int k = 0; k<nbins; k++) {
// Calculate z-range...
DensityGridpoint bottom(0,0,k*chunk_size);
DensityGridpoint top(0,0,chunk_size*(k+1));
double avg = 0.0;
for (int sk = 0; sk < chunk_size && sk+kk < dims[2]; sk++, kk++)
for (int j=0; j<dims[1]; j++)
for (int i=0; i<dims[0]; i++)
avg += grid(kk, j, i);
avg /= volume;
if (avg >= max_avg_density)
max_avg_density = avg;
}
if (kk < dims[2]) {
double avg = 0.0;
volume = 0;
for (; kk < dims[2]; kk++)
for (int j=0; j<dims[1]; j++)
for (int i=0; i<dims[0]; i++, volume++)
avg += grid(kk, j, i);
DensityGridpoint top(0,0,kk);
avg /= volume;
if (avg >= max_avg_density)
max_avg_density = avg;
}
return(max_avg_density);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
if (argc != 1) {
cerr << "Usage- gridautoscale <input.grid >output.grid\n";
cerr <<
"DESCRIPTION\n\tgridautoscale is used to normalize the density\n"
"values in a grid for solvated membrane systems. It divides the system\n"
"into bins in Z (normal to the membrane) and looks for the bulk water peak.\n"
"The entire grid is then scaled so that the average density in the bulk\n"
"regions is 1.\n";
exit(-1);
}
Grid grid;
cin >> grid;
DensityGridpoint dims = grid.gridDims();
double best_avg = 0.0;
uint best_bin = 0;
cerr << "Autoscaling- ";
for (int nbins = 5; nbins <= dims[2]; ++nbins) {
if (nbins % 10 == 0)
cerr << '.';
double avg = findPeakDensitySlice(grid, nbins);
if (avg > best_avg) {
best_avg = avg;
best_bin = nbins;
}
}
cerr << "\nScaling to 1/" << best_avg << " based on " << best_bin << " bins" << endl;
double konst = 1.0 / best_avg;
grid.scale(konst);
grid.addMetadata(hdr);
ostringstream oss;
oss << "Auto scaling = " << konst << ", bins = " << best_bin;
grid.addMetadata(oss.str());
cout << grid;
}
| 3,276
|
C++
|
.cpp
| 94
| 30.819149
| 87
| 0.658188
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,136
|
gridmask.cpp
|
GrossfieldLab_loos/Packages/DensityTools/gridmask.cpp
|
/*
gridmask.cpp
Given an int grid that represents picked blobs, use this as a mask
against a double grid...
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <boost/tuple/tuple.hpp>
#include <algorithm>
#include <sstream>
#include <limits>
#include <DensityGrid.hpp>
using namespace std;
using namespace loos;
using namespace DensityTools;
/*
* Applies a mask to an edm grid. This can select a particular
* region within the grid.
*
* Example:
* gridmask < foo_grid foo_picked > masked_foo
* This will apply the mask called \"foo_picked\" to the grid
* \"foo_grid\" and write out a new grid, \"masked_foo\". This
* assumes foo_picked was created with the \"pick_blob\" tool.
*
* This output my be converted to an xplor map and then used for
* visualization within pymol.
*
*/
int main(int argc, char *argv[]) {
if (argc != 2) {
cerr <<
"SYNOPSIS\n\tExtracts a region of density given a mask grid\n"
"\nDESCRIPTION\n\tThis tool will zero out any unwanted density\n"
"given a density grid and a grid mask. The grid mask is an integer\n"
"grid. Any non-zero element of the grid mask means that the corresponding\n"
"density from the density grid will be copied to the output grid.\n"
"All other locations will have a zero density value. (Think of an alpha-mask\n"
"in gimp or photoshop).\n"
"\nEXAMPLES\n\tgridmask <density.grid mask.grid >masked_density.grid\n"
"This will apply the mask.grid mask to the density.grid, writing the output\n"
"to masked_density.grid\n"
"\n"
"\tblobid --threshold 1 <foo.grid >foo_id.grid\n"
"\tpick_blob --model foo.pdb --selection 'resid == 65' <foo_id.grid >foo_picked.grid\n"
"\tgridmask <foo.grid foo_picked.grid >foo_masked.grid\n"
"This example will first threshold the density at 1.0, then it will find the blob\n"
"closest to residue 65. This blob is then used as a mask for the original density\n"
"grid. foo_picked.grid therefore contains the actual density values, but with\n"
"all extraneous density removed.\n";
cerr << "Usage- gridmask <edm_grid mask_grid >masked_edm_grid\n";
exit(-1);
}
DensityGrid<int> mask;
ifstream ifs(argv[1]);
if (!ifs) {
cerr << "Error - cannot open " << argv[1] << " for reading.\n";
exit(-10);
}
ifs >> mask;
DensityGrid<double> data;
cin >> data;
DensityGridpoint dims = data.gridDims();
DensityGridpoint ddims = mask.gridDims();
if (dims != ddims) {
cerr << "Error - differing dimensions between mask and density grids.\n";
exit(-10);
}
long k = dims[0] * dims[1] * dims[2];
for (long i=0; i<k; i++)
if (!mask(i))
data(i) = 0.0;
cout << data;
}
| 3,606
|
C++
|
.cpp
| 90
| 36.188889
| 93
| 0.702524
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,137
|
internal-water-filter.cpp
|
GrossfieldLab_loos/Packages/DensityTools/internal-water-filter.cpp
|
/*
Internal water filter library
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <internal-water-filter.hpp>
using namespace std;
namespace loos {
namespace DensityTools {
string WaterFilterBox::name(void) const {
stringstream s;
s << boost::format("WaterFilterBox(pad=%f)") % pad_;
return(s.str());
}
vector<int> WaterFilterBox::filter(const AtomicGroup& solv, const AtomicGroup& prot) {
bdd_ = boundingBox(prot);
vector<int> result(solv.size());
AtomicGroup::const_iterator ai;
uint j = 0;
for (ai = solv.begin(); ai != solv.end(); ++ai) {
bool flag = true;
GCoord c = (*ai)->coords();
for (int i=0; i<3; ++i)
if (c[i] < bdd_[0][i] || c[i] > bdd_[1][i]) {
flag = false;
break;
}
result[j++] = flag;
}
return(result);
}
double WaterFilterBox::volume(void) {
GCoord v = bdd_[1] - bdd_[0];
return(v[0] * v[1] * v[2]);
}
vector<GCoord> WaterFilterBox::boundingBox(const AtomicGroup& grp) {
vector<GCoord> bdd = grp.boundingBox();
bdd[0] = bdd[0] - pad_;
bdd[1] = bdd[1] + pad_;
return(bdd);
}
// --------------------------------------------------------------------------------
string WaterFilterRadius::name(void) const {
stringstream s;
s << boost::format("WaterFilterRadius(radius=%f)") % radius_;
return(s.str());
}
vector<int> WaterFilterRadius::filter(const AtomicGroup& solv, const AtomicGroup& prot) {
bdd_ = boundingBox(prot);
vector<int> result(solv.size());
double r2 = radius_ * radius_;
for (uint j=0; j<solv.size(); ++j) {
GCoord sc = solv[j]->coords();
for (uint i=0; i<prot.size(); ++i)
if (sc.distance2(prot[i]->coords()) <= r2) {
result[j] = 1;
break;
}
}
return(result);
}
double WaterFilterRadius::volume(void) {
GCoord v = bdd_[1] - bdd_[0];
return(v[0] * v[1] * v[2]);
}
vector<GCoord> WaterFilterRadius::boundingBox(const AtomicGroup& grp) {
vector<GCoord> bdd = grp.boundingBox();
bdd[0] = bdd[0] - radius_;
bdd[1] = bdd[1] + radius_;
return(bdd);
}
// --------------------------------------------------------------------------------
string WaterFilterContacts::name(void) const {
stringstream s;
s << boost::format("WaterFilterContacts(radius=%f,contacts=%u)") % radius_ % threshold_;
return(s.str());
}
vector<int> WaterFilterContacts::filter(const AtomicGroup& solv, const AtomicGroup& prot) {
bdd_ = boundingBox(prot);
vector<int> result(solv.size());
double r2 = radius_ * radius_;
for (uint j=0; j<solv.size(); ++j) {
uint count = 0;
for (uint i=0; i<prot.size(); ++i) {
if (solv[j]->coords().distance2(prot[i]->coords()) <= r2) {
++count;
if (count >= threshold_) {
result[j] = 1;
break;
}
}
}
}
return(result);
}
double WaterFilterContacts::volume(void) {
GCoord v = bdd_[1] - bdd_[0];
return(v[0] * v[1] * v[2]);
}
vector<GCoord> WaterFilterContacts::boundingBox(const AtomicGroup& grp) {
vector<GCoord> bdd = grp.boundingBox();
bdd[0] = bdd[0] - radius_;
bdd[1] = bdd[1] + radius_;
return(bdd);
}
// --------------------------------------------------------------------------------
string WaterFilterAxis::name(void) const {
stringstream s;
s << boost::format("WaterFilterAxis(radius=%f)") % sqrt(radius_);
return(s.str());
}
vector<int> WaterFilterAxis::filter(const AtomicGroup& solv, const AtomicGroup& prot) {
bdd_ = boundingBox(prot);
vector<int> result(solv.size());
AtomicGroup::const_iterator ai;
uint j = 0;
for (ai = solv.begin(); ai != solv.end(); ++ai) {
GCoord a = (*ai)->coords();
if (a.z() < bdd_[0][2] || a.z() > bdd_[1][2]) {
result[j++] = 0;
continue;
}
// Find the nearest point on the axis to the atom...
a -= orig_;
double k = (axis_ * a) / axis_.length2();
GCoord ah = orig_ + k * axis_;
GCoord v = (*ai)->coords() - ah;
// Are we within the radius cutoff?
double d = v.length2();
if (d <= radius_)
result[j++] = true;
else
result[j++] = false;
}
return(result);
}
double WaterFilterAxis::volume(void) {
return((bdd_[1][2] - bdd_[0][2]) * PI * radius_);
}
vector<GCoord> WaterFilterAxis::boundingBox(const AtomicGroup& grp) {
// Set the principal axis...
orig_ = grp.centroid();
vector<GCoord> axes = grp.principalAxes();
axis_ = axes[0];
vector<GCoord> bdd = grp.boundingBox();
// Calculate the extents of the box containing the principal axis cylinder...
double r = sqrt(radius_);
GCoord lbd = orig_ - axis_ - GCoord(r,r,0.0);
GCoord ubd = orig_ + axis_ + GCoord(r,r,0.0);
// Set the z-bounds to the protein bounding box...
lbd[2] = bdd[0][2];
ubd[2] = bdd[1][2];
// Replace...
bdd[0] = lbd;
bdd[1] = ubd;
return(bdd);
}
// --------------------------------------------------------------------------------
string WaterFilterCore::name(void) const {
stringstream s;
s << boost::format("WaterFilterCore(radius=%f)") % sqrt(radius_);
return(s.str());
}
GCoord WaterFilterCore::calculateAxis(const AtomicGroup& bundle)
{
if (!bundle.hasBonds())
throw(runtime_error("WaterFilterCore requires model connectivity (bonds)"));
vector<AtomicGroup> segments = bundle.splitByMolecule();
GCoord axis(0,0,0);
for (vector<AtomicGroup>::iterator i = segments.begin(); i != segments.end(); ++i) {
vector<GCoord> axes = (*i).principalAxes();
if (axes[0].z() < 0.0)
axis -= axes[0];
else
axis += axes[0];
}
axis /= axis.length();
return(axis);
}
vector<int> WaterFilterCore::filter(const AtomicGroup& solv, const AtomicGroup& prot) {
bdd_ = boundingBox(prot);
vector<int> result(solv.size());
AtomicGroup::const_iterator ai;
uint j = 0;
for (ai = solv.begin(); ai != solv.end(); ++ai) {
GCoord a = (*ai)->coords();
if (a.z() < bdd_[0][2] || a.z() > bdd_[1][2]) {
result[j++] = 0;
continue;
}
// Find the nearest point on the axis to the atom...
a -= orig_;
double k = (axis_ * a) / axis_.length2();
GCoord ah = orig_ + k * axis_;
GCoord v = (*ai)->coords() - ah;
// Are we within the radius cutoff?
double d = v.length2();
if (d <= radius_)
result[j++] = true;
else
result[j++] = false;
}
return(result);
}
// TODO: Fix!
double WaterFilterCore::volume(void) {
return((bdd_[1][2] - bdd_[0][2]) * PI * radius_);
}
vector<GCoord> WaterFilterCore::boundingBox(const AtomicGroup& grp) {
// Set the principal axis...
orig_ = grp.centroid();
axis_ = calculateAxis(grp);
vector<GCoord> bdd = grp.boundingBox();
// Calculate the extents of the box containing the principal axis cylinder...
double r = sqrt(radius_);
GCoord lbd = orig_ - axis_ - GCoord(r,r,0.0);
GCoord ubd = orig_ + axis_ + GCoord(r,r,0.0);
// Set the z-bounds to the protein bounding box...
lbd[2] = bdd[0][2];
ubd[2] = bdd[1][2];
// Replace...
bdd[0] = lbd;
bdd[1] = ubd;
return(bdd);
}
// --------------------------------------------------------------------------------
string WaterFilterBlob::name(void) const {
stringstream s;
GCoord min = blob_.minCoord();
GCoord max = blob_.maxCoord();
DensityGridpoint dim = blob_.gridDims();
s << "WaterFilterBlob(" << dim << ":" << min << "x" << max << ")";
return(s.str());
}
double WaterFilterBlob::volume(void) {
if (vol >= 0.0)
return(vol);
GCoord d = blob_.gridDelta();
double delta = d[0] * d[1] * d[2];
long n = blob_.maxGridIndex();
long c = 0;
for (long i=0; i<n; ++i)
if (blob_(i))
++c;
vol = c * delta;
return(vol);
}
vector<int> WaterFilterBlob::filter(const AtomicGroup& solv, const AtomicGroup& prot) {
vector<int> result(solv.size());
AtomicGroup::const_iterator ci;
uint j = 0;
for (ci = solv.begin(); ci != solv.end(); ++ci) {
GCoord c = (*ci)->coords();
DensityGridpoint probe = blob_.gridpoint(c);
if (blob_.inRange(probe))
result[j++] = (blob_(c) != 0);
else
result[j++] = 0;
}
return(result);
}
// This ignores the protein bounding box...
vector<GCoord> WaterFilterBlob::boundingBox(const AtomicGroup& prot) {
if (bdd_set)
return(bdd_);
DensityGridpoint dim = blob_.gridDims();
DensityGridpoint min = dim;
DensityGridpoint max(0,0,0);
for (int k=0; k<dim[2]; ++k)
for (int j=0; j<dim[1]; ++j)
for (int i=0; i<dim[0]; ++i) {
DensityGridpoint probe(i,j,k);
if (blob_(probe) != 0)
for (int x=0; x<3; ++x) {
if (probe[x] < min[x])
min[x] = probe[x];
if (probe[x] > max[x])
max[x] = probe[x];
}
}
vector<GCoord> bdd(2);
bdd[0] = blob_.gridToWorld(min);
bdd[1] = blob_.gridToWorld(max);
return(bdd);
}
// --------------------------------------------------------------------------------
string ZClippedWaterFilter::name(void) const {
stringstream s;
s << boost::format("ZClippedWaterFilter(%s, %f, %f)") % WaterFilterDecorator::name() % zmin_ % zmax_;
return(s.str());
}
vector<int> ZClippedWaterFilter::filter(const AtomicGroup& solv, const AtomicGroup& prot) {
vector<int> result = WaterFilterDecorator::filter(solv, prot);
for (uint i=0; i<result.size(); ++i)
if (result[i]) {
GCoord c = solv[i]->coords();
if (c[2] < zmin_ || c[2] > zmax_)
result[i] = 0;
}
return(result);
}
vector<GCoord> ZClippedWaterFilter::boundingBox(const AtomicGroup& grp) {
vector<GCoord> bdd = WaterFilterDecorator::boundingBox(grp);
bdd[0][2] = zmin_;
bdd[1][2] = zmax_;
return(bdd);
}
// --------------------------------------------------------------------------------
string BulkedWaterFilter::name(void) const {
stringstream s;
s << boost::format("BulkedWaterFilter(%s, %f, %f, %f)") % WaterFilterDecorator::name() % pad_ % zmin_ % zmax_;
return(s.str());
}
vector<int> BulkedWaterFilter::filter(const AtomicGroup& solv, const AtomicGroup& prot) {
vector<int> result = WaterFilterDecorator::filter(solv, prot);
vector<GCoord> bdd = boundingBox(prot);
for (uint i=0; i<result.size(); ++i)
if (!result[i]) {
GCoord c = solv[i]->coords();
if ( ((c[0] >= bdd[0][0] && c[0] <= bdd[1][0]) &&
(c[1] >= bdd[0][1] && c[1] <= bdd[1][1]) &&
(c[2] >= bdd[0][2] && c[2] <= zmin_))
||
((c[0] >= bdd[0][0] && c[0] <= bdd[1][0]) &&
(c[1] >= bdd[0][1] && c[1] <= bdd[1][1]) &&
(c[2] <= bdd[1][2] && c[2] >= zmax_)) )
result[i] = true;
}
return(result);
}
vector<GCoord> BulkedWaterFilter::boundingBox(const AtomicGroup& grp) {
vector<GCoord> bdd = grp.boundingBox();
bdd[0] -= pad_;
bdd[1] += pad_;
return(bdd);
}
};
};
| 12,847
|
C++
|
.cpp
| 352
| 28.857955
| 116
| 0.530028
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,138
|
gridgauss.cpp
|
GrossfieldLab_loos/Packages/DensityTools/gridgauss.cpp
|
/*
Gridgauss
Apply a gaussian kernel to a grid
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <DensityGrid.hpp>
#include <GridUtils.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
int main(int argc, char *argv[]) {
if (argc != 5) {
cerr <<
"DESCRIPTION\n\tApply a gaussian kernel convolution with a grid\n"
"\nUSAGE\n\tgridgauss width size scaling sigma <grid >output\n"
"Width controls the size (in grid units) of the kernel. Size\n"
"determines how the gaussian is mapped onto the kernel, i.e.\n"
"-size <= x < size. The gaussian is f(x) = exp(-0.5*(x/sigma)^2)\n"
"and is normalized so the sum of f(x) is one, then multiplied by\n"
"the scaling factor.\n"
"\nEXAMPLES\n\tgridgauss 10 3 1 1 <foo.grid >foo_smoothed.grid\n"
"This convolves the grid with a 10x10 kernel with sigma=1, and is a good\n"
"starting point for smoothing out water density grid.\n";
exit(0);
}
string hdr = invocationHeader(argc, argv);
int k = 1;
uint width = strtol(argv[k++], 0, 10);
double scaling = strtod(argv[k++], 0);
double normalization = strtod(argv[k++], 0);
double sigma = strtod(argv[k++], 0);
vector<double> kernel;
double scaling2 = 2.0 * scaling;
double sum = 0.0;
for (uint i=0; i<width; ++i) {
double x = scaling2 * i / width - scaling;
double f = exp(-0.5*(x/sigma)*(x/sigma));
sum += f;
kernel.push_back(f);
}
double a = normalization / sum;
for (uint i=0; i<kernel.size(); ++i)
kernel[i] *= a;
cerr << "Kernel (" << kernel.size() << "): ";
copy(kernel.begin(), kernel.end(), ostream_iterator<double>(cerr, ","));
cerr << endl;
cerr << "normalization = " << sum << endl;
DensityGrid<double> grid;
cin >> grid;
gridConvolve(grid, kernel);
grid.addMetadata(hdr);
cout << grid;
}
| 2,732
|
C++
|
.cpp
| 70
| 35.2
| 81
| 0.690087
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,139
|
water-hist-lib.cpp
|
GrossfieldLab_loos/Packages/DensityTools/water-hist-lib.cpp
|
// -------------------------------------------------
// Water Histogram Library
// -------------------------------------------------
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009 Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <water-hist-lib.hpp>
namespace loos {
namespace DensityTools {
void ZClipEstimator::reinitialize(pTraj& traj, const std::vector<uint>& frames) {
std::vector<GCoord> bdd = getBounds(traj, water_, frames);
bdd[0] -= 1;
if (bdd[0][2] > zclip_)
throw(std::runtime_error("Bulk zclip is too small"));
bdd[0][2] = zclip_;
bdd[1] += 1;
GCoord gridsize = bdd[1] - bdd[0] + 1;
gridsize /= gridres_;
DensityGridpoint dims;
for (int i=0; i<3; ++i)
dims[i] = static_cast<int>(floor(gridsize[i] + 0.5));
thegrid.resize(bdd[0], bdd[1], dims);
}
void ZClipEstimator::operator()(const double density) {
for (AtomicGroup::const_iterator i = water_.begin(); i != water_.end(); ++i) {
GCoord c = (*i)->coords();
if (c.z() >= zclip_)
thegrid((*i)->coords()) += density;
}
}
double ZClipEstimator::bulkDensity(void) const {
double mean = 0.0;
long n = 0;
for (long i = 0; i < thegrid.maxGridIndex(); ++i) {
if (!count_zero && thegrid(i) == 0.0)
continue;
mean += thegrid(i);
++n;
}
return(mean/n);
}
double ZClipEstimator::stdDev(const double mean) const {
double std = 0.0;
long n = 0;
for (long i = 0; i < thegrid.maxGridIndex(); ++i)
if (thegrid(i) != 0.0) {
double d = thegrid(i) - mean;
std += d*d;
++n;
}
std = sqrt(std/(n-1));
return(std);
}
// ------------------------------------------------------------------------
// Note: no checks on whether the z-slice is sensible...
void ZSliceEstimator::reinitialize(pTraj& traj, const std::vector<uint>& frames) {
std::vector<GCoord> bdd = getBounds(traj, water_, frames);
bdd[0] -= 1;
bdd[0][2] = zmin_;
bdd[1] += 1;
bdd[1][2] = zmax_;
GCoord gridsize = bdd[1] - bdd[0] + 1;
gridsize /= gridres_;
DensityGridpoint dims;
for (int i=0; i<3; ++i)
dims[i] = static_cast<int>(floor(gridsize[i] + 0.5));
thegrid.resize(bdd[0], bdd[1], dims);
}
void ZSliceEstimator::operator()(const double density) {
for (AtomicGroup::const_iterator i = water_.begin(); i != water_.end(); ++i) {
GCoord c = (*i)->coords();
if (c.z() >= zmin_ && c.z() < zmax_)
thegrid((*i)->coords()) += density;
}
}
double ZSliceEstimator::bulkDensity(void) const {
double mean = 0.0;
long n = 0;
for (long i = 0; i < thegrid.maxGridIndex(); ++i) {
if (!count_zero && thegrid(i) == 0.0)
continue;
mean += thegrid(i);
++n;
}
return(mean/n);
}
double ZSliceEstimator::stdDev(const double mean) const {
double std = 0.0;
long n = 0;
for (long i = 0; i < thegrid.maxGridIndex(); ++i)
if (thegrid(i) != 0.0) {
double d = thegrid(i) - mean;
std += d*d;
++n;
}
std = sqrt(std/(n-1));
return(std);
}
// ------------------------------------------------------------------------
void WaterHistogrammer::setGrid(const GCoord& min, const GCoord& max, const double resolution) {
GCoord gridsize = max - min + 1;
gridsize /= resolution;
DensityGridpoint dims;
for (int i=0; i<3; ++i)
dims[i] = static_cast<int>(floor(gridsize[i] + 0.5));
grid_.resize(min, max, dims);
}
void WaterHistogrammer::setGrid(pTraj& traj, const std::vector<uint>& frames, const double resolution, const double pad) {
std::vector<GCoord> bdd(2);
for (uint i=0; i<frames.size(); ++i) {
traj->readFrame(i);
traj->updateGroupCoords(protein_);
std::vector<GCoord> fbdd = the_filter->boundingBox(protein_);
for (uint j=0; j<3; ++j) {
if (fbdd[0][j] < bdd[0][j])
bdd[0][j] = fbdd[0][j];
if (fbdd[1][j] > bdd[1][j])
bdd[1][j] = fbdd[1][j];
}
}
setGrid(bdd[0] - pad, bdd[1] + pad, resolution);
}
void WaterHistogrammer::accumulate(const double density) {
std::vector<int> picks = the_filter->filter(water_, protein_);
for (uint i = 0; i<picks.size(); ++i)
if (picks[i]) {
GCoord c = water_[i]->coords();
if (!grid_.inRange(grid_.gridpoint(c)))
++out_of_bounds;
else
grid_(c) += density;
}
(*estimator_)(density);
}
void WaterHistogrammer::accumulate(pTraj& traj, const std::vector<uint>& frames) {
estimator_->reinitialize(traj, frames);
double density = 1.0 / frames.size();
for (std::vector<uint>::const_iterator i = frames.begin(); i != frames.end(); ++i) {
traj->readFrame(*i);
traj->updateGroupCoords(protein_);
traj->updateGroupCoords(water_);
accumulate(density);
}
}
};
};
| 6,191
|
C++
|
.cpp
| 159
| 30.289308
| 126
| 0.533087
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,140
|
near_blobs.cpp
|
GrossfieldLab_loos/Packages/DensityTools/near_blobs.cpp
|
/*
near_blobs.cpp
Find residues within a given distance of a blob
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2012, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <DensityGrid.hpp>
#include <DensityTools.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
typedef vector<GCoord> vCoords;
typedef vector<vCoords> vvCoords;
typedef vector<AtomicGroup> vGroup;
vvCoords separateBlobs(const DensityGrid<int>& grid) {
int max_blobid = 0;
for (long i = 0; i < grid.size(); ++i)
if (grid(i) > max_blobid)
max_blobid = grid(i);
vvCoords blobs(max_blobid);
DensityGridpoint dims = grid.gridDims();
for (int k=0; k<dims.z(); ++k)
for (int j=0; j<dims.y(); ++j)
for (int i=0; i<dims.x(); ++i) {
DensityGridpoint p(i, j, k);
if (grid(p)) {
int id = grid(p);
GCoord c = grid.gridToWorld(p);
blobs[id-1].push_back(c);
}
}
return(blobs);
}
vector<uint> findBlobsNearResidue(const vvCoords& blobs, const AtomicGroup& residue, const double dist) {
vector<uint> blobids;
double d2 = dist * dist;
for (uint k=0; k<blobs.size(); ++k) {
bool flag = true;
for (uint j=0; j<residue.size() && flag; ++j) {
GCoord c = residue[j]->coords();
for (uint i=0; i<blobs[k].size() && flag; ++i)
if (c.distance2(blobs[k][i]) <= d2)
flag = false;
}
if (!flag)
blobids.push_back(k);
}
return(blobids);
}
int main(int argc, char *argv[]) {
if (argc != 4) {
cerr << "Usage- near_blobs model selection distance <blobs.grid\n";
cerr << "NOTE: grid must have IDs (i.e. output from blobid)\n";
exit(-1);
}
string hdr = invocationHeader(argc, argv);
int k = 1;
AtomicGroup model = createSystem(argv[k++]);
AtomicGroup subset = selectAtoms(model, argv[k++]);
double distance = strtod(argv[k++], 0);
DensityGrid<int> the_grid;
cin >> the_grid;
vvCoords blobs = separateBlobs(the_grid);
vGroup residues = subset.splitByResidue();
cout << "# " << hdr << endl;
cout << "# Atomid Resid Resname Segid Bloblist...\n";
for (uint i=0; i<residues.size(); ++i) {
vector<uint> ids = findBlobsNearResidue(blobs, residues[i], distance);
if (ids.size() == 0)
continue;
cout << boost::format("%d\t%d\t%s\t%s\t")
% residues[i][0]->id()
% residues[i][0]->resid()
% residues[i][0]->resname()
% residues[i][0]->segid();
for (uint j=0; j<ids.size(); ++j)
cout << ids[j]+1 << (j == ids.size()-1 ? "" : ",");
cout << endl;
}
}
| 3,381
|
C++
|
.cpp
| 95
| 31.115789
| 105
| 0.651235
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,141
|
GridUtils.cpp
|
GrossfieldLab_loos/Packages/DensityTools/GridUtils.cpp
|
/*
Utility functions/classes for LOOS grids
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <GridUtils.hpp>
using namespace std;
namespace loos {
namespace DensityTools {
std::vector<double> gaussian1d(const int w, const double sigma) {
double a = 1.0 / sqrt(2.0 * M_PI * sigma);
double b = -1.0 / (2.0 * sigma);
std::vector<double> kernel;
for (int i=0; i<=w; ++i) {
double x = 2.0*i/w-1.0;
kernel.push_back(a*exp(b*x*x));
}
return(kernel);
}
};
};
| 1,355
|
C++
|
.cpp
| 35
| 33.942857
| 77
| 0.714509
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,142
|
gridavg.cpp
|
GrossfieldLab_loos/Packages/DensityTools/gridavg.cpp
|
/*
gridavg
Average grids together. Requires that grids have the same dimensions.
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2013, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <DensityGrid.hpp>
#include <GridUtils.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
int main(int argc, char *argv[]) {
if (argc <3) {
cerr <<
"DESCRIPTION\n\tAverage together multiple grids\n"
"\nUSAGE\n\tgridavg grid1 grid2 [grid3 ...] >averaged.grid\n"
"Requires that the grids have the same dimensions.\n"
"\nEXAMPLES\n\tgridavg water1.grid water2.grid water3.grid >water.grid\n";
exit(0);
}
string hdr = invocationHeader(argc, argv);
DensityGrid<double> avg;
int k = 1;
ifstream ifs(argv[k]);
if (ifs.fail()) {
cerr << "Error- cannot open " << argv[k] << endl;
exit(-1);
}
ifs >> avg;
avg.addMetadata(hdr);
ifs.close();
uint n = 0;
for (++k;k < argc; ++k) {
ifs.open(argv[k]);
if (ifs.fail()) {
cerr << "Error- cannot open " << argv[k] << endl;
exit(-2);
}
DensityGrid<double> grid;
ifs >> grid;
if (grid.gridDims() != avg.gridDims()) {
cerr << "Error- grid in " << argv[k] << " has dimensions " << grid.gridDims() << ",\n"
<< "but was expecting it to be " << avg.gridDims() << endl;
exit(-3);
}
if (grid.minCoord() != avg.minCoord() || grid.maxCoord() != avg.maxCoord())
cerr << "Warning- real world bounds for grid in " << argv[k] << " do not match. Proceeding anyway...\n";
double mean = 0.0;
for (long i=0; i<grid.size(); ++i) {
mean += grid(i);
avg(i) += grid(i);
}
++n;
}
for (long i=0; i<avg.size(); ++i)
avg(i) /= n;
cout << avg;
}
| 2,581
|
C++
|
.cpp
| 74
| 30.540541
| 111
| 0.65749
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,143
|
gridinfo.cpp
|
GrossfieldLab_loos/Packages/DensityTools/gridinfo.cpp
|
/*
gridinfo.cpp
Just dump the grid header info...
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <DensityGrid.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
int main(int argc, char *argv[]) {
DensityGrid<double> grid;
if (argc == 2) {
string fname(argv[1]);
if (fname == "--help" || fname == "-h" || fname == "--fullhelp") {
cerr << "Usage- gridinfo <foo.grid\n\tgridinfo foo.grid\n";
cerr << "\nPrints out basic information about a grid\n";
cerr << "Requires a double-precision floating point grid.\n";
exit(-1);
}
ifstream ifs(argv[1]);
if (!ifs) {
cerr << "Error- cannot open " << argv[1] << endl;
exit(-1);
}
ifs >> grid;
} else
cin >> grid;
loos::GCoord min = grid.minCoord();
loos::GCoord max = grid.maxCoord();
DensityGridpoint dim = grid.gridDims();
cout << "Grid = " << min << " x " << max << " @ " << dim << endl;
cout << "Resolution = " << (max.x() - min.x()) / dim.x() << endl;
cout << "Metadata: ";
SimpleMeta meta = grid.metadata();
if (meta.empty())
cout << "none\n";
else {
cout << endl;
copy(meta.begin(), meta.end(), ostream_iterator<SimpleMeta::value_type>(cout, "\n"));
}
}
| 2,072
|
C++
|
.cpp
| 57
| 32.77193
| 89
| 0.673347
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,144
|
peakify.cpp
|
GrossfieldLab_loos/Packages/DensityTools/peakify.cpp
|
/*
Peakify.cpp
Creates a PDB representing peaks in the grid...
Usage: peakify threshold <input.grid >output.pdb
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <DensityGrid.hpp>
#include <GridUtils.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
int main(int argc, char *argv[]) {
if (argc != 2) {
cerr <<
"Usage- peakify threshold <foo.grid >peaks.pdb\n"
"\n"
"Given a double-precision floating point grid of density values\n"
"and a threshold, this tool writes out a PDB representing the density\n"
"peaks. The algorithm for finding the peaks uses a flood-fill to find\n"
"unique blobs of density. For each blob, the center of mass becomes a\n"
"pseudo-atom in the output PDB (with atom name \"UNK\" and residue name \"GRD\").\n"
"Note that these are really blob centers, as opposed to the point of maximum\n"
"density within a blob.\n";
exit(-1);
}
double thresh = strtod(argv[1], 0);
string hdr = invocationHeader(argc, argv);
DensityGrid<double> grid;
cin >> grid;
cerr << "Read in grid " << grid.gridDims() << "\n";
DensityGrid<int> blobs(grid.minCoord(), grid.maxCoord(), grid.gridDims());
PDB pdb;
vector<GCoord> peaks = findPeaks(grid, Threshold<double>(thresh));
for (uint i = 0; i < peaks.size(); ++i) {
pAtom atom(new Atom(i+1, "UNK", peaks[i]));
atom->resid(i+1);
atom->resname("UNK");
atom->segid("BLOB");
pdb.append(atom);
}
pdb.remarks().add(hdr);
cout << pdb;
}
| 2,375
|
C++
|
.cpp
| 59
| 36.474576
| 90
| 0.70993
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,145
|
water-survival.cpp
|
GrossfieldLab_loos/Packages/DensityTools/water-survival.cpp
|
// (c) 2014 Tod D. Romo, Grossfield Lab, URMC
#include <loos.hpp>
using namespace loos;
using namespace std;
typedef Math::Matrix<int> WaterClassMatrix;
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
if (argc == 1) {
cerr << "Usage- " << argv[0] << " water_matrix [max-t] >output.asc\n";
exit(-1);
}
int k = 1;
string matname(argv[k++]);
uint max_t = 0;
if (k != argc)
max_t = strtoul(argv[k++], 0, 10);
Math::Matrix<int> M;
cerr << "Reading matrix...\n";
readAsciiMatrix(matname, M);
uint m = M.rows();
uint n = M.cols();
if (max_t == 0)
max_t = n/10;
cerr << boost::format("Water matrix is %d x %d\n") % m % n;
cout << "# " << hdr << endl;
cout << "# tau\tavg\tstdev\tsterr\n";
cerr << "Processing- ";
for (uint tau=0; tau<max_t; ++tau) {
vector<double> survivals;
if (tau % 100 == 0)
cerr << '.';
for (uint j=0; j<m; ++j) {
uint inside = 0;
uint pairs = 0;
for (uint t=0; t<n-tau-1; ++t)
if (M(j, t))
{
++pairs;
if (M(j, t+tau))
++inside;
}
if (pairs)
survivals.push_back(static_cast<double>(inside) / (pairs));
}
dTimeSeries ts(survivals);
cout << tau << '\t' << ts.average() << '\t' << ts.stdev() << '\t' << ts.sterr() << endl;
}
cerr << " Done\n";
}
| 1,357
|
C++
|
.cpp
| 49
| 23.265306
| 92
| 0.551779
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,146
|
blob_contact.cpp
|
GrossfieldLab_loos/Packages/DensityTools/blob_contact.cpp
|
/*
blob_contact.cpp
Find residues within a given distance of a blob
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2012, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <DensityGrid.hpp>
#include <DensityTools.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
GCoord findMinCoord(const vector<GCoord>& coords) {
GCoord min(numeric_limits<double>::max(),
numeric_limits<double>::max(),
numeric_limits<double>::max());
for (vector<GCoord>::const_iterator i = coords.begin(); i != coords.end(); ++i)
for (uint j=0; j<3; ++j)
if ((*i)[j] < min[j])
min[j] = (*i)[j];
return(min);
}
GCoord findMaxCoord(const vector<GCoord>& coords) {
GCoord max(numeric_limits<double>::min(),
numeric_limits<double>::min(),
numeric_limits<double>::min());
for (vector<GCoord>::const_iterator i = coords.begin(); i != coords.end(); ++i)
for (uint j=0; j<3; ++j)
if ((*i)[j] > max[j])
max[j] = (*i)[j];
return(max);
}
vector<GCoord> findBlobCoords(DensityGrid<int>& grid, const int blobid) {
DensityGridpoint griddims = grid.gridDims();
vector<GCoord> coords;
for (int k=0; k<griddims.z(); ++k)
for (int j=0; j<griddims.y(); ++j)
for (int i=0; i<griddims.x(); ++i) {
DensityGridpoint grid_coord(i, j, k);
if (grid(grid_coord) == blobid)
coords.push_back(grid.gridToWorld(grid_coord));
}
return(coords);
}
vector<int> findResiduesNearBlob(const vector<GCoord>& blob, const vector<AtomicGroup>& residues, const double threshold) {
double thresh2 = threshold * threshold;
vector<int> nearby(residues.size(), 0);
for (uint k=0; k<residues.size(); ++k) {
bool flag = false;
for (uint j=0; j<residues[k].size() && !flag; ++j) {
GCoord c = residues[k][j]->coords();
for (uint i=0; i<blob.size(); ++i) {
double d = c.distance2(blob[i]);
if (d <= thresh2) {
flag = true;
break;
}
}
}
nearby[k] = flag;
}
return(nearby);
}
vector<double> calculatePercentageContacts(const RealMatrix& M) {
vector<long> sum(M.cols()-1, 0);
for (uint i=1; i<M.cols(); ++i)
for (uint j=0; j<M.rows(); ++j)
sum[i-1] += M(j, i);
vector<double> occ(M.cols()-1, 0.0);
for (uint i=0; i<M.cols()-1; ++i)
occ[i] = static_cast<double>(sum[i]) / M.rows();
return(occ);
}
int main(int argc, char *argv[]) {
if (argc != 7) {
cerr << "Usage- blob_contact model traj selection skip blobid distance <grid >out.asc 2>report.txt\n";
cerr << "Note: requires an grid with blob ids (i.e. output from blobid)\n";
exit(-1);
}
string hdr = invocationHeader(argc, argv);
int k = 1;
AtomicGroup model = createSystem(argv[k++]);
pTraj traj = createTrajectory(argv[k++], model);
AtomicGroup residue_subset = selectAtoms(model, argv[k++]);
vector<AtomicGroup> residues = residue_subset.splitByResidue();
uint skip = strtoul(argv[k++], 0, 10);
int blobid = strtol(argv[k++], 0, 10);
double distance = strtod(argv[k++], 0);
DensityGrid<int> grid;
cin >> grid;
vector<GCoord> blob = findBlobCoords(grid, blobid);
if (blob.empty()) {
cerr << boost::format("ERROR- no voxels found for blobid %d\n") % blobid;
exit(-10);
}
GCoord blobmin = findMinCoord(blob);
GCoord blobmax = findMaxCoord(blob);
ostringstream shdr;
shdr << hdr << endl;
shdr << boost::format("# Blob bounding box is %s x %s\n") % blobmin % blobmax;
shdr << boost::format("# Blob has %d voxels\n") % blob.size();
shdr << "# Residue list...\n";
for (uint i=0; i<residues.size(); ++i)
shdr << boost::format("# %d : %d %d %s %s\n")
% i
% residues[i][0]->id()
% residues[i][0]->resid()
% residues[i][0]->resname()
% residues[i][0]->segid();
uint n = traj->nframes();
if (skip > 0) {
n -= skip;
traj->readFrame(skip-1);
}
RealMatrix M(n, residues.size()+1);
uint t = 0;
while (traj->readFrame()) {
traj->updateGroupCoords(model);
M(t, 0) = t + skip;
vector<int> nearby = findResiduesNearBlob(blob, residues, distance);
for (uint i=0; i<nearby.size(); ++i)
M(t, i+1) = nearby[i];
++t;
}
writeAsciiMatrix(cout, M, shdr.str());
cerr << "# " << hdr << endl;
cerr << "# gnuplot-col\tresid\tatomid\tfractional contact\n";
vector<double> fraction = calculatePercentageContacts(M);
for (uint i=0; i<residues.size(); ++i) {
cerr << boost::format("%d\t%d\t%d\t%f\n")
% (i+2)
% residues[i][0]->resid()
% residues[i][0]->id()
% fraction[i];
}
}
| 5,434
|
C++
|
.cpp
| 150
| 31.546667
| 123
| 0.635544
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,147
|
gridslice.cpp
|
GrossfieldLab_loos/Packages/DensityTools/gridslice.cpp
|
/*
gridslice.cpp
Takes a double grid and extracts a plane from it as a matrix...
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <boost/tuple/tuple.hpp>
#include <DensityGrid.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
typedef Math::Matrix<double, Math::RowMajor> Matrix;
void invalidIndex(int i) {
cerr << "ERROR - invalid plane index " << i << endl;
exit(-1);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
cerr << "Usage- gridslice [i|j|k] index <grid >matrix\n";
cerr <<
"\n"
"Gridslice extracts a slice of the grid and writes it out\n"
"as a Matlab/Octave/Gnuplot compatible ASCII matrix.\n"
"The first option (i, j, or k) determines the orientation\n"
"of the slice. The index represents the coordinate in the\n"
"direction. For example, \"k 20\" means extract the plane\n"
"when k=20 (an i,j-plane). Using \"i 13\" means extract the\n"
"plane when i=13 (a j,k-plane).\n";
exit(-1);
}
string hdr = invocationHeader(argc, argv);
string plane(argv[1]);
int idx = atoi(argv[2]);
DensityGrid<double> grid;
cin >> grid;
DensityGridpoint dims = grid.gridDims();
cerr << boost::format("Grid dimensions are %d x %d x %d (i x j x k)\n") % dims[0] % dims[1] % dims[2];
if (plane == "k") {
if (idx > dims[2])
invalidIndex(idx);
Matrix M(dims[1]+1, dims[0]+1);
for (int j=0; j<dims[1]; ++j)
for (int i=0; i<dims[0]; ++i)
M(j,i) = grid(idx,j,i);
writeAsciiMatrix(cout, M, hdr);
} else if (plane == "j") {
if (idx > dims[1])
invalidIndex(idx);
Matrix M(dims[2]+1, dims[0]+1);
for (int k=0; k<dims[2]; ++k)
for (int i=0; i<dims[0]; ++i)
M(k,i) = grid(k,idx,i);
writeAsciiMatrix(cout, M, hdr);
} else if (plane == "i") {
if (idx > dims[0])
invalidIndex(idx);
Matrix M(dims[2]+1, dims[1]+1);
for (int k=0; k<dims[2]; ++k)
for (int j=0; j<dims[1]; ++j)
M(k,j) = grid(k,j,idx);
writeAsciiMatrix(cout, M, hdr);
} else {
cerr << "ERROR - unknown plane '" << plane << "'\n";
exit(-1);
}
}
| 3,015
|
C++
|
.cpp
| 82
| 32.463415
| 104
| 0.65093
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,148
|
griddiff.cpp
|
GrossfieldLab_loos/Packages/DensityTools/griddiff.cpp
|
/*
griddiff.cpp
Subtract one grid from another (required grids to match)
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2012, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <DensityGrid.hpp>
#include <DensityTools.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
int main(int argc, char *argv[]) {
if (argc != 3) {
cerr << "Usage- griddiff grid1 grid2 >grid1-grid2\n";
exit(-1);
}
string hdr = invocationHeader(argc, argv);
DensityGrid<double> grid1;
DensityGrid<double> grid2;
int k = 1;
ifstream ifs1(argv[k++]);
ifs1 >> grid1;
ifstream ifs2(argv[k++]);
ifs2 >> grid2;
DensityGridpoint dims1 = grid1.gridDims();
DensityGridpoint dims2 = grid2.gridDims();
if (dims1 != dims2) {
cerr << "Error- the grid sizes must match\n";
exit(-2);
}
if (grid1.minCoord() != grid2.minCoord()
|| grid1.maxCoord() != grid2.maxCoord()) {
cerr << "Error- the extents of the grids do not match\n";
exit(-3);
}
for (long i = 0; i<grid1.size(); ++i)
grid1(i) -= grid2(i);
grid1.addMetadata(hdr);
cout << grid1;
}
| 1,895
|
C++
|
.cpp
| 55
| 31.145455
| 77
| 0.717666
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,149
|
water-sides.cpp
|
GrossfieldLab_loos/Packages/DensityTools/water-sides.cpp
|
/*
water-sides.cpp
Desc:
Classifies a water as being on one side of the membrane or the
other or inside the membrane (1 = upper, 0 = inside, -1 = lower).
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <limits>
#include <boost/format.hpp>
#include <DensityTools.hpp>
using namespace std;
using namespace loos;
// @cond TOOLS_INTERNAL
typedef std::pair<double,double> Range;
typedef Math::Matrix<int, Math::ColMajor> Matrix;
Range membrane(0.0, 0.0);
string model_name, traj_name, selection_string;
enum Location { UPPER = 1, MEMBRANE = 0, LOWER = -1 };
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\n"
"\tClassify waters as above, below, or inside a membrane (based on Z-coordinate)\n"
"\n"
"DESCRIPTION\n"
"\n"
"\twater-sides constructs a TxN matrix where T is the size of the trajectory (# of frames)\n"
"and N is the number of water molecules. Each element has a value of 1 (above membrane),\n"
"0 (inside membrane), or -1 (below membrane). The classification of the water is based\n"
"solely on it's z-coordinate and the range specified on the command line.\n"
"\n"
"\nEXAMPLES\n"
"\twater-sides foo.pdb foo.dcd -15 15\n"
"This example uses the default water selection (\"name == 'OH2'\") and places the\n"
"membrane at -15 <= Z <= 15\n"
"\n"
"\twater-sides --selection 'name == \"HOH\"' foo.pdb foo.dcd -25 20\n"
"This example picks all atoms called \"HOH\" as waters and places the membrane\n"
"at -25 <= Z <= 20\n"
;
return(msg);
}
class WaterSidesOptions : public opts::OptionsPackage {
public:
WaterSidesOptions() : lower_bounds(0.0), upper_bounds(0.0) { }
void addHidden(po::options_description& options) {
options.add_options()
("lower", po::value<double>(&lower_bounds), "Lower leaflet bounds")
("upper", po::value<double>(&upper_bounds), "Upper leaflet bounds");
}
void addPositional(po::positional_options_description& options) {
options.add("lower", 1);
options.add("upper", 1);
}
bool check(po::variables_map& map) {
return(! (map.count("lower") && map.count("upper")) );
}
string help() const { return("membrane-lower-bounds membrane-upper-bounds"); }
string print() const {
ostringstream oss;
oss << boost::format("lower=%f, upper=%f") % lower_bounds % upper_bounds;
return(oss.str());
}
double lower_bounds, upper_bounds;
};
// @endcond
Range parseRange(const string& s) {
double a, b;
int i = sscanf(s.c_str(), "%lf:%lf", &a, &b);
if (i != 2) {
cerr << "Parse error with " << s << endl;
exit(-1);
}
return(Range(a,b));
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions *basic_opts = new opts::BasicOptions(fullHelpMessage());
opts::BasicSelection *basic_selection = new opts::BasicSelection("name == 'OH2'");
opts::TrajectoryWithFrameIndices *basic_traj = new opts::TrajectoryWithFrameIndices;
WaterSidesOptions *my_opts = new WaterSidesOptions;
opts::AggregateOptions options;
options.add(basic_opts).add(basic_selection).add(basic_traj).add(my_opts);
if (!options.parse(argc, argv)) {
exit(0);
}
AtomicGroup model = basic_traj->model;
pTraj traj = basic_traj->trajectory;
AtomicGroup subset = selectAtoms(model, basic_selection->selection);
vector<uint> frames = basic_traj->frameList();
uint n = subset.size();
uint m = frames.size();
Matrix M(m,n+1);
for (uint j=0; j<m; ++j) {
traj->readFrame(frames[j]);
traj->updateGroupCoords(subset);
M(j, 0) = frames[j];
for (uint i=0; i<n; ++i) {
GCoord c = subset[i]->coords();
Location l;
if (c[2] > membrane.second)
l = UPPER;
else if (c[2] >= membrane.first)
l = MEMBRANE;
else
l = LOWER;
M(j, i+1) = l;
}
}
writeAsciiMatrix(cout, M, hdr);
}
| 4,744
|
C++
|
.cpp
| 128
| 33.15625
| 97
| 0.682991
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,150
|
water-inside.cpp
|
GrossfieldLab_loos/Packages/DensityTools/water-inside.cpp
|
/*
water-inside.cpp
(c) 2008 Tod D. Romo,
Grossfield Lab,
University of Rochester Medical and Dental School
Applies a given set of criteria to determine whether or not a water
is inside a protein. A matrix is then built up where each column
represents a timepoint in the trajectory and each row is the
internal water state (i.e. 1 = water is inside, 0 = water is not
inside)
Also tracks the volume of the probe region (i.e. what's defined as
inside, if possible) and writes out a list of atomids that describe
which atoms go with which rows of the matrix.
*/
#include <loos.hpp>
#include <loos.hpp>
#include <cmath>
#include <boost/format.hpp>
#include <DensityGrid.hpp>
#include <DensityTools.hpp>
#include <DensityOptions.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
typedef Math::Matrix<int, Math::ColMajor> Matrix;
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\n"
"\tClassify waters as inside a protein or not in a trajectory\n"
"\n"
"DESCRIPTION\n"
"\n"
"\twater-inside applies a user-specified set of criteria to determine\n"
"whether or not water is inside a protein. A matrix is constructed where\n"
"each column is a time-series for each water. A 1 means the corresponding\n"
"water is inside the protein, and 0 means it's not. The volume of the probe region\n"
"is also tracked (if possible), and written out separately. In addition, a file\n"
"is written that maps the water atomids to the columns of the matrix.\n"
"See water-hist for more information about internal-water criteria.\n"
"\n"
"\nEXAMPLES\n"
"\twater-inside --prefix water foo.pdb foo.dcd\n"
"This example will use the axis filter for water (i.e. water atoms within\n"
"the default radius of 10 Angstroms from the first principal axis of the protein\n"
"selection. The default water selection (name == 'OH2') and protein selection\n"
"(name == 'CA') are used. The output prefix is set to 'water', so 'water.asc',\n"
"'water.vol', and 'water.atoms' will be created containing the time-series matrix,\n"
"the internal water region volume, and the atom mapping respectively.\n\n"
"\twater-inside --mode radius --radius 5 --prot 'resid == 65'\\\n"
"\t --prefix pocket foo.pdb foo.dcd\n"
"This example will find water atoms (using the default selection) that are within\n"
"5 Angstroms of any atom in residue 65, and use the output prefix 'pocket'.\n"
"\n"
"NOTES\n"
"\tLOOS does not care what is called a protein or water. You can use any selection,\n"
"for example, to track ligands, or lipids, etc.\n"
"\n"
"SEE ALSO\n"
"\twater-hist\n"
;
return(msg);
}
void writeAtomIds(const string& fname, const AtomicGroup& grp, const string& hdr) {
ofstream ofs(fname.c_str());
AtomicGroup::const_iterator ci;
uint t = 0;
ofs << "# " << hdr << endl;
ofs << "# i\tatomid(i)\tresidue(i)\n";
for (ci = grp.begin(); ci != grp.end(); ++ci) {
ofs << boost::format("%u\t%d\t%s-%d\n") % t++ % (*ci)->id() % (*ci)->name() % (*ci)->resid();
}
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* basopts = new opts::BasicOptions(fullHelpMessage());
opts::OutputPrefix* prefopts = new opts::OutputPrefix;
opts::TrajectoryWithFrameIndices* tropts = new opts::TrajectoryWithFrameIndices;
opts::BasicWater* watopts = new opts::BasicWater;
opts::AggregateOptions options;
options.add(basopts).add(prefopts).add(tropts).add(watopts);
if (!options.parse(argc, argv))
exit(-1);
AtomicGroup model = tropts->model;
pTraj traj = tropts->trajectory;
vector<uint> frames = tropts->frameList();
AtomicGroup subset = selectAtoms(model, watopts->prot_string);
AtomicGroup waters = selectAtoms(model, watopts->water_string);
uint m = waters.size();
uint n = traj->nframes();
Matrix M(m,n);
Math::Matrix<double> V(n, 1);
cerr << boost::format("Water matrix is %d x %d.\n") % m % n;
uint i = 0;
cerr << "Processing - ";
for (vector<uint>::iterator t = frames.begin(); t != frames.end(); ++t) {
if (i % 100 == 0)
cerr << ".";
traj->readFrame(*t);
traj->updateGroupCoords(model);
vector<int> mask = watopts->filter_func->filter(waters, subset);
if (mask.size() != m) {
cerr << boost::format("ERROR - returned mask has size %u but expected %u.\n") % mask.size() % m;
exit(-10);
}
for (uint j=0; j<m; ++j)
M(j,i) = mask[j];
V(i,0) = watopts->filter_func->volume();
++i;
}
cerr << " done\n";
writeAsciiMatrix(prefopts->prefix + ".asc", M, hdr);
writeAsciiMatrix(prefopts->prefix + ".vol", V, hdr);
writeAtomIds(prefopts->prefix + ".atoms", waters, hdr);
}
| 4,853
|
C++
|
.cpp
| 116
| 37.793103
| 102
| 0.678313
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,151
|
pick_blob.cpp
|
GrossfieldLab_loos/Packages/DensityTools/pick_blob.cpp
|
/*
pick_blob.cpp
Given an grid-mask, a PDB, and a selection, finds the blob closest
to ANY atom in the selection...
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <algorithm>
#include <limits>
#include <DensityGrid.hpp>
using namespace std;
using namespace loos;
using namespace loos::DensityTools;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// @cond TOOL_INTERNAL
struct Blob {
Blob() : closest_point(0,0,0), grid_dist(numeric_limits<double>::max()),
real_dist(numeric_limits<double>::max()) { }
int id;
DensityGridpoint closest_point;
double grid_dist;
double real_dist;
};
// @endcond
int debug = 0;
string model_name, selection;
GCoord spot;
vector<int> picked_ids;
bool use_spot = false;
bool largest = false;
double range = 0.0;
bool query = false;
// @cond TOOLS_INTERNAL
string fullHelpMessage(void) {
string msg =
"SYNOPSIS\n"
"\n"
"\tIdentify the blob closest to a user-specified criterion\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tpick_blobs finds the blob closest to a user input. Several methods\n"
"of input are supported. For instance, given a pdb and selection string\n"
"the blob closest to the selection will be returned. Additionally, a blob\n"
"may be selected using its ID (see blobid). A point within the grid may\n"
"also be used. A range of distances and the largest blob within the range\n"
"are alternate criteria.\n"
"\n"
"The input is an integer grid (from blobid), and the output is another integer-grid\n"
"that can be used to mask a density grid.\n"
"\n"
"EXAMPLES\n"
"\tblobid --threshold 1 <foo.grid >foo_id.grid\n"
"\tpick_blob --model foo.pdb --selection 'resid==65' < foo_id.grid > foo_picked.grid\n"
"This example first segments the density at 1.0, and then picks the blob closest to\n"
"any atom in residue 65 in the model.\n"
"\n"
"\tpick_blob --point '(13,7,3)' <foo.grid >foo_picked.grid\n"
"This example picks the blob nearest coordinates (13,7,3) in real-space (i.e.\n"
"Angstroms).\n"
"\n"
"\tpick_blob --model foo.pdb --selection 'resid==65' --range 15 <foo_id.grid >foo_picked.grid\n"
"This example finds ALL blobs that are within 15 Angstroms of any atom in residue 65.\n"
"\n"
"\tpick_blob --model foo.pdb --selection 'resid==64' --range 15 --largest 1 <foo_id.grid >foo_picked.grid\n"
"This example is as above, except that only the largest blob within 15 Angstroms is picked,\n"
"rather than ALL blobs within 15 Angstroms.\n"
"\n"
"SEE ALSO\n"
"\tblobid, gridmask\n";
return(msg);
}
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("query", po::value<bool>(&query)->default_value(false), "Query nearby blobs, do NOT write out a grid")
("model", po::value<string>(&model_name)->default_value(""), "Select using this model (must have coords)")
("selection", po::value<string>(&selection)->default_value(""), "Select atoms within the PDB to find nearest blob")
("id", po::value<string>(&id_string), "Select blob with this ID")
("point", po::value<string>(&point_spec), "Select blob closest to this point")
("range", po::value<double>(&range), "Select blobs that are closer than this distance")
("largest", po::value<bool>(&largest)->default_value(false), "Select only the largest blob that fits the distance criterion");
}
bool postConditions(po::variables_map& vm) {
if (!model_name.empty()) {
if (selection.empty()) {
cerr << "Error: must provide a selection when using a model to select blobs\n";
return(false);
}
} else if (!point_spec.empty()) {
use_spot = true;
istringstream iss(point_spec);
if (!(iss >> spot)) {
cerr << "Error: cannot parse coordinate " << point_spec << endl;
return(false);
}
} else if (!id_string.empty()) {
picked_ids = parseRangeList(id_string);
} else {
cerr << "Error: must specify either a PDB with selection, a point, or a blob-ID to pick\n";
return(false);
}
return(true);
}
string spot_spec;
string point_spec;
string id_string;
};
void zapGrid(DensityGrid<int>& grid, const vector<int>& vals) {
DensityGridpoint dims = grid.gridDims();
for (int k=0; k<dims[2]; k++)
for (int j=0; j<dims[1]; j++)
for (int i=0; i<dims[0]; i++) {
DensityGridpoint point(i,j,k);
int val = grid(point);
vector<int>::const_iterator ci = find(vals.begin(), vals.end(), val);
if (ci == vals.end())
grid(point) = 0;
}
}
int maxBlobId(const DensityGrid<int>& grid) {
DensityGridpoint dims = grid.gridDims();
long k = dims[0] * dims[1] * dims[2];
int maxid = 0;
for (long i=0; i<k; i++)
if (grid(i) > maxid)
maxid = grid(i);
return(maxid);
}
vector<Blob> pickBlob(const DensityGrid<int>& grid, const vector<GCoord>& points) {
vector<DensityGridpoint> gridded;
vector<GCoord>::const_iterator ci;
for (ci = points.begin(); ci != points.end(); ++ci)
gridded.push_back(grid.gridpoint(*ci));
int maxid = maxBlobId(grid);
if (debug >= 1)
cerr << boost::format("Found %d total blobs in grid.\n") % maxid;
vector<Blob> blobs(maxid+1, Blob());
DensityGridpoint dims = grid.gridDims();
for (int k=0; k<dims[2]; k++)
for (int j=0; j<dims[1]; j++)
for (int i=0; i<dims[0]; i++) {
DensityGridpoint point(i,j,k);
int id = grid(point);
if (!id)
continue;
vector<DensityGridpoint>::iterator cj;
for (cj = gridded.begin(); cj != gridded.end(); ++cj) {
double d = point.distance2(*cj);
if (d < blobs[id].grid_dist) {
blobs[id].id = id;
blobs[id].grid_dist = d;
blobs[id].closest_point = point;
GCoord a = grid.gridToWorld(point);
GCoord b = grid.gridToWorld(*cj);
blobs[id].real_dist = a.distance2(b);
}
}
}
if (debug > 1) {
cerr << "* DEBUG: Blob list dump *\n";
for (int i=0; i<=maxid; i++)
cerr << boost::format("\tid=%d, grid_dist=%12.8g, real_dist=%12.8g\n")
% blobs[i].id
% blobs[i].grid_dist
% blobs[i].real_dist;
}
vector<Blob> res;
if (range == 0.0) {
double min = numeric_limits<double>::max();
int id = -1;
for (int i=1; i<=maxid; i++)
if (blobs[i].grid_dist < min) {
min = blobs[i].grid_dist;
id = i;
}
if (id > 0)
res.push_back(blobs[id]);
} else {
for (int i=1; i<=maxid; i++)
if (blobs[i].real_dist <= range)
res.push_back(blobs[i]);
}
return(res);
}
// @endcond
int main(int argc, char *argv[]) {
string header = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
vector<GCoord> points;
if (picked_ids.empty()) {
if (use_spot)
points.push_back(spot);
else {
AtomicGroup model = createSystem(model_name);
AtomicGroup subset = selectAtoms(model, selection);
for (AtomicGroup::iterator i = subset.begin(); i != subset.end(); ++i)
points.push_back((*i)->coords());
}
}
DensityGrid<int> grid;
cin >> grid;
cerr << "Read in grid with dimensions " << grid.gridDims() << endl;
GCoord delta = grid.gridDelta();
double voxel_volume = 1.0 / delta[0];
for (int i=1; i<3; i++)
voxel_volume *= (1.0 / delta[i]);
if (picked_ids.empty()) {
vector<Blob> picks = pickBlob(grid, points);
if (picks.empty()) {
cerr << "Warning - no blobs picked\n";
exit(0);
}
cerr << "Picked " << picks.size() << " blobs:\n";
vector<Blob>::const_iterator ci;
vector<int> ids;
for (ci = picks.begin(); ci != picks.end(); ++ci) {
cerr << boost::format("\tid=%d, dist=%12.8g\n") % ci->id % ci->real_dist;
ids.push_back(ci->id);
}
if (!query) {
zapGrid(grid, ids);
cout << grid;
}
} else if (!query) {
zapGrid(grid, picked_ids);
cout << grid;
}
exit(0);
}
| 8,999
|
C++
|
.cpp
| 252
| 31.404762
| 132
| 0.652661
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,152
|
water-lib.cpp
|
GrossfieldLab_loos/Packages/DensityTools/water-lib.cpp
|
// -------------------------------------------------
// Water (density) Library
// -------------------------------------------------
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009 Tod D. Romo, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "water-lib.hpp"
namespace loos {
namespace DensityTools {
std::vector<GCoord> getBounds(pTraj& traj, AtomicGroup& g, const std::vector<uint>& indices) {
double d = std::numeric_limits<double>::max();
GCoord min(d, d, d);
GCoord max(-d, -d, -d);
for (std::vector<uint>::const_iterator i = indices.begin(); i != indices.end(); ++i) {
traj->readFrame(*i);
traj->updateGroupCoords(g);
std::vector<GCoord> bdd = g.boundingBox();
for (int j=0; j<3; ++j) {
if (bdd[0][j] < min[j])
min[j] = bdd[0][j];
if (bdd[1][j] > max[j])
max[j] = bdd[1][j];
}
}
std::vector<GCoord> bdd;
bdd.push_back(min);
bdd.push_back(max);
return(bdd);
}
};
};
| 1,786
|
C++
|
.cpp
| 44
| 34.863636
| 98
| 0.623248
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,153
|
AverageLinkage.cpp
|
GrossfieldLab_loos/Packages/Clustering/AverageLinkage.cpp
|
#include "AverageLinkage.hpp"
namespace Clustering
{
Eigen::Matrix<dtype, 1, Eigen::Dynamic> AverageLinkage::dist(idxT idxA, idxT idxB)
{
idxT sizeA = currStg[idxA]->size();
idxT sizeB = currStg[idxB]->size();
return (sizeA * clusterDists.row(idxA) + sizeB * clusterDists.row(idxB)) / (sizeA + sizeB);
}
}
| 325
|
C++
|
.cpp
| 10
| 29.6
| 95
| 0.692063
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,154
|
ClusteringOptions.cpp
|
GrossfieldLab_loos/Packages/Clustering/ClusteringOptions.cpp
|
#include "ClusteringOptions.hpp"
#include "ClusteringUtils.hpp"
#include <iostream>
#include <string>
namespace Clustering{
void ClusteringOptions::addGeneric(po::options_description & opts){
opts.add_options()
("score-file,f", po::value<std::string>(&similarity_filename), "File containing whitespace-delimited pairwise similarities.")
("stream,s", po::bool_switch(&stream_mode), "Read similarities from stdin.");
}
bool ClusteringOptions::postConditions(po::variables_map& vm) {
if (stream_mode && !similarity_filename.empty()){
std::cerr << "Usage Error:\nYou've asked that the tool both reads a file: \n \"" << similarity_filename << "\"\nand that it read from stdin. \n";
return false;
}
if (stream_mode) {
try {
similarityScores = readMatrixFromStream<dtype>(std::cin);
}
catch(const loos::LOOSError &e) {
std::cerr << e.what() << '\n';
return false;
}
}
else if (!similarity_filename.empty()){
std::ifstream stream;
stream.open(similarity_filename);
try{
similarityScores = readMatrixFromStream<dtype>(stream);
}
catch(const loos::LOOSError &e) {
std::cerr << e.what() << '\n';
return false;
}
}
else // false causes briefhelp print and exit
return false;
return true;
}
}
| 1,372
|
C++
|
.cpp
| 40
| 28.525
| 152
| 0.645675
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
755,155
|
KGS.cpp
|
GrossfieldLab_loos/Packages/Clustering/KGS.cpp
|
#include "KGS.hpp"
#include "ClusteringUtils.hpp"
#include <iostream>
using std::cout;
using std::endl;
using std::vector;
using namespace Eigen;
namespace Clustering
{
// call this to search for a cutoff stage in clustering.
idxT KGS::cutoff()
{
dtype min = avgSpread.minCoeff();
dtype max = avgSpread.maxCoeff();
dtype norm = (eltCount - 2) / (max - min);
#ifdef DEBUG
cout << "penalties:" << endl
<< penalties << endl;
cout << "avgSpreads: " << endl
<< avgSpread << endl;
#endif
Matrix<dtype, Eigen::Dynamic, 1> normAvSp = (norm * (avgSpread.array() - min) + 1).matrix();
#ifdef DEBUG
cout << "normalized avgSpreads:" << endl
<< normAvSp << endl;
#endif
penalties += normAvSp;
#ifdef DEBUG
cout << "penalties after adding normAvSpreads:" << endl
<< penalties << endl;
#endif
idxT minIndex;
penalties.minCoeff(&minIndex);
// need to increment minindex to correspond to stage,
// since avgSpread (and therefore penalty) undefined at stage 0.
// This has caused us to use a penalties vector that is eltCount-1 long.
return minIndex + 1;
}
void KGS::penalty()
{
// look up merged clustersize so we can assess change in spread.
idxT sizeA = (clusterTraj[stage - 1][minRow]).size();
idxT sizeB = (clusterTraj[stage - 1][minCol]).size();
idxT sizeAB = sizeA + sizeB;
#ifdef DEBUG
cout << "sizeA: " << sizeA << endl;
cout << "sizeB: " << sizeB << endl;
#endif
dtype normSpA{0};
dtype normSpB{0};
dtype sumCrossDists = sizeA * sizeB * distOfMerge(stage);
// spread of A will be sum of distances of elts in a divided by (N*(N-1)/2)
// This is for both A and B, hence two goes to the numerator of their sum.
// nClusters goes up to record addition of one merged (nontrivial cluster)
if (merged)
{
// determine if the merge created a nontrivial cluster
if (sizeA == 1)
currentClusterCount++;
else
normSpA = 0.5 * (sizeA * (sizeA - 1)) * spreads(minRow);
// account for the case where the merged cluster was nontrivial
if (sizeB > 1)
{
currentClusterCount--;
normSpB = 0.5 * (sizeB * (sizeB - 1)) * spreads(minCol);
}
// spreads(minRow) = 2*(2*(normSpA + normSpB) + sumCrossDists)/(sizeAB*(sizeAB-1));
// remove spreads[minCol]
removeRow(spreads, minCol);
if (minCol < minRow)
spreads(minRow - 1) = 2 * (2 * (normSpA + normSpB) + sumCrossDists) / (sizeAB * (sizeAB - 1));
else
spreads(minRow) = 2 * (2 * (normSpA + normSpB) + sumCrossDists) / (sizeAB * (sizeAB - 1));
}
else
{
// determine if the merge created a nontrivial cluster
if (sizeB == 1)
currentClusterCount++;
else
normSpB = 0.5 * (sizeB * (sizeB - 1)) * spreads(minCol);
// account for the case where the merged cluster was nontrivial
if (sizeA > 1)
{
currentClusterCount--;
normSpA = 0.5 * (sizeA * (sizeA - 1)) * spreads(minCol);
}
// spreads(minCol) = 2*(2*(normSpA + normSpB) + sumCrossDists)/(sizeAB*(sizeAB-1));
// remove spreads[minRow]
removeRow(spreads, minRow);
if (minRow < minCol)
spreads(minCol - 1) = 2 * (2 * (normSpA + normSpB) + sumCrossDists) / (sizeAB * (sizeAB - 1));
else
spreads(minCol) = 2 * (2 * (normSpA + normSpB) + sumCrossDists) / (sizeAB * (sizeAB - 1));
}
// from paper, divide only by number of nontrivial clusters.
avgSpread(stage - 1) = spreads.sum() / currentClusterCount;
// set penalties at the number of clusters, which is the same as eltCount - stage
penalties(stage - 1) = eltCount - stage;
}
} // namespace Clustering
| 3,585
|
C++
|
.cpp
| 102
| 31.480392
| 100
| 0.653835
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,156
|
cluster-kgs.cpp
|
GrossfieldLab_loos/Packages/Clustering/cluster-kgs.cpp
|
// cluster-kgs.cpp
// Kelly, Gardner, and Sutcliffe, Prot. Eng. 9 11 1063-1065 (1996)
// hereafter KGS
// To perform exactly the analysis specified there, one must first apply
// one of the all-to-all rmsd tolls (such as rmsds or multi-rmsds) before
// running this tool. Those tools write their RMSD matricies to cout, and
// this tool reads from cin, so the effect can be achieved through a pipe.
#include "Clustering.hpp"
#include "ClusteringOptions.hpp"
#include <iostream>
#include <loos.hpp>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using namespace Clustering;
// namespace opts = loos::OptionsFramework;
const std::string indent = " ";
std::string fullHelpMessage(void) {
std::string helpstr =
"usage: \n"
"cluster-kgs -s < similarity_scores.asc > clustering_results.json \n"
" \n"
"cluster-kgs mimics the clustering aspect of the NMRCLUST utility that is \n"
"incorporated as part of the OLDERADO webserver for structural biology \n"
"informatics. It was originally published as: \n"
"Kelly, Gardner, and Sutcliffe, Prot. Eng. 9 11 1063-1065 (1996) \n"
"This type of clustering exists in other places, most notably in R, and has been\n"
" put to many uses beside clustering protein structures with their RMSD as the \n"
"distance between each structure. It is called cluster-kgs because this method \n"
"is referred to in other contexts (that is, where it is not being used to \n"
"analyze NMR ensembles) as kgs clustering, and because this executable operates \n"
"on a provided similarity matrix it is similarly flexible. Note that we do not \n"
"implement the 'eigen analysis' for cluster center determination, instead \n"
"choosing to use the element from each cluster with the lowest mean distance to \n"
"the other elements in the cluster. \n"
" \n"
"The tool works by reading in a similarity score matrix from a file (or stdin) \n"
"and writing the clustering results to stdout. The results report the index of \n"
"each cluster, with all the elements in each cluster following its index on the \n"
"same line. It will also provide an exemplar (the element nearest the centroid) \n"
"for each cluster in a separate block. The input matrix should be an NxN \n"
"symmetric matrix of similarity scores where the ij-th element is the similarity\n"
" between datum i and datum j. The similarity score matrix is expected to be \n"
"whitespace delimited in the column and newline delimited in the row. '#' is an \n"
"acceptable comment character, but only produces a comment-read at the beginning\n"
"of a line (not at any point in a line, like a comment in a shell script). \n"
"NOTE that the code checks that the matrix you gave it is square, but only uses\n"
"the upper triangle of the matrix. It therefore CAN NOT TELL if the matrix you\n"
"supplied is symmetric. If you are doing something that would produce a non-\n"
"symmetric matrix, that means your \'similarity score\' is either not a metric \n"
"(it is not reflexive: D(i, j) != D(j, i)), or that you have not done a full \n"
"comparison of every data point to every other. In this case, similarity based\n"
"clustering (such as this algorithm) will not work with your input. That will \n"
"not stop this code from outputting a result, however.\n"
"\n"
"In order to mimic the functionality of the OLDERADO tool mentioned above, one \n"
"can use the loos tool rmsds (or similar) to produce the matrix of similarity \n"
"scores. \n"
"For example: \n"
" \n"
"$ rmsds model.pdb ensemble.dcd | cluster-kgs -s > clustering_results.json \n"
" \n"
"would use rmsds to compute the alpha carbon RMSDs from the frame-pairs in \n"
"ensemble.dcd to generate the similarity matrix, then redirect it to cluster-\n"
"kgs, which will read from stdin because the -s flag was thrown. Then the \n"
"clustering results are written to an output file (which should be valid JSON, \n"
"for convenient further scripting). This shell-redirect would also cause the \n"
"distance matrix from rmsds to be written to stderr. Note that in this \n"
"particular command line the RMSD values emitted by rmsds will be in angstroms, \n"
"and will be rounded to 2 digits. For more reported precision (rmsds uses \n"
"doubles internally), use the '-p' flag. If you would like to both save the \n"
"similarities generated in this way, but also not have them written to disk \n"
"before feeding them to the clustering algorithm, you can redirect stderr and \n"
"stdout to separate files: \n"
" \n"
"$ rmsds model.pdb ensemble.dcd | \\\n"
" cluster-kgs -s 1> clustering_results.json 2>distances.asc \n"
" \n"
"You can also read a distance matrix from a file using the -f flag. If you do \n"
"that, it will not be emitted to stderr, and you would write: \n"
"cluster-kgs -f distances.asc > clustering_results.json \n"
" \n"
"Note: the output of multi-rmsds is also compatible with cluster-kgs; \n"
"this is useful when you want to do all-to-all frame comparison across\n"
"2 or more trajectories.\n"
" \n"
"The output from the clustering will be structured as JSON, and will have four \n"
"keys: \n"
" - 'invocation': a string containing the command line used to call cluster-kgs\n"
" - 'clusters': a 2D list containing the assignment of each index to a \n"
" cluster. clusters[i] is a list containing the indices\n"
" assigned to cluster i.\n"
" - 'penalties': the value of the penalty function as a function of the stage\n"
" of agglomeration. \n"
" - 'optimal stage': The index of the minimum value of the penalties \n"
" array. The number of clusters output will be determined\n"
" by this value. If there are 1000 data points and \n"
" 'optimal stage' is 9991, you'll get 10 clusters.\n"
" - 'exemplar': list of indexes into the source trajectory. For each cluster\n"
" this list contains the index of the most central structure,\n"
" defined as the one with the minimum average distance to the \n"
" other structures in the cluster. The clusters are in the \n"
" same order as the 'clusters' array.\n"
;
return helpstr;
}
int main(int argc, char *argv[]) {
std::string hdr = loos::invocationHeader(argc, argv);
opts::BasicOptions *bopts = new opts::BasicOptions(fullHelpMessage());
ClusteringOptions *copts = new ClusteringOptions;
opts::AggregateOptions options;
options.add(bopts).add(copts);
if (!options.parse(argc, argv))
exit(-1);
KGS clusterer(copts->similarityScores);
if (copts->stream_mode)
std::cerr << copts->similarityScores; // Eigen objects stringify.
clusterer.cluster();
idxT optStg = clusterer.cutoff();
vector<idxT> exemplars =
getExemplars(clusterer.clusterTraj[optStg], copts->similarityScores);
// below here is output stuff. All quantities of interest have been obtained.
cout << "{\n";
cout << indent + "\"invocation\": \"" << hdr << "\",\n";
cout << indent + "\"optimal stage\": " << optStg << ",\n";
cout << indent + "\"penalties\": ";
containerAsJSONArr<Eigen::Matrix<dtype, Eigen::Dynamic, 1>>(
clusterer.penalties, cout);
cout << ",\n";
cout << indent + "\"clusters\": ";
vectorVectorsAsJSONArr<idxT>((clusterer.clusterTraj)[optStg], cout, " ");
cout << ",\n";
cout << indent + "\"exemplars\": ";
containerAsJSONArr<vector<idxT>>(exemplars, cout, " ");
cout << "\n";
cout << "}" << endl;
}
| 7,476
|
C++
|
.cpp
| 139
| 52.172662
| 85
| 0.720797
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
755,157
|
ClusteringUtils.cpp
|
GrossfieldLab_loos/Packages/Clustering/ClusteringUtils.cpp
|
#include "ClusteringUtils.hpp"
#include "ClusteringTypedefs.hpp"
#include <iostream>
#include <algorithm>
#include <fstream>
using std::cout;
using std::endl;
using std::istream;
using std::ostream;
using std::sort;
using std::string;
using std::stringstream;
using std::vector;
using namespace Eigen;
namespace Clustering
{
// MatrixXd
// readMatrixFromStream(istream &input, const char commentChar)
// {
// vector<vector<double>> matbuff;
// string line;
// double elt;
// while (getline(input, line))
// {
// // skip commets. Only permits comments at the beginning of lines.
// if (line[0] == commentChar)
// continue;
// stringstream streamline(line);
// vector<double> row;
// // process a row here. Should work for whitespace delimited...
// while (streamline >> elt)
// // if a single line comment char is found, break out to line loop
// row.push_back(elt);
// // push the vector into the matrix buffer.
// matbuff.push_back(row);
// }
// // Populate matrix with numbers.
// // should be a better way to do this with Eigen::Map...
// // though nb mapped eigen matricies are not the same as eigen dense mats.
// Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
// result(matbuff[0].size(), matbuff.size());
// for (idxT i = 0; i < matbuff.size(); i++)
// for (idxT j = i; j < matbuff[0].size(); j++)
// result(i, j) = matbuff[i][j];
// return result;
// };
// use formula (a - b)^2 = a^2 + b^2 -2a*b.
// MatrixXd
// pairwiseDists(const Ref<const MatrixXd> &data)
// {
// const VectorXd data_sq = data.rowwise().squaredNorm();
// MatrixXd distances;
// distances = data_sq.rowwise().replicate(data.rows()) +
// data_sq.transpose().colwise().replicate(data.rows()) -
// 2. * data * data.transpose();
// distances.diagonal().setZero(); // prevents nans from occurring along diag.
// distances = distances.cwiseSqrt();
// return distances;
// }
// possibly naive implementation, relies on keeping full similarity matrix.
// vector<idxT>
// getExemplars(vector<vector<idxT>> &clusters,
// const Ref<const MatrixXd> &distances)
// {
// vector<idxT> exemplars(clusters.size());
// for (idxT cdx = 0; cdx < clusters.size(); cdx++)
// {
// MatrixXd clusterDists(clusters[cdx].size(), clusters[cdx].size());
// for (idxT i = 0; i < clusters[cdx].size(); i++)
// {
// for (idxT j = 0; j < i; j++)
// {
// clusterDists(i, j) = distances(clusters[cdx][i], clusters[cdx][j]);
// }
// }
// idxT centeridx;
// clusterDists = clusterDists.selfadjointView<Upper>();
// clusterDists.colwise().mean().minCoeff(¢eridx);
// exemplars[cdx] = clusters[cdx][centeridx];
// }
// return exemplars;
// }
// from
// <https://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes>
// PermutationMatrix<Dynamic, Dynamic>
// sort_permutation(const Ref<const VectorXd> &v)
// {
// // initialize original index locations
// PermutationMatrix<Dynamic, Dynamic> p(v.size());
// p.setIdentity();
// // sort indexes based on comparing values in v
// sort(p.indices().data(),
// p.indices().data() + p.indices().size(),
// [&v](size_t i1, size_t i2) { return v.data()[i1] < v.data()[i2]; });
// return p;
// }
} // namespace Clustering
| 3,394
|
C++
|
.cpp
| 97
| 33.927835
| 87
| 0.639319
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,158
|
HAC.cpp
|
GrossfieldLab_loos/Packages/Clustering/HAC.cpp
|
#include "HAC.hpp"
#include "ClusteringUtils.hpp"
#include <iostream>
using std::cout;
using std::endl;
using std::unique_ptr;
using std::vector;
using namespace Eigen;
// Merge two clusters into whichever is larger.
// Return true if new composite cluster is minRow, else return false
// In the case where clusters are of equal size, merge into minRow.
namespace Clustering
{
bool HAC::merge()
{
bool ret;
idxT sizeA = currStg[minRow]->size();
idxT sizeB = currStg[minCol]->size();
if (sizeA < sizeB)
{
currStg[minCol]->insert(currStg[minCol]->end(),
currStg[minRow]->begin(),
currStg[minRow]->end());
currStg.erase(currStg.begin() + minRow);
ret = false;
}
else
{
currStg[minRow]->insert(currStg[minRow]->end(),
currStg[minCol]->begin(),
currStg[minCol]->end());
currStg.erase(currStg.begin() + minCol);
ret = true;
}
// append new assortment of clusters to Cluster Trajectory
vector<vector<idxT>> recordAtStg(currStg.size());
for (idxT i = 0; i < currStg.size(); i++)
{
recordAtStg[i] = *(currStg[i]);
}
clusterTraj.push_back(recordAtStg);
return ret;
}
// Run through the clustering cycle, populating the 'trajectory' vectors.
void HAC::cluster()
{
// initialize the list of cluster indices with one index per cluster
vector<vector<idxT>> recordCurrStg(eltCount);
for (idxT i = 0; i < eltCount; i++)
{
unique_ptr<vector<idxT>> cluster_ptr(new vector<idxT>{i});
currStg.push_back(std::move(cluster_ptr));
vector<idxT> clusterRecord{i};
recordCurrStg[i] = clusterRecord;
}
clusterTraj.push_back(recordCurrStg);
// Get the max value to make the diagonal never the minCoeff (see distOfMerge[stage] below)
dtype maxDist = clusterDists.maxCoeff() + 1;
for (stage = 1; stage < eltCount; stage++)
{
#ifdef DEBUG
cout << "stage: " << stage << endl;
#endif
// bind the minimum distance found for dendrogram construction
distOfMerge(stage) = (clusterDists + maxDist * Matrix<dtype, Dynamic, Dynamic>::Identity(
clusterDists.rows(), clusterDists.rows()))
.minCoeff(&minRow, &minCol);
// build merged row. Must happen before clusterTraj merge is performed.
Matrix<dtype, Dynamic, 1> mergedRow = dist(minRow, minCol);
// merge the clusters into whichever of the two is larger. Erase the other.
merged = merge();
#ifdef DEBUG
cout << "clusters:" << endl;
vectorVectorsAsJSONArr(clusterTraj[stage], cout);
#endif
// compute the penalty, if such is needed. Needs cluster merged into.
penalty();
// update the matrix of clusterDists
if (merged)
{ // minRow was the cluster merged into
// update clusterDists to zero out minCol column & row
// removeRow<Matrix<double, -1, -1, 1>>(clusterDists, minCol);
// removeCol<Matrix<double, -1, -1, 1>>(clusterDists, minCol);
removeRow(clusterDists, minCol);
removeCol(clusterDists, minCol);
// remove the column we eliminated from our merged row of distances.
removeRow(mergedRow, minCol);
// recalculate minRow column and row
if (minCol < minRow)
minRow--;
// Note that the dist matrix will not have a zero at this row/col after doing this.
// because of how we have increased the values of the diagonal anyway for the mincoeff
// this should not interfere with anything. But if you're relying on the diagonal to be zero...
clusterDists.row(minRow) = mergedRow;
clusterDists.col(minRow) = mergedRow.transpose();
}
else
{ // minCol was the cluster merged into
// update clusterDists to delete minRow column & row
removeRow(clusterDists, minRow);
removeCol(clusterDists, minRow);
// remove the column we eliminated from our merged row of distances.
removeRow(mergedRow, minRow);
// recalculate minCol column and row
if (minRow < minCol)
minCol--;
clusterDists.row(minCol) = mergedRow;
clusterDists.col(minCol) = mergedRow.transpose();
}
}
stage--;
}
} // namespace Clustering
| 4,233
|
C++
|
.cpp
| 113
| 31.769912
| 101
| 0.663667
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
755,159
|
ufidpick.cpp
|
GrossfieldLab_loos/Packages/Convergence/ufidpick.cpp
|
/*
ufidpick
Picks uniform fiducial structures for a structural histogram, a la Lyman &
Zuckerman, J Phys Chem B (2007) 111:12876-12882
Usage- ufidpick model trajectory selection output-name probability [seed]
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include "fid-lib.hpp"
using namespace std;
using namespace loos;
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tPick fiducial structures for a structural histogram\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool picks structures from a trajectory for use as fiducials in a\n"
"structural histogram. They are picked using bins with a uniform probability. For\n"
"more details, see Lyman & Zuckerman, J Phys Chem B (2007) 111:12876-12882.\n"
"\n"
"EXAMPLES\n"
"\n"
"\tufidpick model.pdb simulation.dcd all 'name == \"CA\"' zuckerman 0.1 >ufidpick.log\n"
"This example uses bins with a probability of 0.1 (i.e. 10 bins), using only\n"
"the alpha-carbons. The output files include a log of what structures were \n"
"picked, stored in ufidpick.log, as well as a trajectory containing just the\n"
"fiducial structures in zuckerman.dcd and the corresponding model file in zuckerman.pdb\n"
"\n"
"SEE ALSO\n"
"\tassign_frames, hierarchy, effsize.pl, neff\n";
return(msg);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
if (argc < 7 || argc > 8) {
cerr << "Usage - " << argv[0] << " model trajectory range|all selection output-name cutoff [seed]\n";
cerr << fullHelpMessage();
exit(-1);
}
int opti = 1;
AtomicGroup model = createSystem(argv[opti++]);
model.clearBonds();
pTraj traj = createTrajectory(argv[opti++], model);
string range(argv[opti++]);
string selection(argv[opti++]);
AtomicGroup subset = selectAtoms(model, selection);
string outname(argv[opti++]);
double cutoff = strtod(argv[opti++], 0);
uint seed;
if (opti < argc) {
seed = strtoul(argv[opti++], 0, 10);
rng_singleton().seed(static_cast<unsigned int>(seed)); // This addresses a bug in earlier BOOSTs
} else
seed = randomSeedRNG();
cout << "# " << hdr << endl;
cout << "# seed = " << seed << endl;
vector<uint> source_frames;
if (range == "all")
for (uint i=0; i<traj->nframes(); ++i)
source_frames.push_back(i);
else
source_frames = parseRangeList<uint>(range);
vector<uint> frames = trimFrames(source_frames, cutoff);
if (frames.size() != source_frames.size())
cout << "# WARNING- truncated last " << source_frames.size() - frames.size() << " frames\n";
boost::tuple<vecGroup, vecUint> result = pickFiducials(subset, traj, frames, cutoff);
cout << "# n\tref\n";
vecGroup fiducials = boost::get<0>(result);
vecUint id = boost::get<1>(result);
for (uint i=0; i<id.size(); ++i)
cout << i << "\t" << id[i] << "\n";
DCDWriter dcd(outname + ".dcd", fiducials, hdr);
PDB pdb = PDB::fromAtomicGroup(fiducials[0]);
pdb.remarks().add(hdr);
string fname = outname + ".pdb";
ofstream ofs(fname.c_str());
ofs << pdb;
}
| 3,912
|
C++
|
.cpp
| 96
| 36.927083
| 105
| 0.692084
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,160
|
expfit.cpp
|
GrossfieldLab_loos/Packages/Convergence/expfit.cpp
|
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2011, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <Simplex.hpp>
#include <limits>
using namespace std;
using namespace loos;
// @cond TOOLS_INTERNAL
typedef pair<double, double> LPoint;
typedef vector<double> vecDouble;
typedef vector<vecDouble> vvecDouble;
struct ExponentialFit {
ExponentialFit(const vector<LPoint>& datapoints) : _datapoints(datapoints) { }
double operator()(const vector<double>& v) {
double sum = 0.0;
for (vector<double>::const_iterator i = v.begin(); i != v.end(); ++i)
if (*i < 0.0)
return(numeric_limits<double>::max());
for (vector<LPoint>::iterator j = _datapoints.begin(); j != _datapoints.end(); ++j) {
double x = j->first;
double y = j->second;
double val = 1.0;
for (vector<double>::const_iterator i = v.begin(); i != v.end();) {
double k = *i++;
double t = *i++;
val += k * exp(-x/t);
}
double d = y - val;
sum += d*d;
}
return(sum);
}
vector<LPoint> _datapoints;
};
// @endcond
vvecDouble readData(const string& fname) {
ifstream ifs(fname.c_str());
if (!ifs) {
cerr << "Error- unable to open " << fname << endl;
exit(-1);
}
return(readTable<double>(ifs));
}
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tExponential fit for bootstrapped-bcom/bcom output\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool calculates a multi-exponential fit to the bootstrapped-bcom/bcom data.\n"
"A Nelder-Mead Simplex is used as the optimizer.\n"
"\n"
"EXAMPLES\n"
"\n"
"\texpfit bcom.asc boot_bcom.asc 5 2 0.7 10 0.3 100\n"
"This tries to fit bcom.asc and boot_bcom.asc using 5 replicas and using a 2-exponential\n"
"with inital coefficients of 0.7 and 0.3 and initial correlation times of 10 and 100\n"
"respectively.\n"
"\n"
"SEE ALSO\n"
"\tbcom, boot_bcom, bootstrap_overlap.pl\n";
return(msg);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
if (argc < 5) {
cerr << "Usage- expfit bcom.asc boot_bcom.asc nreps ndims constant-1 time-1 [constant-2 time-2 ...]\n";
cerr << fullHelpMessage();
exit(-1);
}
int k = 1;
vvecDouble bcom = readData(argv[k++]);
vvecDouble bbcom = readData(argv[k++]);
if (bcom.size() != bbcom.size()) {
cerr << boost::format("Error- bcom has %d datapoints but bbcom has %d\n") % bcom.size() % bbcom.size();
exit(-10);
}
vector<LPoint> datapoints;
for (uint i=0; i<bcom.size(); ++i)
datapoints.push_back(LPoint(bcom[i][0], bbcom[i][1]/bcom[i][1]));
int nreps = atoi(argv[k++]);
int ndims = atoi(argv[k++]);
vector<double> seeds;
vector<double> lens;
ndims *= 2;
if (argc - 5 != ndims) {
cerr << boost::format("Error- only %d seeds were specified, but require %d for %d dimensions\n")
% (argc - 5)
% (ndims)
% (ndims/2);
exit(-1);
}
for (int i=0; i<ndims; ++i) {
double d = strtod(argv[k++], 0);
seeds.push_back(d);
lens.push_back(d/2.0);
}
ExponentialFit fitFunction(datapoints);
while (nreps-- > 0) {
Simplex<double> optimizer(ndims);
optimizer.tolerance(1e-6);
optimizer.maximumIterations(10000);
optimizer.seedLengths(lens);
vector<double> final = optimizer.optimize(seeds, fitFunction);
for (uint i=0; i<final.size(); ++i)
cout << boost::format("%12.8g ") % final[i];
cout << boost::format("\t\t%.6g\n") % optimizer.finalValue();
seeds = final;
}
}
| 4,355
|
C++
|
.cpp
| 126
| 30.214286
| 107
| 0.652403
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,161
|
block_average.cpp
|
GrossfieldLab_loos/Packages/Convergence/block_average.cpp
|
/*
Compute block-averaged standard error for a time series
using the Flyvbjerg & Petersen approach. Outputs the block averaged
standard error as a function of block size -- you'll need to plot it
and estimate the plateau value.
References:
Flyvbjerg, H. & Petersen, H. G. Error estimates on averages
of correlated data J. Chem. Phys., 1989, 91, 461-466
Grossfield, A., and Zuckerman, D. M. Quantifying uncertainty and sampling
quality in biomolecular simulations, Ann. Reports in Comp. Chem., 2009,
5, 23-48
Alan Grossfield
Grossfield Lab
Department of Biochemistry and Biophysics
University of Rochester Medical School
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
string fullHelpMessage(void)
{
string s =
"\n"
"SYNOPSIS\n"
"\n"
"Apply block averaging to estimate standard error of timeseries data\n"
"\n"
"DESCRIPTION\n"
"\n"
"This tool performs a block averaging analysis in order to estimate the \n"
"standard error of a set of time series data. It takes as input a text\n"
"file with white-space delimited data in columns (each time point is a \n"
"row), and returns the estimated standard error as a function of block \n"
"size. \n"
"\n"
"The command line arguments are as follows:\n"
"\n"
"block_average TimeSeriesFile column max_blocks skip\n"
"\n"
"TimeSeriesFile columnated text file (blank lines and lines starting \n"
" with \"#\" are ignored) containing the time series data\n"
"column which column to use for analysis (1-based)\n"
"max_blocks maximum number of blocks to use in the analysis\n"
"skip number of frames to skip from the beginning of the \n"
" trajectory\n"
" \n"
"The algorithm used is in essence that of Flyvbjerg and Petersen [Ref 1],\n"
"and is intended to estimate the standard error for a correlated time\n"
"series. For uncorrelated data, the standard error can be estimated as\n"
"\n"
"SE = sqrt(var(a) / N) = stdev(a) / sqrt(N)\n"
"\n"
"where \"a\" is the quantity of interest and \"N\" is the number of points.\n"
"When the data has correlations, as is the case for nearly all molecular\n"
"dynamics or Monte Carlo simulations, this formula significantly \n"
"underestimates the statistical uncertainty. \n"
"\n"
"The block averaging algorithm works by breaking the \"N\" data points\n"
"into \"M\" equal-sized contiguous blocks , computing the average within \n"
"each block, and then combining them to get the standard deviation in the \n"
"averages. By tracking how that standard dev changes as a function of block \n"
"size, we can estimate the standard error in the limit of inifinite\n"
"block size, which is an estimate of the true standard error. \n"
"\n"
"As the blocks get longer, there are fewer of them, and their variance\n"
"can get very noisy. If you've got really good data, the at long block \n"
"time will be pronounced before the curve gets noisy. If not, you can\n"
"estimate the plateau value by averaging the values at the last few block\n"
"sizes (in a plot of std err vs. block size). If there is no plateau (e.g.\n"
"the curve is still systematically rising), your data is sufficiently \n"
"unconverged that the statistical error cannot be estimated.\n"
"\n"
"It is important to note that block averaging can significantly\n"
"underestimate the standard error for extremely undersampled systems, \n"
"because it is entirely based on what has been seen in the trajectory. For\n"
"example, in the case of a 2-state system with different positions along\n"
"a reaction coordinate x, a very short simulation might only have population\n"
"in 1 state; block averaging this data would produce a small estimated \n"
"uncertainty, because the data looks very homogeneous. Basically, the\n"
"analysis can't know what it hasn't seen.\n"
"\n"
"Note: If the number of blocks doesn't evenly divide the number of points,\n"
"then the remainder will be discarded from the end of the trajectory.\n"
"\n"
"\n"
"See references 1 and 2 for more discussion of the block averaging algorithm.\n"
"\n"
"1. Flyvbjerg, H. & Petersen, H. G. Error estimates on averages \n"
" of correlated data J. Chem. Phys., 1989, 91, 461-466\n"
"\n"
"2. Grossfield, A., and Zuckerman, D. M. Quantifying uncertainty and \n"
" sampling quality in biomolecular simulations, Ann. Reports in Comp. \n"
" Chem., 2009, 5, 23-48\n"
"\n"
"\n"
"EXAMPLE\n"
"\n"
"block_average trj_1.dat 2 20 100\n"
"\n"
"In this case, trj_1.dat is the data file (I used NAMD's output of the box\n"
"dimensions), 2 means analyze the 2nd column (the dimension of the x \n"
"coordinate), 20 means use from 2--20 blocks, and 100 means skip the \n"
"first 100 time points in the file.\n"
"\n"
"The output will look like:\n"
"\n"
"# block_average 'trj_1.dat' '2' '20' '100' - alan (Fri Apr 6 14:22:45 2012) {/home/alan/projects/IBM/lipopeptides/analysis/box_area/pope_popg} [2.0.0 120406]\n"
"# Num_Blocks BlockLen StdErr\n"
"20 111 0.190357\n"
"19 117 0.194111\n"
"18 123 0.193382\n"
"17 131 0.19941\n"
"(more lines like this)\n"
"3 743 0.239527\n"
"2 1114 0.354243\n"
"\n"
"The first column is the number of blocks the data is broken into, the \n"
"second is the number of time points in each block, and the last column \n"
"is the standard error of the averages for each block. As a rule, you'll\n"
"want to plot this data using column 2 as the x-axis, and column 3 as the \n"
"y-axis.\n"
"\n"
;
return(s);
}
void Usage()
{
cerr << "Usage: block_average TimeSeriesFile column max_blocks skip"
<< endl;
cerr << endl;
cerr << "TimeSeriesFile is a columnated text file. Blank lines and "
<< "lines starting with \"#\" are ignored"
<< endl;
}
int main(int argc, char*argv[])
{
if ( (argc >=2) && (strncmp(argv[1], "--fullhelp", 10) == 0) )
{
cout << fullHelpMessage() << endl;
exit(-1);
}
if ( (argc <= 1) ||
( (argc >= 2) && (strncmp(argv[1], "-h", 2) == 0) ) ||
(argc < 5)
)
{
Usage();
exit(-1);
}
// Print the command line arguments
cout << "# " << invocationHeader(argc, argv) << endl;
char *datafile = argv[1];
int column = atoi(argv[2]);
unsigned int max_blocks = atoi(argv[3]);
unsigned int skip = atoi(argv[4]);
// Read the TimeSeries file
TimeSeries<float> data = TimeSeries<float>(datafile, column);
unsigned int num_points = data.size();
// validate the arguments
if (skip > num_points)
{
cerr << "You set skip ( " << skip << " ) greater than the number "
<< "of points in the trajectory ( " << num_points << " )."
<< endl
<< "This doesn't work."
<< endl;
exit(-1);
}
// Remove the equilibration time
data.set_skip(skip);
num_points -= skip;
if (max_blocks > num_points)
{
cerr << "You set max_blocks ( " << max_blocks << " ) greater than "
<< "the number of points in the trajectory minus the number skipped "
<< "( " << num_points << " )."
<< endl
<< "This doesn't work."
<< endl;
exit(-1);
}
// Loop over the number of blocks, computing the variance of the averages for
// each number of blocks
cout << "# Num_Blocks\tBlockLen\tStdErr" << endl;
for (int i=max_blocks; i>=2; i--)
{
int time = num_points / i;
float variance = data.block_var(i);
float std_err = sqrt(variance/i);
cout << i << "\t\t"
<< time << "\t\t"
<< std_err
<< endl;
}
}
| 8,500
|
C++
|
.cpp
| 209
| 37.856459
| 162
| 0.682049
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,162
|
fidpick.cpp
|
GrossfieldLab_loos/Packages/Convergence/fidpick.cpp
|
/*
Picks fiducial structures for a structural histogram, a la Lyman &
Zuckerman, Biophys J (2006) 91:164-172
Usage- fidpick model trajectory selection output-name cutoff [seed]
Note: This is the older method of partitioning based on a distance
cutoff only, rather than only taking the closest N structures (used
in the decorr-time and Neff methods
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
typedef vector<AtomicGroup> vGroup;
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tPick fiducial structures for a structural histogram using a distance cutoff\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool implements the older method of constructing a structural histogram\n"
"where bins are defined in terms of the closest N structures to a randomly picked\n"
"fiducial. See Lyman and Zuckerman, Biophys J (2006) 91:164-72 for more information.\n"
"\n"
"EXAMPLES\n"
"\n"
"\tfidpick model.pdb simulation.dcd all 'name == \"CA\" fiducials 5.0 >>fiducials.asc\n"
"This example uses all alpha-carbons, assigns bins based on a distance cutoff of 5.0 angstroms\n"
"and writes the fiducials to fiducials.pdb and fiducials.dcd. A log of the selections\n"
"is stored in fiducials.asc\n"
"\n"
"SEE ALSO\n"
"\tsortfids\n";
return(msg);
}
vector<uint> findFreeFrames(const vector<int>& map) {
vector<uint> indices;
for (uint i=0; i<map.size(); ++i)
if (map[i] < 0)
indices.push_back(i);
return(indices);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
if (argc < 7 || argc > 8) {
cerr << "Usage - fidpick model trajectory range|all selection output-name cutoff [seed]\n";
exit(-1);
}
int opti = 1;
AtomicGroup model = createSystem(argv[opti++]);
model.clearBonds();
pTraj traj = createTrajectory(argv[opti++], model);
string range(argv[opti++]);
string selection(argv[opti++]);
AtomicGroup subset = selectAtoms(model, selection);
string outname(argv[opti++]);
double cutoff = strtod(argv[opti++], 0);
long seed;
if (opti < argc) {
seed = strtol(argv[opti++], 0, 10);
rng_singleton().seed(static_cast<unsigned int>(seed)); // This addresses a bug in earlier BOOSTs
} else
randomSeedRNG();
vector<uint> frames;
if (range == "all")
for (uint i=0; i<traj->nframes(); ++i)
frames.push_back(i);
else
frames = parseRangeList<uint>(range);
boost::uniform_real<> rmap;
boost::variate_generator< base_generator_type&, boost::uniform_real<> > rng(rng_singleton(), rmap);
vGroup fiducials;
vector<int> assignments(frames.size(), -1);
cout << "Frames picked:\n";
vector<uint> possible_frames = findFreeFrames(assignments);
while (! possible_frames.empty()) {
uint pick = possible_frames[static_cast<uint>(floor(possible_frames.size() * rng()))];
traj->readFrame(frames[pick]);
traj->updateGroupCoords(model);
AtomicGroup fiducial = subset.copy();
fiducial.centerAtOrigin();
uint myid = fiducials.size();
if (assignments[pick] >= 0) {
cerr << "INTERNAL ERROR - " << pick << " pick was already assigned to " << assignments[pick] << endl;
exit(-99);
}
fiducials.push_back(fiducial);
assignments[pick] = myid;
uint cluster_size = 0;
for (uint i = 0; i<assignments.size(); ++i) {
if (assignments[i] >= 0 || i == pick)
continue;
traj->readFrame(frames[i]);
traj->updateGroupCoords(model);
subset.centerAtOrigin();
subset.alignOnto(fiducial);
double d = subset.rmsd(fiducial);
if (d < cutoff) {
assignments[i] = myid;
++cluster_size;
}
}
cout << "\t" << frames[pick] << "\t" << cluster_size << endl;
possible_frames = findFreeFrames(assignments);
}
cerr << "Done!\nWrote " << fiducials.size() << " fiducials to " << outname << endl;
DCDWriter dcd(outname + ".dcd", fiducials, hdr);
PDB pdb = PDB::fromAtomicGroup(fiducials[0]);
pdb.remarks().add(hdr);
string fname = outname + ".pdb";
ofstream ofs(fname.c_str());
ofs << pdb;
}
| 4,992
|
C++
|
.cpp
| 129
| 34.325581
| 107
| 0.687188
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,163
|
decorr_time.cpp
|
GrossfieldLab_loos/Packages/Convergence/decorr_time.cpp
|
/*
Structural Histogram IID analysis a la Lyman & Zuckerman J Phys Chem
B (2007) 111:12876-12882
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include "ConvergenceOptions.hpp"
#include "fid-lib.hpp"
using namespace std;
using namespace loos;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// * GLOBALS *
// Turning on generates some internal debugging information
const bool debugging = false;
uint verbosity;
uint nreps = 5;
double frac;
vecUint trange;
vecUint nrange;
vecUint indices;
// @cond TOOLS_INTERNAL
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tCompute decorrelation times for a simulation\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool implements the decorrelation time method described in Lyman and Zuckerman,\n"
"J Phys Chem B (2007) 111:12876-12882. Bins for the structural histogram used are selected\n"
"using a uniform probability, set with the --frac option (the default is 0.05 for 20 bins).\n"
"The range of sample sizes (n, in figure 2) is given by the --nrange option, which takes\n"
"either a comma-separated list of sizes or a matlab/octave-style range. Finally, the\n"
"required t-range is also a matlab/octave-style range (or comma-separated list) that\n"
"gives the sample step-size (t in figure 2). This is not to be confused with a range in\n"
"frames of the trajectory. However, the notion of \"time\" is dictated by the sampling\n"
"rate of your trajectory, and is specified in terms of frames. For example, if your\n"
"trajectory has 1 frame/ns, then the t-range is specified in ns. If your trajectory\n"
"has one frame every 100 ps, then the t-range is specified in 100 ps units (i.e. frames).\n"
"This whole procedure is repeated multiple times for each sample size, n. The number of\n"
"repeats is given by the --reps option (default of 5).\n"
"\tThe output is an ASCII matrix where the first column is the step-size t. Each subsequent\n"
"set of two-columns corresponds to a different sample size or n-value. The first column\n"
"in each set is the scaled variance (eq 3), averaged over each replica. The second column\n"
"is the standard error in the scaled variance. This data can be plotted, e.g. figure 3.\n"
"\n"
"EXAMPLES\n"
"\n"
"\tdecorr_time --selection '!hydrogen' model.pdb simulation.dcd 5:5:100 >decorr.asc\n"
"A decorrelation time calculation using the default sample sizes of 2, 4, and 10 and\n"
"the default bin-size of 20 (probability 0.05). The calculation is repeated the default\n"
"of 5 times for each sample-size. Only non-hydrogen atoms are used. And the range in t\n"
"is 5 to 100 at every 5 frames (assuming a 1 frame/ns trajectory, then 5 to 100 ns every 5 ns).\n"
"\n"
"\tdecorr_time --selection 'name == \"CA\"' --nrange 2,3,4 --frac 0.1 \\\n"
"\t model.pdb simulation.dcd 10:10:250 >decorr.asc\n"
"Here, only alpha-carbons are used. Sample sizes are 2, 3, and 4 and there are 10 bins. The\n"
"t-range here is 10 to 250 at every 10 frames.\n"
"\n"
"NOTES\n"
"\tSimulations that are not well-converge may have difficulty with the default sample-size\n"
"range. Try a smaller range (i.e. 2,3,4) as well as large bins.\n"
"SEE ALSO\n"
"\tufidpick, effsize.pl, neff, assign_frames, hierarchy\n";
return(msg);
}
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("nrange", po::value<string>(&nrange_spec)->default_value("2,4,10"), "Range of N to use")
("frac", po::value<double>(&frac)->default_value(0.05), "Bin fraction")
("reps", po::value<uint>(&nreps)->default_value(5), "# of repetitions to use for each N");
}
bool postConditions(po::variables_map& vm) {
nrange = parseRangeList<uint>(nrange_spec);
return(true);
}
string print() const {
ostringstream oss;
oss << boost::format("nrange='%s', frac=%f, reps=%f")
% nrange_spec
% frac
% nreps;
return(oss.str());
}
string nrange_spec;
};
// @endcond
// Despite the name, this histograms the assignments (i.e. frequency
// of the various fiducials in the trajectory)
vecDouble rebinFrames(const vecUint& assignments, const uint S, const vecUint& ensemble) {
vecUint hist(S, 0);
for (vecUint::const_iterator i = ensemble.begin(); i != ensemble.end(); ++i) {
if (assignments[*i] >= S)
throw(runtime_error("Bin index exceeds number of fiducials in rebinFrames()"));
++hist[assignments[*i]];
}
vecDouble pops(S);
for (uint i=0; i<S; ++i)
pops[i] = static_cast<double>(hist[i])/ensemble.size();
return(pops);
}
vecDouble binVariances(const vecUint& assignments, const uint S, const uint n, const uint t) {
vector<vecDouble> fik;
uint curframe = 0;
if (debugging)
cerr << boost::format("Debug> S=%d, n=%d, t=%d\n") % S % n % t;
while (curframe < assignments.size()) {
vecUint ensemble;
for (uint i=0; i<n && curframe < assignments.size(); ++i, curframe += t)
ensemble.push_back(curframe);
// Incomplete sample, so ignore...
if (ensemble.size() < n)
break;
vecDouble hist = rebinFrames(assignments, S, ensemble);
fik.push_back(hist);
}
if (debugging) {
cerr << "Debug> populations=\n";
for (uint i=0;i<fik.size(); ++i) {
cerr << "\t" << i << " : ";
copy(fik[i].begin(), fik[i].end(), ostream_iterator<double>(cerr, ","));
cerr << "\n";
}
cerr << endl;
}
vecDouble means(S, 0.0);
for (vector<vecDouble>::iterator j = fik.begin(); j != fik.end(); ++j)
for (uint i=0; i<S; ++i)
means[i] += (*j)[i];
for (uint i=0; i<S; ++i)
means[i] /= fik.size();
if (debugging) {
cerr << "Debug> means=";
copy(means.begin(), means.end(), ostream_iterator<double>(cerr, ","));
cerr << endl;
}
vecDouble vars(S, 0.0);
for (vector<vecDouble>::iterator j = fik.begin(); j != fik.end(); ++j)
for (uint i=0; i<S; ++i) {
double d = (*j)[i] - means[i];
vars[i] += d*d;
}
for (vecDouble::iterator i = vars.begin(); i != vars.end(); ++i)
*i /= fik.size();
if (debugging) {
cerr << boost::format("Debug> chunks = %d\n") % fik.size();
cerr << "Debug> vars=";
copy(vars.begin(), vars.end(), ostream_iterator<double>(cerr, ","));
cerr << endl;
}
return(vars);
}
double avgVariance(const vecDouble& vars) {
double mean = 0.0;
for (vecDouble::const_iterator i = vars.begin(); i != vars.end(); ++i)
mean += *i;
mean /= vars.size();
return(mean);
}
double sigma(const vecUint& assignments, const uint S, const uint n, const uint t) {
vecDouble vars = binVariances(assignments, S, n, t);
double mean_vars = avgVariance(vars);
double f = 1.0 / S;
double N = static_cast<double>(assignments.size()) / t;
double expected = (f*(1.0-f) / n) * (N-n)/(N-1.0);
double val = mean_vars / expected;
if (debugging)
cerr << boost::format("Debug> f=%f, N=%f, expected=%f, val=%f\n\n") % f % N % expected % val;
return(val);
}
DoubleMatrix statistics(const vector<DoubleMatrix>& V) {
uint m = V[0].rows();
uint n = V[0].cols();
DoubleMatrix M(m, n);
for (uint k=0; k<V.size(); ++k)
for (ulong i=0; i<m*n; ++i)
M[i] += V[k][i];
for (long i=0; i<m*n; ++i)
M[i] /= V.size();
DoubleMatrix S(m, n);
if (V.size() > 2) {
for (uint k=0; k<V.size(); ++k)
for (ulong i=0; i<m*n; ++i) {
double d = V[k][i] - M[i];
S[i] = d*d;
}
for (ulong i=0; i<m*n; ++i)
S[i] = sqrt(S[i] / (V.size() - 1));
}
uint nn = (n-1) * 2 + 1;
DoubleMatrix R(m, nn);
for (uint j=0; j<m; ++j)
for (uint i=0; i<n; ++i)
if (i == 0)
R(j, i) = M(j, i);
else {
R(j, 2*(i-1)+1) = M(j, i);
R(j, 2*(i-1)+2) = S(j, i);
}
return(R);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions *bopts = new opts::BasicOptions(fullHelpMessage());
opts::BasicSelection *sopts = new opts::BasicSelection;
opts::TrajectoryWithFrameIndices *tropts = new opts::TrajectoryWithFrameIndices;
opts::BasicConvergence *copts = new opts::BasicConvergence;
ToolOptions* topts = new ToolOptions;
opts::RequiredArguments* ropts = new opts::RequiredArguments("trange", "T-range");
opts::AggregateOptions options;
options.add(bopts).add(sopts).add(tropts).add(copts).add(topts).add(ropts);
if (!options.parse(argc, argv))
exit(-1);
verbosity = bopts->verbosity;
cout << "# " << hdr << endl;
cout << "# " << vectorAsStringWithCommas<string>(options.print()) << endl;
AtomicGroup model = tropts->model;
pTraj traj = tropts->trajectory;
AtomicGroup subset = selectAtoms(model, sopts->selection);
string trange_spec = ropts->value("trange");
trange = parseRangeList<uint>(trange_spec);
indices = assignTrajectoryFrames(traj, tropts->frame_index_spec, tropts->skip);
vector<DoubleMatrix> results;
for (uint k = 0; k<nreps; ++k) {
if (verbosity > 0)
cerr << "Replica #" << k << endl;
boost::tuple<vecGroup, vecUint> fids = pickFiducials(subset, traj, indices, frac);
vecGroup fiducials = boost::get<0>(fids);
vecUint assignments = assignStructures(subset, traj, indices, fiducials);
uint S = fiducials.size();
DoubleMatrix M(trange.size(), nrange.size() + 1);
for (uint i=0; i<nrange.size(); ++i)
for (uint j=0; j<trange.size(); ++j)
M(j, i+1) = sigma(assignments, S, nrange[i], trange[j]);
for (uint j=0; j<trange.size(); ++j)
M(j, 0) = trange[j];
results.push_back(M);
}
DoubleMatrix M = statistics(results);
writeAsciiMatrix(cout, M, "");
}
| 10,658
|
C++
|
.cpp
| 260
| 36.596154
| 102
| 0.655924
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,164
|
coscon.cpp
|
GrossfieldLab_loos/Packages/Convergence/coscon.cpp
|
/*
Cosine content for varying windows of a trajectory,
based on:
Hess, B. "Convergence of sampling in protein simulations."
Phys Rev E (2002) 65(3):031910
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2011, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include "bcomlib.hpp"
using namespace std;
using namespace loos;
using namespace Convergence;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// @cond TOOLS_INTERNAL
typedef vector<AtomicGroup> vGroup;
// Convenience structure for aggregating results
struct Datum {
Datum(const double avg, const double var, const uint nblks) : avg_cosine(avg),
var_cosine(var),
nblocks(nblks) { }
double avg_cosine;
double var_cosine;
uint nblocks;
};
string fullHelpMessage() {
string s =
"\n"
"SYNOPSIS\n"
"\n"
"Calculate the cosine constent of a simulation\n"
"\n"
"DESCRIPTION\n"
"\n"
"\n"
"Calculate the cosine content in the PCA of a simulation.\n"
"This is done in a block averaged manner. Smaller contiguous\n"
"blocks of the trajectory are used for the calcualation. This\n"
"tool assesses convergence of a trajectory by calulating how\n"
"\"cosine-like\" the principal components appear. The technique\n"
"was described by Hess who noted that random diffusion showed a \n"
"close resemblance to a cosine in:\n"
"\n"
"Hess, B. \"Convergence of sampling in protein \n"
" simulations.\" Phys Rev E (2002) 65(3):031910\n"
"\n"
"As the blocks increase in size more of the trajectory is used\n"
"in this calulation. The output is formatted in 4 columns:\n"
"\n"
"\t n - current block size (nanoseconds)\n"
"\tCos cont - avg cosine content in a block\n"
"\tVariance - variance across all (N_blocks)\n"
"\tN_blocks - number of blocks of a given length\n"
"\n"
"\n"
//
"EXAMPLES\n"
"\n"
"coscon -s 'name==\"CA\"' model.pdb traj.dcd\n"
"\tCalculate the block averaged cosine content in the\n"
"\ttrajectory using only CA's in the calculation.\n"
"\n"
"coscon --pc=1 -s 'name==\"CA\"' model.pdb traj.dcd\n"
"\tSame as above, but only compute the cosine content\n"
"\tof the first principal component.\n"
"\n"
"coscon --block 100:100:500 -s 'name==\"CA\"' model.pdb traj.dcd\n"
"\tHere we specify the range over which the calculation\n"
"\tis performed. The smallest block size used is 100 frames.\n"
"\tThe block size will then increase by 100 frames upto a max\n"
"\tblock size of 500 frames (ie...100,200,300,400,500).\n"
"\n"
"\n"
"SEE ALSO\n"
"\n"
"Packages/Convergence/qcoscon - \n"
"\tPerform a quick cos content analysis on a simulation.\n"
"\tSimilar to coscon, but only performs the analysis on\n"
"\tthe full length simulation.\n"
"\n"
"Packages/Convergence/rsv-coscon - \n"
"\tCalculate the cos content of the RSVs from a simulation\n"
"\tPCA.\n"
"\t\n"
"\n"
"Tools/svd - \n"
"\tCompute the principal components via the SVD.\n"
"\tThis results in several matrix files including\n"
"\tthe RSVs used as input to the current tool. \n"
"\tThe file [prefix]_V.asc contains the RSV matrix.\n"
"\n"
"\n";
return(s);
}
// @endcond
// Configuration
const uint nsteps = 50;
// Global options
bool local_average;
vector<uint> blocksizes;
string model_name, traj_name, selection;
uint principal_component;
// @cond TOOLS_INTERAL
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("pc", po::value<uint>(&principal_component)->default_value(0), "Which principal component to use")
("blocks", po::value<string>(&blocks_spec), "Block sizes (MATLAB style range)")
("local", po::value<bool>(&local_average)->default_value(true), "Use local avg in block PCA rather than global");
}
bool postConditions(po::variables_map& vm) {
if (!blocks_spec.empty())
blocksizes = parseRangeList<uint>(blocks_spec);
for (vector<uint>::iterator i = blocksizes.begin(); i != blocksizes.end(); ++i)
if (*i == 0) {
cerr << "Error- a block-size must be > 0\n";
return(false);
}
return(true);
}
string print() const {
ostringstream oss;
oss << boost::format("blocks='%s', local=%d, pc=%d")
% blocks_spec
% local_average
% principal_component;
return(oss.str());
}
string blocks_spec;
};
// @endcond
vGroup subgroup(const vGroup& A, const uint a, const uint b) {
vGroup B;
for (uint i=a; i<b; ++i)
B.push_back(A[i]);
return(B);
}
// Breaks the ensemble up into blocks and computes the RSV for each
// block and the statistics for the cosine content...
template<class ExtractPolicy>
Datum blocker(const uint pc, vGroup& ensemble, const uint blocksize, ExtractPolicy& policy) {
TimeSeries<double> cosines;
for (uint i=0; i<ensemble.size() - blocksize; i += blocksize) {
vGroup subset = subgroup(ensemble, i, i+blocksize);
RealMatrix V = rsv(subset, policy);
double val = cosineContent(V, pc);
cosines.push_back(val);
}
return( Datum(cosines.average(), cosines.variance(), cosines.size()) );
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::BasicSelection* sopts = new opts::BasicSelection;
opts::BasicTrajectory* tropts = new opts::BasicTrajectory;
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(sopts).add(tropts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
cout << "# " << hdr << endl;
cout << "# " << vectorAsStringWithCommas<string>(options.print()) << endl;
AtomicGroup model = tropts->model;
pTraj traj = tropts->trajectory;
if (blocksizes.empty()) {
uint n = traj->nframes();
uint step = n / nsteps;
if (step < 1)
step = 1;
cout << "# Auto block-sizes - " << step << ":" << step << ":" << n-1 << endl;
for (uint i = step; i < n; i += step)
blocksizes.push_back(i);
}
AtomicGroup subset = selectAtoms(model, sopts->selection);
vector<AtomicGroup> ensemble;
readTrajectory(ensemble, subset, traj);
// First, read in and align trajectory
boost::tuple<std::vector<XForm>, greal, int> ares = iterativeAlignment(ensemble);
AtomicGroup avg = averageStructure(ensemble);
NoAlignPolicy policy(avg, local_average);
// Now iterate over all requested block sizes
// Provide user-feedback since this can be a slow computation
PercentProgress watcher;
ProgressCounter<PercentTrigger, EstimatingCounter> slayer(PercentTrigger(0.1), EstimatingCounter(blocksizes.size()));
slayer.attach(&watcher);
slayer.start();
for (vector<uint>::iterator i = blocksizes.begin(); i != blocksizes.end(); ++i) {
Datum result = blocker(principal_component, ensemble, *i, policy);
cout << *i << "\t" << result.avg_cosine << "\t" << result.var_cosine << "\t" << result.nblocks << endl;
slayer.update();
}
slayer.finish();
}
| 8,126
|
C++
|
.cpp
| 209
| 34.086124
| 119
| 0.673571
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,165
|
block_avgconv.cpp
|
GrossfieldLab_loos/Packages/Convergence/block_avgconv.cpp
|
/*
block_avgconv.cpp
Convergence of average via block averaging
Usage- block_avgconv model traj selection range
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
using namespace loos;
using namespace std;
const uint default_starting_number_of_blocks = 500;
const double default_fraction_of_trajectory = 0.25;
AtomicGroup averageSelectedSubset(const vector<AtomicGroup>& ensemble, const vector<uint>& indices) {
AtomicGroup avg = ensemble[0].copy();
for (AtomicGroup::iterator i = avg.begin(); i != avg.end(); ++i)
(*i)->coords() = GCoord(0,0,0);
uint n = avg.size();
for (vector<uint>::const_iterator j = indices.begin(); j != indices.end(); ++j)
for (uint i=0; i<n; ++i)
avg[i]->coords() += ensemble[*j][i]->coords();
for (AtomicGroup::iterator i = avg.begin(); i != avg.end(); ++i)
(*i)->coords() /= indices.size();
return(avg);
}
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tBlock-average approach to average structure convergence\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThe trajectory is divided into n-blocks. The average structure for each\n"
"block is computed. The RMSD between all pairs of blocks is calculated and the\n"
"average, variance, and standard error are written out. The block size is then\n"
"increased and the process repeated.\n"
"\tThe trajectory is first optimally aligned using an iterative method described in\n"
"in Grossfield, et al. Proteins 67, 31–40 (2007) unless the 'do not align' flag is given.\n"
"\n"
"EXAMPLES\n"
"\n"
"\tblock_avgconv sim.psf traj.dcd '!hydrogen' >blocks.asc\n"
"This example uses all non-hydrogen atoms with automatically determined block sizes.\n"
"The trajectory is optimally aligned.\n"
"\n"
"\tblock_avgconv sim.psf traj.dcd 'name == \"CA\" 10:10:1000 >blocks.asc\n"
"This example uses all alpha-carbons and block sizes 10, 20, 30, ..., 1000.\n"
"\n"
"\tblock_avgconv sim.psf traj.dcd 'segid == \"PE1\"' 25:25:500 1 >blocks.asc\n"
"This example does NOT optimally align the trajectory first. All atoms from segment\n"
"'PE1' are used. Block sizes are 25, 50, 75, ..., 500\n"
"\n"
"SEE ALSO\n"
"\tavgconv, block_average\n";
return(msg);
}
int main(int argc, char *argv[]) {
if (argc < 4 || argc > 6) {
cerr << "Usage- block_avgconv model traj sel [range [1 = do not align trajectory]]\n";
cerr << fullHelpMessage();
exit(-1);
}
string hdr = invocationHeader(argc, argv);
int k = 1;
AtomicGroup model = createSystem(argv[k++]);
pTraj traj = createTrajectory(argv[k++], model);
AtomicGroup subset = selectAtoms(model, argv[k++]);
vector<uint> sizes;
bool do_align = true;
if (argc == k) {
uint step = traj->nframes() / default_starting_number_of_blocks;
for (uint i=step; i<traj->nframes() * default_fraction_of_trajectory; i += step)
sizes.push_back(i);
} else {
sizes = parseRangeList<uint>(argv[k++]);
if (argc == k+1)
do_align = (argv[k][0] != '1');
}
cout << "# " << hdr << endl;
cout << "# n\tavg\tvar\tblocks\tstderr\n";
vector<AtomicGroup> ensemble;
cerr << "Reading trajectory...\n";
readTrajectory(ensemble, subset, traj);
if (do_align) {
cerr << "Aligning trajectory...\n";
boost::tuple<vector<XForm>, greal, int> result = iterativeAlignment(ensemble);
} else
cerr << "Trajectory is already aligned!\n";
cerr << "Processing- ";
for (uint block = 0; block < sizes.size(); ++block) {
if (block % 50)
cerr << ".";
uint blocksize = sizes[block];
vector<AtomicGroup> averages;
for (uint i=0; i<ensemble.size() - blocksize; i += blocksize) {
vector<uint> indices(blocksize);
for (uint j=0; j<blocksize; ++j)
indices[j] = i+j;
averages.push_back(averageSelectedSubset(ensemble, indices));
}
TimeSeries<double> rmsds;
for (uint j=0; j<averages.size() - 1; ++j)
for (uint i=j+1; i<averages.size(); ++i) {
AtomicGroup left = averages[j];
AtomicGroup right = averages[i];
left.alignOnto(right);
rmsds.push_back(left.rmsd(right));
}
double v = rmsds.variance();
uint n = averages.size();
cout << boost::format("%d\t%f\t%f\t%d\t%f\n") % blocksize % rmsds.average() % v % n % sqrt(v/n);
}
cerr << "\nDone!\n";
}
| 5,248
|
C++
|
.cpp
| 129
| 36.03876
| 101
| 0.667129
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
755,166
|
neff.cpp
|
GrossfieldLab_loos/Packages/Convergence/neff.cpp
|
/*
neff
Based on Zhang, Bhatt, and Zuckerman; JCTC, DOI: 10.1021/ct1002384
and code provided by the Zuckerman Lab
(http://www.ccbb.pitt.edu/Faculty/zuckerman/software.html)
Computes effective sample size given an assignment file and a state file
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <limits>
using namespace loos;
using namespace std;
typedef vector<uint> vUint;
typedef vector<vUint> vvUint;
const double stddev_tol = 1e-6;
vvUint readStates(const string& fname) {
ifstream ifs(fname.c_str());
if (ifs.fail()) {
cerr << "Error- cannot open " << fname << endl;
exit(-1);
}
vvUint states;
int n;
string dummy;
getline(ifs, dummy);
ifs >> n;
if (n <= 0) {
cerr << boost::format("Error- bad number of states (%d).\n") % n;
exit(-10);
}
while (n-- > 0) {
int m;
ifs >> m;
if (m <= 0) {
cerr << boost::format("Error- bad number of bins (%d).\n") % m;
exit(-10);
}
vUint list;
while (m-- > 0) {
uint s;
ifs >> s;
list.push_back(s);
}
states.push_back(list);
}
return(states);
}
vector<uint> readAssignments(const string& fname) {
ifstream ifs(fname.c_str());
if (ifs.fail()) {
cerr << "Error- cannot open " << fname << endl;
exit(-1);
}
return(readVector<uint>(ifs));
}
vUint mapStates(const vvUint& states) {
uint maxbin = 0;
for (vvUint::const_iterator j = states.begin(); j != states.end(); ++j)
for (vUint::const_iterator i = j->begin(); i != j->end(); ++i)
if (*i > maxbin)
maxbin = *i;
vUint binmap(maxbin, 0);
for (uint j=0; j<states.size(); ++j)
for (vUint::const_iterator i = states[j].begin(); i != states[j].end(); ++i)
binmap[*i] = j;
return(binmap);
}
vector<double> rowAvg(const DoubleMatrix& M) {
vector<double> avg(M.rows(), 0.0);
for (uint j=0; j<M.rows(); ++j) {
for (uint i=0; i<M.cols(); ++i)
avg[j] += M(j, i);
avg[j] /= M.cols();
}
return(avg);
}
vector<double> rowStd(const DoubleMatrix& M, const vector<double>& means) {
vector<double> dev(M.rows(), 0.0);
for (uint j=0; j<M.rows(); ++j) {
for (uint i=0; i<M.cols(); ++i) {
double d = M(j, i) - means[j];
dev[j] += d*d;
}
dev[j] = sqrt(dev[j] / (M.cols() - 1));
}
return(dev);
}
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tDetermine the effective sample size of a simulation\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool determines the effective sample size (Neff) as described in\n"
"Zhang, Batt, and Zuckerman, JCTC (2010) 6:3048-57.\n"
"\n"
"EXAMPLES\n"
"\n"
"\tneff assignments.asc zuckerman.states 0.1\n"
"This example determines the Neff given the structural histogram assigments\n"
"in assignments.asc, the clustering in zuckerman.states, and a bin-probability of 0.1\n"
"\n"
"NOTES\n"
"\n"
"\tThe partition_size should match the bin-probability used in\n"
"generating the structural histogram (i.e. ufidpick)\n"
"\n"
"SEE ALSO\n"
"\tufidpick, assign_frames, hierarchy, effsize.pl\n";
return(msg);
}
int main(int argc, char *argv[]) {
if (argc != 4) {
cerr << "Usage- " << argv[0] << " assignments states partition_size\n";
cerr << fullHelpMessage();
exit(-1);
}
string hdr = invocationHeader(argc, argv);
int k = 1;
vector<uint> assignments = readAssignments(argv[k++]);
vvUint states = readStates(argv[k++]);
uint N = states.size();
uint partition_size = atoi(argv[k++]);
uint nparts = floor(assignments.size() / partition_size);
DoubleMatrix M(N, nparts);
vUint binmap = mapStates(states);
for (uint i=0; i<nparts; ++i) {
for (uint k=0; k<partition_size; ++k) {
uint col = i*partition_size + k;
uint bin = binmap[assignments[col]];
if (bin > N) {
cerr << "Error- internal error, bin=" << bin << ", N=" << N << endl;
exit(-20);
}
M(bin, i) += 1;
}
for (uint j=0; j<N; ++j)
M(j, i) /= partition_size;
}
vector<double> means = rowAvg(M);
vector<double> devs = rowStd(M, means);
double min_neff = numeric_limits<double>::max();
for (uint j=0; j<N; ++j) {
double neff = (1.0 - means[j]) * means[j] / (devs[j] * devs[j]);
cout << boost::format("Estimated effective sample size from state %d = %f\n") % j % neff;
if (neff < min_neff)
min_neff = neff;
}
double total = min_neff * nparts;
cout << boost::format("Segment effective sample size = %f\n") % min_neff;
cout << boost::format("Trajectory effective sample size = %f\n") % total;
}
| 5,518
|
C++
|
.cpp
| 170
| 28.188235
| 93
| 0.63111
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,167
|
avgconv.cpp
|
GrossfieldLab_loos/Packages/Convergence/avgconv.cpp
|
/*
avgconv
Usage- avgconv model traj selection range
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2011, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
using namespace std;
using namespace loos;
bool locally_optimal = false;
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tConvergence of the average structure\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThe convergence of the average structure from a trajectory is determined by first\n"
"dividing the trajectory into blocks. An average structure is computed for the i'th and\n"
"the i+1'th block. These two average structure are superimposed using a Kabsch alignment\n"
"algorithm. The RMSD is calculated. This is then repeated for all blocks.\n"
"\tInitially, the whole trajectory is optimally aligned first using an iterative alignment\n"
"process (described in Grossfield, et al. Proteins 67, 31–40 (2007)). Optionally,\n"
"each block may be optimally aligned independently by using the 'locally optimal' flag.\n"
"\n"
"EXAMPLES\n"
"\n"
"\tavgconv sim.psf traj.dcd 'segid == \"PE1\"' >avgconv.asc\n"
"This example uses automatic block-sizes for the subsamples and calculates the RMSD and\n"
"superpositions using all atoms from the PE1 segment. The output is placed in avgconv.asc\n"
"\n"
"\tavgconv sim.psf traj.dcd 'name == \"CA\"' 10:10:500 >avgconv.asc\n"
"This example uses all alpha-carbons and explicitly sets the block sizes to 10,\n"
"20, ..., 100\n"
"\n"
"\tavgconv sim.psf traj.dcd '!hydrogen' 10:10:500 1 >avgconv.asc\n"
"This example uses all non-hydrogen atoms with block sizes of 10, 20, 30, ..., 5000,\n"
"and the blocks are all iteratively aligned prior to computing the average.\n"
"SEE ALSO\n"
"\tblock_average, block_avgconv\n";
return(msg);
}
AtomicGroup calcAverage(const vector<AtomicGroup>& ensemble, const uint size) {
vector<AtomicGroup> subsample(size);
for (uint i=0; i<size; ++i)
subsample[i] = ensemble[i];
if (locally_optimal)
(void)iterativeAlignment(subsample);
AtomicGroup avg = averageStructure(subsample);
return(avg);
}
int main(int argc, char *argv[]) {
if (argc < 4 || argc > 6) {
cerr << "Usage- avgconv model traj selection [range [1 = local optimal avg]]\n";
cerr << fullHelpMessage();
exit(-1);
}
string hdr = invocationHeader(argc, argv);
cout << "# " << hdr << endl;
cout << "# n\trmsd\n";
int k = 1;
AtomicGroup model = createSystem(argv[k++]);
pTraj traj = createTrajectory(argv[k++], model);
string sel = string(argv[k++]);
vector<uint> blocks;
if (argc == 4) {
uint step = traj->nframes() / 100;
if (step == 0) {
cerr << "Error- too few frames for auto-blocksizes. Please specify block sizes explicitly\n";
exit(-1);
}
for (uint i=step; i<traj->nframes(); i += step)
blocks.push_back(i);
} else {
blocks = parseRangeList<uint>(argv[k++]);
if (argc == k+1)
locally_optimal = (argv[k][0] == '1');
}
AtomicGroup subset = selectAtoms(model, sel);
cout << boost::format("# Subset has %d atoms\n") % subset.size();
vector<AtomicGroup> ensemble;
readTrajectory(ensemble, subset, traj);
cout << boost::format("# Trajectory has %d frames\n") % ensemble.size();
cout << boost::format("# Blocks = %d\n") % blocks.size();
if (!locally_optimal) {
boost::tuple<vector<XForm>, greal, int> result = iterativeAlignment(ensemble);
cout << boost::format("# Iterative alignment converged to RMSD of %g with %d iterations\n") % boost::get<1>(result) % boost::get<2>(result);
}
AtomicGroup preceding = calcAverage(ensemble, blocks[0]);
for (vector<uint>::const_iterator ci = blocks.begin()+1; ci != blocks.end(); ++ci) {
AtomicGroup avg = calcAverage(ensemble, *ci);
avg.alignOnto(preceding);
double rmsd = preceding.rmsd(avg);
cout << boost::format("%d\t%f\n") % *ci % rmsd;
preceding = avg;
}
}
| 4,790
|
C++
|
.cpp
| 113
| 38.265487
| 144
| 0.691793
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
755,168
|
qcoscon.cpp
|
GrossfieldLab_loos/Packages/Convergence/qcoscon.cpp
|
/*
"Quick" Cosine content. Calculates the cosine content for the
entire trajectory for the first N modes.
based on:
Hess, B. "Convergence of sampling in protein simulations."
Phys Rev E (2002) 65(3):031910
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2011, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include "bcomlib.hpp"
using namespace std;
using namespace loos;
using namespace Convergence;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
typedef vector<AtomicGroup> vGroup;
uint nmodes;
string fullHelpMessage() {
string s =
"\n"
"SYNOPSIS\n"
"\n"
"Calculate the cosine constent of a whole simulation\n"
"\n"
"DESCRIPTION\n"
"\n"
"Quick version of the cosine content calculation.\n"
"This tool performs the same calculation as coscon, \n"
"but instead of varying the trajectory in a block\n"
"averaging approach only the full trajectory is used.\n"
"The results are printed for the first 10 modes.\n"
"\n"
//
"EXAMPLES\n"
"\n"
"qcoscon -s 'name==\"CA\"' model.pdb traj.dcd\n"
"\tCalculate the cos content of the first 10 modes\n"
"\tof traj.dcd using the PCA of the CA atoms.\n"
"\n"
"SEE ALSO\n"
"Packages/Convergence/coscon - \n"
"\tCompute the cosine content of a matrix. This tool\n"
"\tperforms a similar analysis, but it uses a block\n"
"\taveraging approach where the cosine content is\n"
"\tcalculated for increasingly long trajectory blocks\n"
"\n"
"Packages/Convergence/rsv-coscon - \n"
"\tCalculate the cos content of the RSVs from a simulation\n"
"\tPCA.\n"
"\n"
"Tools/svd - \n"
"\tCompute the principal components via the SVD.\n"
"\tThis results in several matrix files including\n"
"\tthe RSVs used as input to the current tool. \n"
"\tThe file [prefix]_V.asc contains the RSV matrix.\n"
"\n"
"\n";
return(s);
}
//@cond TOOLS_INTERNAL
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("modes", po::value<uint>(&nmodes)->default_value(10), "Compute cosine content for first N modes");
}
string print() const {
ostringstream oss;
oss << boost::format("modes=%d") % nmodes;
return(oss.str());
}
};
// @endcond TOOLS_INTERNAL
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::BasicSelection* sopts = new opts::BasicSelection;
opts::BasicTrajectory* tropts = new opts::BasicTrajectory;
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(sopts).add(tropts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
cout << "# " << hdr << endl;
cout << "# " << vectorAsStringWithCommas<string>(options.print()) << endl;
AtomicGroup model = tropts->model;
pTraj traj = tropts->trajectory;
if (tropts->skip)
cerr << "Warning: --skip option ignored\n";
AtomicGroup subset = selectAtoms(model, sopts->selection);
vector<AtomicGroup> ensemble;
readTrajectory(ensemble, subset, traj);
// Read in and align...
boost::tuple<std::vector<XForm>, greal, int> ares = iterativeAlignment(ensemble);
AtomicGroup avg = averageStructure(ensemble);
NoAlignPolicy policy(avg, true);
RealMatrix V = rsv(ensemble, policy);
cout << "# n\tcoscon\n";
for (uint i=0; i<nmodes; ++i)
cout << i << "\t" << cosineContent(V, i) << endl;
}
| 4,358
|
C++
|
.cpp
| 116
| 33.706897
| 105
| 0.70231
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,169
|
chist.cpp
|
GrossfieldLab_loos/Packages/Convergence/chist.cpp
|
// Histogram of a time series using an increasingly larger window
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2014, Tod D. Romo and Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// @cond TOOLS_INTERNAL
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tCumulative or windowed histogram\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool can calculate either a cumulative or a windowed histogram. The former is\n"
"made by calculating the histogram of the input data up to time t. This is written out\n"
"as a row of data suitable for plotting with gnuplot using the splot command. Each row\n"
"then corresponds to calculating the histogram with more points. The alternative, is\n"
"to only calculate the histogram over a window that is slid along the data.\n"
"\n"
"EXAMPLES\n"
"\n"
"\tchist torsion_data >torsion_hist.asc\n"
"This example uses the defaults, which assumes the column to histogram is column 1\n"
"(i.e. the second column, since colunm indices are 0-based), wich 20 bins, a stride\n"
"through the data of 10 (every 10th datapoint is used in the histogram), the range\n"
"of the histogram is automatically determined from the data, and the histogram type\n"
"is cumulative.\n"
"\n"
"\tchist --min -180 --max 180 --nbins 50 --stride 2 torsion_data >torsion_hist.asc\n"
"This example is similar to the previous, except that the histogram range is explicitly\n"
"set to -180 to 180, 50 bins are used, and every other datapoint is taken.\n"
"\n"
"\tchist --mode window --window 250 torsion_data.asc >torsion_hist.asc\n"
"This example calculates a windowed histogram using 250 datapoints per histogram,\n"
"each window is slid 10 points down (the default for --stride)\n\n";
return(msg);
}
struct ToolOptions : public opts::OptionsPackage {
public:
enum ToolMode { CUMULATIVE, WINDOW };
static const unsigned char SETMIN_F = 0x01;
static const unsigned char SETMAX_F = 0x02;
ToolOptions() : col(1),
nbins(20),
window(100),
stride(10),
mode_string("cume"),
minval(0),
maxval(0),
range_flags(0),
mode(CUMULATIVE)
{}
void addGeneric(po::options_description& o) {
o.add_options()
("column,C", po::value<uint>(&col)->default_value(col), "Data column to use")
("nbins,N", po::value<uint>(&nbins)->default_value(nbins), "Number of bins in histogram")
("window", po::value<uint>(&window)->default_value(window), "Histogram window size")
("stride", po::value<uint>(&stride)->default_value(stride), "Stride through trajectory for cumulative histogram mode, or how far to slide the window")
("mode", po::value<string>(&mode_string)->default_value(mode_string), "Histogram mode: cume or window")
("min", po::value<double>(), "Set min value for histogram range")
("max", po::value<double>(), "Set max value for histogram range");
}
bool postConditions(po::variables_map& map) {
if (mode_string == "cume")
mode = CUMULATIVE;
else if (mode_string == "window")
mode = WINDOW;
else {
cerr << "ERROR- '" << mode_string << "' is an unknown mode. Must be either 'cume' or 'window'\n";
return(false);
}
if (map.count("min")) {
minval = map["min"].as<double>();
range_flags |= SETMIN_F;
}
if (map.count("max")) {
maxval = map["max"].as<double>();
range_flags |= SETMAX_F;
}
return(true);
}
string print() const {
ostringstream oss;
oss << boost::format("col=%d,nbins=%d,window=%d,stride=%d,mode='%s'")
% col
% nbins
% window
% stride
% mode_string;
return(oss.str());
}
uint col;
uint nbins;
uint window;
uint stride;
string mode_string;
double minval, maxval;
unsigned char range_flags;
ToolMode mode;
};
// @endcond
vector<double> histogram(const vector<double>& data,
const uint start,
const uint end,
const uint nbins,
const double minval,
const double maxval) {
vector<uint> hist(nbins, 0);
double delta = nbins / (maxval - minval);
for (uint i=start; i<end; ++i) {
uint bin = (data[i] - minval) * delta;
if (bin < nbins)
hist[bin] += 1;
}
vector<double> h(nbins);
uint nelems = end - start;
for (uint i=0; i<nbins; ++i)
h[i] = static_cast<double>(hist[i]) / nelems;
return(h);
}
pair<double, double> findMinMax(const vector<double>& data) {
double max = numeric_limits<double>::min();
double min = numeric_limits<double>::max();
for (vector<double>::const_iterator ci = data.begin(); ci != data.end(); ++ci) {
if (*ci < min)
min = *ci;
if (*ci > max)
max = *ci;
}
return(pair<double, double>(min, max));
}
vector<double> readData(const string& fname, const uint col)
{
vector< vector<double> > table = readTable<double>(fname);
vector<double> d(table.size());
for (uint i=0; i<table.size(); ++i)
d[i] = table[i][col];
return(d);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
ToolOptions* topts = new ToolOptions;
opts::RequiredArguments* ropts = new opts::RequiredArguments("datafile", "Name of file to histogram");
opts::AggregateOptions options;
options.add(bopts).add(topts).add(ropts);
if (!options.parse(argc, argv))
exit(-1);
vector<double> data = readData(ropts->value("datafile"), topts->col);
double minval, maxval;
pair<double,double> r = findMinMax(data);
minval = r.first;
maxval = r.second;
if (topts->range_flags & ToolOptions::SETMIN_F)
minval = topts->minval;
if (topts->range_flags & ToolOptions::SETMAX_F)
maxval = topts->maxval;
cout << "# " << hdr << endl;
cout << "# min = " << minval << endl << "# max = " << maxval << endl;
double factor = (maxval - minval) / topts->nbins;
if (topts->mode == ToolOptions::CUMULATIVE) {
for (uint y = topts->stride; y<data.size(); y += topts->stride) {
vector<double> h = histogram(data, 0, y, topts->nbins, minval, maxval);
for (uint n=0; n<topts->nbins; ++n) {
double x = (n + 0.5) * factor + minval;
cout << x << '\t' << y << '\t' << h[n] << endl;
}
cout << endl;
}
} else {
for (uint y = 0; y<data.size() + topts->window; y += topts->stride) {
vector<double> h = histogram(data, y, y+topts->window, topts->nbins, minval, maxval);
for (uint n=0; n<topts->nbins; ++n) {
double x = (n + 0.5) * factor + minval;
cout << x << '\t' << y << '\t' << h[n] << endl;
}
cout << endl;
}
}
}
| 7,757
|
C++
|
.cpp
| 198
| 33.813131
| 156
| 0.647414
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,170
|
assign_frames.cpp
|
GrossfieldLab_loos/Packages/Convergence/assign_frames.cpp
|
/*
Assign frames of a trajectory to bins (determined by reference structures)
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2011, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include "fid-lib.hpp"
using namespace std;
using namespace loos;
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tConstruct a structural histogram given a set of fiducial structures\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool assigns the frames of a trajectory to the closest bin based\n"
"on the fiducial structures given. See Lyman & Zuckerman,\n"
"J Phys Chem B (2007) 111:12876-12882 for more details.\n"
"\n"
"EXAMPLES\n"
"\n"
"\tassign_frames model.pdb simulation.dcd all 'name == \"CA\"' \\\n"
"\t zuckerman.dcd >assignments.asc\n"
"This example assigns all frames in simulation.dcd using the fiducials stored in zuckerman.dcd,\n"
"writing the assignments to assignments.asc.\n"
"\n"
"NOTES\n"
"\tThe selection used here must match that given to ufidpick\n"
"SEE ALSO\n"
"\tufidpick, effsize.pl, hierarchy, neff\n";
return(msg);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
if (argc != 6) {
cerr << "Usage - " << argv[0] << " model trajectory range selection fiducials.dcd >assignments.asc\n";
fullHelpMessage();
exit(-1);
}
int k = 1;
AtomicGroup model = createSystem(argv[k++]);
pTraj traj = createTrajectory(argv[k++], model);
string range(argv[k++]);
string selection(argv[k++]);
AtomicGroup subset = selectAtoms(model, selection);
AtomicGroup ref_model = subset.copy();
ref_model.resetAtomIndices();
pTraj fiducials = createTrajectory(argv[k++], ref_model);
vecUint frames;
if (range == "all")
for (uint i=0; i<traj->nframes(); ++i)
frames.push_back(i);
else
frames = parseRangeList<uint>(range);
vecGroup refs;
cerr << "Reading fiducials...\n";
readTrajectory(refs, ref_model, fiducials);
cerr << "Read in " << refs.size() << " fiducials.\n";
cerr << "Assigning...\n";
vecUint assigned = assignStructures(subset, traj, frames, refs);
cout << "# " << hdr << endl;
copy(assigned.begin(), assigned.end(), ostream_iterator<uint>(cout, "\n"));
}
| 3,020
|
C++
|
.cpp
| 79
| 34.43038
| 106
| 0.702749
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,171
|
bcom.cpp
|
GrossfieldLab_loos/Packages/Convergence/bcom.cpp
|
/*
Perform a block-overlap in comparison to a full PCA
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include "ConvergenceOptions.hpp"
#include "bcomlib.hpp"
using namespace std;
using namespace loos;
using namespace Convergence;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
typedef vector<AtomicGroup> vGroup;
typedef boost::tuple<RealMatrix, RealMatrix, RealMatrix> SVDResult;
// Configuration
const bool length_normalize = true;
uint nsteps = 25;
// Global options
bool local_average;
bool use_zscore;
uint ntries;
vector<uint> blocksizes;
uint seed;
string gold_standard_trajectory_name;
string fullHelpMessage() {
string s =
"\n"
"SYNOPSIS\n"
"\n"
"Perform a block-overlap in comparison to a full PCA\n"
"\n"
"DESCRIPTION\n"
"\n"
"This tool reports on how well a small \"block\" of a trajectory samples\n"
"the subspace explored by the full simulation using principal component\n"
"analysis. It does this by computing the covariance overlap between a\n"
"full simulation PCA and the PCA of increasingly longer contiguous \n"
"blocks of that trajectory.\n "
"\n"
"See: Romo and Grossfield, J. Chem. Theor. Comput., 2011, 7, 2464-2472\n"
"\n"
"The output is a tab separated stream:\n"
"n\tCoverlap\tVariance\tN_blocks\n"
"\n"
"\t n - current block size (nanoseconds)\n"
"\tCoverlap - covariance overlap between block and full PCA\n"
"\tVariance - variance in coverlap across all (N_blocks)\n"
"\tN_blocks - number of blocks of a given length\n"
"\n"
"USAGE NOTES\n"
"The --skip command is NOT used by this tool.\n"
"\n"
//
"EXAMPLES\n"
"bcom -s 'name==\"CA\"' --blocks 25:25:500 model.pdb traj.dcd > bcom_output\n"
"\tCalculate the bcom of traj.dcd using a PCA of CA atoms. This\n"
"\tis done for blocks in a range of 25 ns to 500 ns, with 25 ns\n"
"\tintervals. The result is written to the file bcom_output\n"
"\n"
"bcom -Z1 -s 'name==\"CA\"' --blocks 25:25:500 model.pdb traj.dcd > bcom_output\n"
"\tSame as the example above, but outputs the block-averaged \n"
"\tZ-score in the place of the block-averaged coverlap.\n"
"\n"
"bcom -s 'name==\"CA\"' --gold 'combined.dcd' model.pdb traj.dcd > bcom_output\n"
"\tHere we make two changes. First don't specify block sizes\n"
"\tThis tells bcom to figure it out on its own. In this case\n"
"\tthe tool will run a max block size equal to half the trajectory.\n"
"\tNext, we compare our block-averaged PCA results to a separate\n"
"\ttrajectory called combined.dcd instead of the PCA of the full\n"
"\ttraj.dcd. As the name implies, combined.dcd may be a concatonation\n"
"\tof several trajectories. \n"
"\t\tTo make such a concatoned trajectory see the tools\n"
"\t\tmerge-traj and subsetter.\n"
"\n"
"SEE ALSO\n"
"\n"
" Packages/Convergence/boot_bcom - \n"
"\tThis tool performs a similar analysis, but pulls random frames\n"
"\tfrom the trajectory rather than contiguous ones.\n"
"\t\n"
"* Visualization Notes *\n"
"\tThe output should be plotted in the format X:Y:SQRT(Y-error)\n"
"\twhere the colons separate the 1st 3 columns of the output.\n"
"\tThis puts stdev error bars on the result\n"
"\tIn GNUplot this would look like the following:\n"
"\t plot 'bcom_output' using 1:2:(sqrt(\\$3)) with errorlines\n"
"\n"
"\n";
return(s);
}
// @cond TOOLS_INTERAL
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("blocks", po::value<string>(&blocks_spec), "Block sizes (MATLAB style range)")
("steps", po::value<uint>(&nsteps)->default_value(25), "Max number of blocks for auto-ranging")
("zscore,Z", po::value<bool>(&use_zscore)->default_value(false), "Use Z-score rather than covariance overlap")
("ntries,N", po::value<uint>(&ntries)->default_value(20), "Number of tries for Z-score")
("local", po::value<bool>(&local_average)->default_value(true), "Use local avg in block PCA rather than global")
("gold", po::value<string>(&gold_standard_trajectory_name)->default_value(""), "Use this trajectory for the gold-standard instead");
}
bool postConditions(po::variables_map& vm) {
if (!blocks_spec.empty())
blocksizes = parseRangeList<uint>(blocks_spec);
return(true);
}
string print() const {
ostringstream oss;
oss << boost::format("blocks='%s', zscore=%d, ntries=%d, local=%d, gold='%s'")
% blocks_spec
% use_zscore
% ntries
% local_average
% gold_standard_trajectory_name;
return(oss.str());
}
string blocks_spec;
};
// Convenience structure for aggregating results
struct Datum {
Datum(const double avg, const double var, const uint nblks) : avg_coverlap(avg),
var_coverlap(var),
nblocks(nblks) { }
double avg_coverlap;
double var_coverlap;
uint nblocks;
};
// @endcond
vGroup subgroup(const vGroup& A, const uint a, const uint b) {
vGroup B;
for (uint i=a; i<b; ++i)
B.push_back(A[i]);
return(B);
}
// Breaks the ensemble up into blocks and computes the PCA for each
// block and the statistics for the covariance overlaps...
template<class ExtractPolicy>
Datum blocker(const RealMatrix& Ua, const RealMatrix sa, vGroup& ensemble, const uint blocksize, ExtractPolicy& policy) {
TimeSeries<double> coverlaps;
for (uint i=0; i<ensemble.size() - blocksize; i += blocksize) {
vGroup subset = subgroup(ensemble, i, i+blocksize);
boost::tuple<RealMatrix, RealMatrix> pca_result = pca(subset, policy);
RealMatrix s = boost::get<0>(pca_result);
RealMatrix U = boost::get<1>(pca_result);
// Scale the singular values by block-size
if (length_normalize)
for (uint j=0; j<s.rows(); ++j)
s[j] /= blocksize;
double val;
if (use_zscore) {
boost::tuple<double, double, double> result = zCovarianceOverlap(sa, Ua, s, U, ntries);
val = boost::get<0>(result);
} else
val = covarianceOverlap(sa, Ua, s, U);
coverlaps.push_back(val);
}
return( Datum(coverlaps.average(), coverlaps.variance(), coverlaps.size()) );
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::BasicSelection* sopts = new opts::BasicSelection;
opts::BasicTrajectory* tropts = new opts::BasicTrajectory;
opts::BasicConvergence* copts = new opts::BasicConvergence;
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(sopts).add(tropts).add(copts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
cout << "# " << hdr << endl;
cout << "# " << vectorAsStringWithCommas<string>(options.print()) << endl;
AtomicGroup model = tropts->model;
pTraj traj = tropts->trajectory;
if (tropts->skip)
cerr << "Warning: --skip option ignored\n";
if (blocksizes.empty()) {
uint n = traj->nframes();
uint half = n / 2;
uint step = half / nsteps;
if (step < 1)
step = 1;
cout << "# Auto block-sizes - " << step << ":" << step << ":" << half << endl;
for (uint i = step; i <= half; i += step)
blocksizes.push_back(i);
}
AtomicGroup subset = selectAtoms(model, sopts->selection);
vector<AtomicGroup> ensemble;
readTrajectory(ensemble, subset, traj);
// First, align the input trajectory...
boost::tuple<std::vector<XForm>, greal, int> ares = iterativeAlignment(ensemble);
cout << "# Alignment converged to " << boost::get<1>(ares) << " in " << boost::get<2>(ares) << " iterations\n";
cout << "# n\t" << (use_zscore ? "Z-score" : "Coverlap") << "\tVariance\tN_blocks\n";
// Handle the gold-standard, either using the whole input traj, or the alternate traj...
NoAlignPolicy policy;
RealMatrix Us;
RealMatrix UA;
if (gold_standard_trajectory_name.empty()) {
AtomicGroup avg = averageStructure(ensemble);
policy = NoAlignPolicy(avg, local_average);
boost::tuple<RealMatrix, RealMatrix> res = pca(ensemble, policy);
Us = boost::get<0>(res);
UA = boost::get<1>(res);
if (length_normalize)
for (uint i=0; i<Us.rows(); ++i)
Us[i] /= traj->nframes();
} else {
// Must read in another trajectory, process it, and get the PCA
pTraj gold = createTrajectory(gold_standard_trajectory_name, model);
vector<AtomicGroup> gold_ensemble;
readTrajectory(gold_ensemble, subset, gold);
boost::tuple<vector<XForm>, greal, int> bres = iterativeAlignment(gold_ensemble);
cout << "# Gold Alignment converged to " << boost::get<1>(bres) << " in " << boost::get<2>(bres) << " iterations\n";
AtomicGroup avg = averageStructure(gold_ensemble);
policy = NoAlignPolicy(avg, local_average);
boost::tuple<RealMatrix, RealMatrix> res = pca(gold_ensemble, policy);
Us = boost::get<0>(res);
UA = boost::get<1>(res);
if (length_normalize)
for (uint i=0; i<Us.rows(); ++i)
Us[i] /= gold->nframes();
}
// Now iterate over all requested block sizes
// Provide user-feedback since this can be a slow computation
PercentProgress watcher;
ProgressCounter<PercentTrigger, EstimatingCounter> slayer(PercentTrigger(0.1), EstimatingCounter(blocksizes.size()));
slayer.attach(&watcher);
slayer.start();
for (vector<uint>::iterator i = blocksizes.begin(); i != blocksizes.end(); ++i) {
Datum result = blocker(UA, Us, ensemble, *i, policy);
cout << *i << "\t" << result.avg_coverlap << "\t" << result.var_coverlap << "\t" << result.nblocks << endl;
slayer.update();
}
slayer.finish();
}
| 10,746
|
C++
|
.cpp
| 250
| 38.188
| 138
| 0.674808
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,172
|
hierarchy.cpp
|
GrossfieldLab_loos/Packages/Convergence/hierarchy.cpp
|
/*
hierarchy
Based on Zhang, Bhatt, and Zuckerman; JCTC, DOI: 10.1021/ct1002384
and code provided by the Zuckerman Lab
(http://www.ccbb.pitt.edu/Faculty/zuckerman/software.html)
Given a trajectory whose structures have been binned into states via
reference structures, computes the MFPT between states and then
constructs a hierarchy of states based on exchange rates
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// @cond TOOLS_INTERNAL
#include <loos.hpp>
#include <boost/format.hpp>
using namespace std;
using namespace loos;
typedef pair<uint, uint> uPair;
typedef vector<uint> vUint;
typedef vector<vUint> vvUint;
// Simple class to sort pairs of numbers based on a third (the rate)
struct RatePair {
RatePair(const double d, const uint a, const uint b) :
rate(d), pair(a,b) { }
bool operator<(const RatePair& x) const {
return(rate > x.rate);
}
double rate;
uPair pair;
};
// @endcond TOOLS_INTERNAL
// Debugging generates a lot of information about the internal state
// of the code. This was used to validate its operation with respect
// to Dan's PERL code.
const bool debugging = false;
double mfpt(const vector<uint>& assign, const uint x, const uint y) {
double fpt = 0.0;
uint n = 0;
bool state = false;
uint start = 0;
for (uint j=0; j<assign.size(); ++j) {
if (!state) {
if (assign[j] == x) {
start = j;
state = true;
}
} else {
if (assign[j] == y) {
fpt += (j - start);
++n;
state = false;
}
}
}
return(n != 0 ? static_cast<double>(n)/fpt : 0.0);
}
DoubleMatrix computeRates(const string& fname) {
ifstream ifs(fname.c_str());
if (!ifs) {
cerr << "Error- unable to open " << fname << endl;
exit(-1);
}
vector<uint> assignments = readVector<uint>(ifs);
uint nbins = 0;
for (vector<uint>::iterator i = assignments.begin(); i != assignments.end(); ++i)
if (*i > 0 && static_cast<uint>(*i) > nbins)
nbins = *i;
++nbins; // Bins are 0-based
DoubleMatrix M(nbins, nbins);
for (uint j=0; j<nbins; ++j)
for (uint i=0; i<nbins; ++i) {
if (i == j)
continue;
M(j, i) = mfpt(assignments, j, i);
}
for (uint j=0; j<nbins-1; ++j)
for (uint i=j+1; i<nbins; ++i)
if (M(j, i) > 0.0 && M(i, j) > 0.0) {
double d = (M(j, i) + M(i, j)) / 2.0;
M(j, i) = d;
} else
M(j, i) = 0.0;
return(M);
}
vector<uPair> sortRates(const DoubleMatrix& M) {
vector<RatePair> rates;
for (uint j=0; j<M.cols()-1; ++j)
for (uint i=j+1; i<M.cols(); ++i)
if (M(j, i) != 0.0)
rates.push_back(RatePair(M(j, i), j, i));
sort(rates.begin(), rates.end());
vector<uPair> pairs;
if (debugging)
cerr << "DEBUG> PAIR_BEGIN\n";
for (vector<RatePair>::iterator i = rates.begin(); i != rates.end(); ++i) {
pairs.push_back(i->pair);
if (debugging)
cerr << boost::format("%d %d = %f\n") % i->pair.first % i->pair.second % i->rate;
}
if (debugging)
cerr << "DEBUG> PAIR_END\n";
return(pairs);
}
void dumpMatrix(ostream& os, const vvUint& M) {
os << M.size() << endl;
for (uint j=0; j<M.size(); ++j) {
os << M[j].size() << "\t";
copy(M[j].begin(), M[j].end(), ostream_iterator<uint>(os, "\t"));
os << endl;
}
}
// Yes, this really needs to be commented... Maybe in the next release.
vvUint cluster(const vector<uPair>& pairs) {
vvUint states;
vUint list;
list.push_back(pairs[0].first);
list.push_back(pairs[0].second);
states.push_back(list);
// Skip the last pair so we have 2 states...
for (uint i=1; i<pairs.size()-1; ++i) {
if (debugging)
cerr << boost::format("DEBUG> i=%d, first=%d, second=%d\n") % i % pairs[i].first % pairs[i].second;
bool flag1 = false, flag2 = false;
uint bin1_state = 0, bin1_element = 0;
uint bin2_state = 0, bin2_element = 0;
for (uint j=0; j<states.size(); ++j)
for (uint k=0; k<states[j].size(); ++k) {
if (states[j][k] == pairs[i].first) {
bin1_state = j;
bin1_element = k;
flag1 = true;
}
if (states[j][k] == pairs[i].second) {
bin2_state = j;
bin2_element = k;
flag2 = true;
}
}
if (debugging)
cerr << boost::format("DEBUG> flag1=%d, flag2=%d\n") % flag1 % flag2;
if (flag1 && flag2) {
uint big = bin1_state;
uint small = bin2_state;
if (bin1_state < bin2_state) {
big = bin2_state;
small = bin1_state;
}
if (debugging)
cerr << boost::format("DEBUG> small=%d, big=%d\n") % small % big;
bool flag3 = false;
for (uint w = 0; w<states[big].size() && !flag3; ++w)
for (uint z=0; z<states[small].size() && !flag3; ++z) {
bool failed = true;
for (uint y=0; y<=i; ++y)
if ( (states[small][z] == pairs[y].first && states[big][w] == pairs[y].second)
|| (states[small][z] == pairs[y].second && states[big][w] == pairs[y].first) ) {
failed = false;
break;
}
if (failed) {
flag3 = true;
if (debugging)
cerr << boost::format("DEBUG> Check failed for w=%d, z=%d\n") % w % z;
}
}
if (!flag3) {
if (debugging)
cerr << "DEBUG> *Merging states*\n";
copy(states[big].begin(), states[big].end(), back_inserter(states[small]));
states.erase(states.begin() + big);
}
} else if (flag1) {
bool failed = false;
for (uint p=0; p<states[bin1_state].size() && !failed; ++p) {
if (p == bin1_element)
continue;
failed = true;
for (uint q=0; q<i; ++q)
if ( (states[bin1_state][p] == pairs[q].first && pairs[i].second == pairs[q].second)
|| (states[bin1_state][p] == pairs[q].second && pairs[i].second == pairs[q].first) ) {
failed = false;
break;
}
}
if (debugging)
cerr << boost::format("DEBUG> [1] failed=%d\n") % failed;
if (!failed)
states[bin1_state].push_back(pairs[i].second);
} else if (flag2) {
bool failed = false;
for (uint p=0; p<states[bin2_state].size() && !failed; ++p) {
if (p == bin2_element)
continue;
failed = true;
for (uint q=0; q<i; ++q)
if ( (states[bin2_state][p] == pairs[q].first && pairs[i].first == pairs[q].second)
|| (states[bin2_state][p] == pairs[q].second && pairs[i].first == pairs[q].first) ) {
failed = false;
break;
}
}
if (debugging)
cerr << boost::format("DEBUG> [1] failed=%d\n") % failed;
if (!failed)
states[bin2_state].push_back(pairs[i].first);
} else {
if (debugging)
cerr << "DEBUG> Adding new state.\n";
vUint newlist;
newlist.push_back(pairs[i].first);
newlist.push_back(pairs[i].second);
states.push_back(newlist);
}
if (debugging) {
dumpMatrix(cerr,states);
cerr << "DEBUG> --------------------------------------\n";
}
}
if (debugging)
cerr << "DEBUG> final states = " << states.size() << endl;
return(states);
}
void findOrphans(vvUint& states, const uint max_states) {
vUint seen;
if (debugging)
cerr << "DEBUG> Finding orphans- ";
for (vvUint::iterator v = states.begin(); v != states.end(); ++v)
copy(v->begin(), v->end(), back_inserter(seen));
vUint unseen;
for (uint i = 0; i<max_states; ++i)
if (find(seen.begin(), seen.end(), i) == seen.end())
unseen.push_back(i);
if (debugging)
cerr << "found " << unseen.size() << endl;
if (! unseen.empty())
states.push_back(unseen);
}
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tPerform a hierarchical clustering needed to determine effective sample size\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool implements the hierarchical clustering algorithm as part of determining\n"
"effective sample size described in Zhang, Batt, and Zuckerman, JCTC (2010) 6:3048-57.\n"
"\n"
"EXAMPLES\n"
"\n"
"\thierarchy assignments.asc >zuckerman.states\n"
"\n"
"SEE ALSO\n"
"\tufidpick, assign_frames, neff, effsize.pl\n";
return(msg);
}
int main(int argc, char *argv[]) {
if (argc == 1) {
cout << "Usage- " << argv[0] << " assignments_file\n";
exit(0);
}
string hdr = invocationHeader(argc, argv);
int k = 1;
DoubleMatrix M = computeRates(argv[k++]);
vector<uPair> pairs = sortRates(M);
if (pairs.empty()) {
cerr << "Error- hierarchy failed to compute rates. Double-check how the assignments\n"
<< " file was generated. Did you use ufidpick to pick the fiducials?\n"
<< " Is the cutoff reasonable? Is the selection correct (use model-select\n"
<< " to confirm)?\n";
exit(-10);
}
vvUint states = cluster(pairs);
// Not all states will get clustered, so manually search for
// "orphaned" ones and add them in...
findOrphans(states, M.rows());
cout << "# " << hdr << endl;
dumpMatrix(cout, states);
// If this happens, you are likely very undersampled
if (states.size() != 2)
cerr << boost::format("Warning- clustering finished with %d states.\n") % states.size();
}
| 10,278
|
C++
|
.cpp
| 295
| 28.888136
| 105
| 0.588379
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,173
|
fid-lib.cpp
|
GrossfieldLab_loos/Packages/Convergence/fid-lib.cpp
|
/*
fid-lib
Fiducial library
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fid-lib.hpp"
using namespace std;
using namespace loos;
vecUint findFreeFrames(const vecInt& map) {
vecUint indices;
for (uint i=0; i<map.size(); ++i)
if (map[i] < 0)
indices.push_back(i);
return(indices);
}
vecUint assignStructures(AtomicGroup& model, pTraj& traj, const vecUint& frames, const vecGroup& refs) {
vecUint assignments(frames.size(), 0);
uint j = 0;
for (vecUint::const_iterator frame = frames.begin(); frame != frames.end(); ++frame) {
traj->readFrame(*frame);
traj->updateGroupCoords(model);
double mind = numeric_limits<double>::max();
uint mini = refs.size() + 1;
for (uint i = 0; i < refs.size(); ++i) {
model.alignOnto(refs[i]);
double d = model.rmsd(refs[i]);
if (d < mind) {
mind = d;
mini = i;
}
}
assignments[j++] = mini;
}
return(assignments);
}
vecUint trimFrames(const vecUint& frames, const double frac) {
uint bin_size = frac * frames.size();
uint remainder = frames.size() - static_cast<uint>(bin_size / frac);
vecUint truncated;
vecUint::const_iterator vi = frames.begin();
for (uint i = 0; i<frames.size() - remainder; ++i)
truncated.push_back(*vi++);
return(truncated);
}
boost::tuple<vecGroup, vecUint> pickFiducials(AtomicGroup& model, pTraj& traj, const vecUint& frames, const double f) {
// Size of bin
uint bin_size = f * frames.size();
// Initialize a RNG to use a uniform random distribution.
// Use the LOOS generator singleton so the random number stream can
// be seeded (or automatically seeded) by LOOS...
boost::uniform_real<> rmap;
boost::variate_generator< base_generator_type&, boost::uniform_real<> > rng(rng_singleton(), rmap);
// Vector of AtomicGroup's representing the fiducial structures
vecGroup fiducials;
// Track which trajectory frame has been assigned to which fiducial
vecInt assignments(frames.size(), -1);
// The indices (frame #'s) of the structures picked to be fiducials
vecUint refs;
vecDouble radii;
// Unassigned frames...bootstrap the loop
vecUint possible_frames = findFreeFrames(assignments);
// Are there any unassigned frames left?
while (! possible_frames.empty()) {
// Randomly pick one
uint pick = possible_frames[static_cast<uint>(floor(possible_frames.size() * rng()))];
traj->readFrame(frames[pick]);
traj->updateGroupCoords(model);
// Make a copy and assign a new bin # to the fiducial
AtomicGroup fiducial = model.copy();
fiducial.centerAtOrigin();
uint myid = fiducials.size();
if (assignments[pick] >= 0) {
cerr << "INTERNAL ERROR - " << pick << " pick was already assigned to " << assignments[pick] << endl;
exit(-99);
}
fiducials.push_back(fiducial);
refs.push_back(pick);
// Now find the distance from every unassigned frame to this new fiducial (aligning
// them first), and then sort by distance...
vector<double> distances(assignments.size(), numeric_limits<double>::max());
for (uint i = 0; i<assignments.size(); ++i) {
if (assignments[i] >= 0)
continue;
traj->readFrame(frames[i]);
traj->updateGroupCoords(model);
model.centerAtOrigin();
model.alignOnto(fiducial);
distances[i] = model.rmsd(fiducial);
}
vecUint indices = sortedIndex(distances);
uint picked = 0;
double maxd = 0.0;
// Pick the first bin_size of them (or however many are remaining)
// and assign these to the newly picked fiducial
for (uint i=0; i<assignments.size() && picked < bin_size; ++i) {
if (assignments[indices[i]] < 0) {
assignments[indices[i]] = myid;
++picked;
if (distances[indices[i]] > maxd)
maxd = distances[indices[i]];
}
}
radii.push_back(maxd);
possible_frames = findFreeFrames(assignments);
}
// Safety check...
for (vecInt::const_iterator i = assignments.begin(); i != assignments.end(); ++i)
if (*i < 0)
throw(runtime_error("A frame was not assigned in binFrames()"));
boost::tuple<vecGroup, vecUint> result(fiducials, refs);
return(result);
}
int findMaxBin(const vecInt& assignments) {
int max_bin = -1;
for (vecInt::const_iterator i = assignments.begin(); i != assignments.end(); ++i)
if (*i > max_bin)
max_bin = *i;
return(max_bin);
}
vecUint histogramBins(const vecInt& assignments) {
int max = findMaxBin(assignments);
vecUint histogram(max+1, 0);
for (vecInt::const_iterator i = assignments.begin(); i != assignments.end(); ++i)
if (*i >= 0)
histogram[*i] += 1;
return(histogram);
}
| 5,519
|
C++
|
.cpp
| 142
| 34.246479
| 119
| 0.683833
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,174
|
rsv-coscon.cpp
|
GrossfieldLab_loos/Packages/Convergence/rsv-coscon.cpp
|
/*
Matrix cosine content. Calculates the cosine content
of a matrix. Expected input is the RSVs of a PCA...
based on:
Hess, B. "Convergence of sampling in protein simulations."
Phys Rev E (2002) 65(3):031910
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2011, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include "bcomlib.hpp"
using namespace std;
using namespace loos;
using namespace Convergence;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
typedef vector<AtomicGroup> vGroup;
uint nmodes;
string rsv;
string fullHelpMessage() {
string s =
"\n"
"SYNOPSIS\n"
"\n"
"Calculate the cosine constent of a right singular vector matrix\n"
"\n"
"DESCRIPTION\n"
"\n"
"This tool calculates the cosine content of a matrix.\n"
"It is intended to be used on the right sinular vectors\n"
"from an SVD. These are projections onto to principal\n"
"components of the simulation.\n"
"\n"
"See: Hess, B. \"Convergence of sampling in protein \n"
" simulations.\" Phys Rev E (2002) 65(3):031910\n"
//Matrix cosine content. Calculates the cosine content
//of a matrix. Expected input is the RSVs of a PCA...
"\n"
"\n"
"EXAMPLES\n"
"\n"
"rsv-coscon pca_V.asc\n"
"\tCompute the cos content of the first 10 (default)\n"
"\tright singular vectors from a simulation PCA. If\n"
"\tthe PCA was computed with the LOOS SVD tool, the \n"
"\tRSVs are stored in _V.asc\n"
"\n"
"rsv-coscon --modes=5 pca_V.asc\n"
"\tCompute the cos content of the first 5 RSVs only.\n"
"\n"
"SEE ALSO\n"
"Packages/Convergence/coscon - \n"
"\tCompute the cosine content of a matrix. This tool\n"
"\tperforms a similar analysis, but it uses a block\n"
"\taveraging approach where the cosine content is\n"
"\tcalculated for increasingly long trajectory blocks\n"
"\n"
"Packages/Convergence/qcoscon - \n"
"\tPerform a quick cos content analysis on a simulation.\n"
"\tSimilar to coscon, but only performs the analysis on\n"
"\tthe full length simulation.\n"
"\n"
"Tools/svd - \n"
"\tCompute the principal components via the SVD.\n"
"\tThis results in several matrix files including\n"
"\tthe RSVs used as input to the current tool. \n"
"\tThe file [prefix]_V.asc contains the RSV matrix.\n"
"\n"
"\n";
return(s);
}
//@cond TOOLS_INTERNAL
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("modes", po::value<uint>(&nmodes)->default_value(10), "Compute cosine content for first N modes");
}
string print() const {
ostringstream oss;
oss << boost::format("modes=%d") % nmodes;
return(oss.str());
}
};
// @endcond TOOLS_INTERNAL
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
// opts::BasicOptions* bopts = new opts::BasicOptions;
ToolOptions* topts = new ToolOptions;
opts::RequiredArguments* ropts = new opts::RequiredArguments("rsv", "right-singular-vectors");
opts::AggregateOptions options;
options.add(bopts).add(topts).add(ropts);
if (!options.parse(argc, argv))
exit(-1);
cout << "# " << hdr << endl;
cout << "# " << vectorAsStringWithCommas<string>(options.print()) << endl;
RealMatrix V;
readAsciiMatrix(ropts->value("rsv"), V);
cout << "# n\tcoscon\n";
for (uint i=0; i<nmodes; ++i)
cout << i << "\t" << cosineContent(V, i) << endl;
}
| 4,407
|
C++
|
.cpp
| 117
| 33.726496
| 105
| 0.691584
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,175
|
sortfids.cpp
|
GrossfieldLab_loos/Packages/Convergence/sortfids.cpp
|
/*
sortfids
Structural histogram, a la Lyman &
Zuckerman, Biophys J (2006) 91:164-172
Usage- sortfids model selection fids hist newfidname
Sorts fiducials based on decreasing histogram bin population
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2010, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
typedef vector<AtomicGroup> vGroup;
typedef Math::Matrix<double, Math::RowMajor> Matrix;
// @cond TOOLS_INTERNAL
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tSorts fiducial structures based on histogram bin population\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tGiven a set of fiducials for a structural histogram, sort them based\n"
"on bin population. This can be useful when using fidpick, which selects\n"
"fiducials based on distance rather than bin probability.\n"
"\n"
"SEE ALSO\n"
"\tfidpick\n";
return(msg);
}
// Sorts based on 3rd col of a matrix
struct Adapter {
Adapter(const Matrix& M) : A(M) { }
uint size() const { return(A.rows()); }
const double& operator[](const uint i) const {
return(A(i,2));
}
const Matrix& A;
};
// @endcond
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
if (argc != 6) {
cerr << "Usage- sortfids model sel fids hist newfids\n";
cerr << fullHelpMessage();
exit(-1);
}
int opti = 1;
AtomicGroup model = createSystem(argv[opti++]);
string selection(argv[opti++]);
AtomicGroup subset = selectAtoms(model, selection);
subset.renumber();
pTraj fids = createTrajectory(argv[opti++], subset);
vGroup fiducials;
readTrajectory(fiducials, subset, fids);
Matrix M;
readAsciiMatrix(argv[opti++], M);
vector<uint> indices = sortedIndex<Adapter, DescendingSort<Adapter> >(Adapter(M));
vGroup sorted;
Matrix A(M.rows(), M.cols());
for (uint i=0; i<M.rows(); ++i) {
sorted.push_back(fiducials[indices[i]]);
A(i,0) = i;
A(i,1) = M(indices[i], 1);
A(i,2) = M(indices[i], 2);
}
DCDWriter(argv[opti++], sorted, hdr);
writeAsciiMatrix(cout, A, hdr);
}
| 2,903
|
C++
|
.cpp
| 84
| 31
| 84
| 0.709294
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,176
|
boot_bcom.cpp
|
GrossfieldLab_loos/Packages/Convergence/boot_bcom.cpp
|
/*
Perform a bootstrap analysis of a trajectory
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2009, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include "ConvergenceOptions.hpp"
#include "bcomlib.hpp"
using namespace std;
using namespace loos;
using namespace Convergence;
namespace opts = loos::OptionsFramework;
namespace po = boost::program_options;
const bool debug = false;
typedef vector<AtomicGroup> vGroup;
typedef boost::tuple<RealMatrix, RealMatrix, RealMatrix> SVDResult;
// Configuration
const bool length_normalize = true;
uint nsteps = 25;
// Global options
vector<uint> blocksizes;
bool local_average;
uint nreps;
string gold_standard_trajectory_name;
string fullHelpMessage() {
string s =
"\n"
"SYNOPSIS\n"
"\n"
"Perform a bootstrapped block-overlap comparison to a full PCA\n"
"\n"
"DESCRIPTION\n"
"\n"
"This tool reports on how well a small \"block\" of a trajectory samples\n"
"the subspace explored by the full simulation using principal component\n"
"analysis. Similar to bcom it does this by computing the covariance\n"
"overlap between a full simulation PCA and the PCA of increasingly \n"
"longer \"blocks\". The DIFFERENCE is that the blocks in this version\n"
"are not contiguous, but rather pulled randomly from the trajectory.\n"
"\n"
"Where bcom shows how well a short subset of a trajectory samples the\n"
"conformational subspace present in the full simulation; boot_bcom shows\n"
"how well a given number of random frames sample the full subspace \n"
"explored in the simulation. This bootstrap analysis can then be\n"
"compared to the bcom result.\n"
"\n"
"See: Romo and Grossfield, J. Chem. Theor. Comput., 2011, 7, 2464-2472\n"
"\t Specifically Figs 4, 6, and 9 for comparison to bcom results.\n"
"\n"
"\n"
"The output is a tab separated stream:\n"
"n\tCoverlap\tVariance\tN_blocks\n"
"\n"
"\t n - current block size (nanoseconds)\n"
"\tCoverlap - covariance overlap between block and full PCA\n"
"\tVariance - variance in coverlap across all (N_blocks)\n"
"\tN_blocks - number of blocks of a given length\n"
"\t Note that this number is constant unlike\n"
"\t the output of bcom\n"
"\n"
"USAGE NOTES\n"
"The --skip command is NOT used by this tool.\n"
"\n"
//
"EXAMPLES\n"
"\n"
"boot_bcom -s 'name==\"CA\"' --blocks 25:25:500 model.pdb traj.dcd\n"
"\tCalculate the bootstrapped bcom of traj.dcd using a PCA of CA\n"
"\tatoms. This is done for \"blocks\" in a range of 25 ns to 500 ns,\n"
"\twith 25 ns intervals. However, the blocks are NOT contiguous, but\n"
"\tare pulled randomly from the trajectory.\n"
"\n"
"boot_bcom -s 'name==\"CA\"' --gold 'combined.dcd' model.pdb traj.dcd\n"
"\tHere we make two changes. First don't specify block sizes\n"
"\tThis tells bcom to figure it out on its own. In this case\n"
"\tthe tool will run through block sizes from ... to the full\n"
"\tlength trajectory. Next, we compare our block-averaged PCA\n"
"\tresults to a separate trajectory called combined.dcd instead\n"
"\tof the PCA of the full traj.dcd. As the name implies, \n"
"\tcombined.dcd may be a concatonation of several trajectories.\n"
"\t\tTo make such a concatoned trajectory see the tools\n"
"\t\tmerge-traj and subsetter.\n"
"\n"
"boot_bcom -s 'name==\"CA\"' --reps=10 --steps=10 model.pdb traj.dcd\n"
"\tHere, we specify the number of reps and number of steps.\n"
"\tThe number of reps is how many trails or each block size\n"
"\twill be used in the averaging. The number of steps says\n"
"\tthat a maximum of 10 different block lengths will be used\n"
"\tin the calculation.\n"
"SEE ALSO\n"
"\n"
" Packages/Convergence/bcom - \n"
"\tThis tool performs a similar analysis, but pulls random frames\n"
"\tfrom the trajectory rather than contiguous ones.\n"
"\t\n"
"* Visualization Notes *\n"
"\tThe output should be plotted in the format X:Y:SQRT(Y-error)\n"
"\twhere the colons separate the 1st 3 columns of the output.\n"
"\tThis puts stdev error bars on the result\n"
"\tIn GNUplot this would look like the following:\n"
"\t plot 'bcom_output' using 1:2:(sqrt(\\$3)) with errorlines\n"
"\n"
"\n";
return(s);
}
// @cond TOOLS_INTERAL
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("blocks", po::value<string>(&blocks_spec), "Block sizes (MATLAB style range)")
("steps", po::value<uint>(&nsteps)->default_value(25), "Max number of blocks for auto-ranging")
("reps", po::value<uint>(&nreps)->default_value(20), "Number of replicates for bootstrap")
("local", po::value<bool>(&local_average)->default_value(true), "Use local avg in block PCA rather than global")
("gold", po::value<string>(&gold_standard_trajectory_name)->default_value(""), "Use this trajectory for the gold-standard instead");
}
bool postConditions(po::variables_map& vm) {
if (!blocks_spec.empty())
blocksizes = parseRangeList<uint>(blocks_spec);
return(true);
}
string print() const {
ostringstream oss;
oss << boost::format("blocks='%s', local=%d, reps=%d, gold='%s'")
% blocks_spec
% local_average
% nreps
% gold_standard_trajectory_name;
return(oss.str());
}
string blocks_spec;
};
// Convenience structure for aggregating results
struct Datum {
Datum(const double avg, const double var, const uint nblks) : avg_coverlap(avg),
var_coverlap(var),
nblocks(nblks) { }
double avg_coverlap;
double var_coverlap;
uint nblocks;
};
// @endcond
// Randomly pick frames
vector<uint> pickFrames(const uint nframes, const uint blocksize) {
boost::uniform_int<uint> imap(0,nframes-1);
boost::variate_generator< base_generator_type&, boost::uniform_int<uint> > rng(rng_singleton(), imap);
vector<uint> picks;
for (uint i=0; i<blocksize; ++i)
picks.push_back(rng());
return(picks);
}
void dumpPicks(const vector<uint>& picks) {
cerr << "Picks:\n";
for (vector<uint>::const_iterator ci = picks.begin(); ci != picks.end(); ++ci)
cerr << "\t" << *ci << endl;
}
// Extract a subgroup of the vector<AtomicGroup> given the indices in picks...
vGroup subgroup(const vGroup& A, const vector<uint>& picks) {
vGroup B;
for (vector<uint>::const_iterator ci = picks.begin(); ci != picks.end(); ++ci)
B.push_back(A[*ci]);
return(B);
}
// Breaks the ensemble up into blocks and computes the PCA for each
// block and the statistics for the covariance overlaps...
template<class ExtractPolicy>
Datum blocker(const RealMatrix& Ua, const RealMatrix sa, const vGroup& ensemble, const uint blocksize, uint repeats, ExtractPolicy& policy) {
TimeSeries<double> coverlaps;
for (uint i=0; i<repeats; ++i) {
vector<uint> picks = pickFrames(ensemble.size(), blocksize);
if (debug) {
cerr << "***Block " << blocksize << ", replica " << i << ", picks " << picks.size() << endl;
dumpPicks(picks);
}
vGroup subset = subgroup(ensemble, picks);
boost::tuple<RealMatrix, RealMatrix> pca_result = pca(subset, policy);
RealMatrix s = boost::get<0>(pca_result);
RealMatrix U = boost::get<1>(pca_result);
if (length_normalize)
for (uint j=0; j<s.rows(); ++j)
s[j] /= blocksize;
coverlaps.push_back(covarianceOverlap(sa, Ua, s, U));
}
return( Datum(coverlaps.average(), coverlaps.variance(), coverlaps.size()) );
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::BasicSelection* sopts = new opts::BasicSelection;
opts::BasicTrajectory* tropts = new opts::BasicTrajectory;
opts::BasicConvergence* copts = new opts::BasicConvergence;
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(sopts).add(tropts).add(copts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
cout << "# " << hdr << endl;
cout << "# " << vectorAsStringWithCommas<string>(options.print()) << endl;
AtomicGroup model = tropts->model;
pTraj traj = tropts->trajectory;
if (tropts->skip)
cerr << "Warning: --skip option ignored\n";
if (blocksizes.empty()) {
uint n = traj->nframes();
uint half = n / 2;
uint step = half / nsteps;
if (step < 1)
step = 1;
cout << "# Auto block-sizes - " << step << ":" << step << ":" << half << endl;
for (uint i = step; i <= half; i += step)
blocksizes.push_back(i);
}
AtomicGroup subset = selectAtoms(model, sopts->selection);
vector<AtomicGroup> ensemble;
readTrajectory(ensemble, subset, traj);
// First, align the input trajectory...
boost::tuple<std::vector<XForm>, greal, int> ares = iterativeAlignment(ensemble);
cout << "# Alignment converged to " << boost::get<1>(ares) << " in " << boost::get<2>(ares) << " iterations\n";
cout << "# n\tCoverlap\tVariance\tN_blocks\n";
// Handle the gold-standard, either using the whole input traj, or the alternate traj...
NoAlignPolicy policy;
RealMatrix Us;
RealMatrix UA;
if (gold_standard_trajectory_name.empty()) {
AtomicGroup avg = averageStructure(ensemble);
policy = NoAlignPolicy(avg, local_average);
boost::tuple<RealMatrix, RealMatrix> res = pca(ensemble, policy);
Us = boost::get<0>(res);
UA = boost::get<1>(res);
if (length_normalize)
for (uint i=0; i<Us.rows(); ++i)
Us[i] /= traj->nframes();
} else {
// Must read in another trajectory, process it, and get the PCA
pTraj gold = createTrajectory(gold_standard_trajectory_name, model);
vector<AtomicGroup> gold_ensemble;
readTrajectory(gold_ensemble, subset, gold);
boost::tuple<vector<XForm>, greal, int> bres = iterativeAlignment(gold_ensemble);
cout << "# Gold Alignment converged to " << boost::get<1>(bres) << " in " << boost::get<2>(bres) << " iterations\n";
AtomicGroup avg = averageStructure(gold_ensemble);
policy = NoAlignPolicy(avg, local_average);
boost::tuple<RealMatrix, RealMatrix> res = pca(gold_ensemble, policy);
Us = boost::get<0>(res);
UA = boost::get<1>(res);
if (length_normalize)
for (uint i=0; i<Us.rows(); ++i)
Us[i] /= gold->nframes();
}
// Now iterate over all requested block sizes...
PercentProgress watcher;
ProgressCounter<PercentTrigger, EstimatingCounter> slayer(PercentTrigger(0.1), EstimatingCounter(blocksizes.size()));
slayer.attach(&watcher);
slayer.start();
for (vector<uint>::iterator i = blocksizes.begin(); i != blocksizes.end(); ++i) {
Datum result = blocker(UA, Us, ensemble, *i, nreps, policy);
cout << *i << "\t" << result.avg_coverlap << "\t" << result.var_coverlap << "\t" << result.nblocks << endl;
slayer.update();
}
slayer.finish();
}
| 11,993
|
C++
|
.cpp
| 274
| 39.051095
| 141
| 0.675911
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,177
|
transition_contacts.cpp
|
GrossfieldLab_loos/Tools/transition_contacts.cpp
|
/*
transition_contacts: compute the fraction of native contacts in a trajectory,
based on an initial structure.
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2013, Nick Leioats, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// @cond TOOLS_INTERNAL
class ToolOptions : public opts::OptionsPackage {
public:
ToolOptions() :
selection("!(segid == 'BULK' || segid == 'SOLV' || hydrogen)")
{ }
void addGeneric(po::options_description& o) {
o.add_options()
("selection", po::value<string>(&selection)->default_value(selection), "Selection for calculation")
("cutoff", po::value<double>(&cutoff)->default_value(8.0), "Cutoff to use for defining contacts")
("source-selection", po::value<string>(&source_sel)->default_value(""), "Selection specific to source model")
("sink-selection", po::value<string>(&sink_sel)->default_value(""), "Selection specific to sink model")
("timeseries", po::value<string>(×eries)->default_value(""), "Report contacts as a timeseries")
("include-heavy", po::value<bool>(&leave_heavy)->default_value(false), "Include backbone and hydrogen atoms")
("smoothed-transition", po::value<bool>(&smoothed_transition)->default_value(true), "Use tanh smoothing of the transition ");
}
void addHidden(po::options_description& o) {
o.add_options()
("source-model", po::value<string>(&source_model), "Source model")
("sink-model", po::value<string>(&sink_model), "Sink model");
}
void addPositional(po::positional_options_description& p) {
p.add("source-model", 1);
p.add("sink-model", 1);
}
string help() const { return("source-model sink-model"); }
string print() const {
ostringstream oss;
oss << boost::format("sink-sel='%s', source-sel='%s', timeseries=%s")
% cutoff
% smoothed_transition
% sink_sel
% source_sel
% timeseries
% leave_heavy;
return(oss.str());
}
bool postConditions(po::variables_map& map) {
if (sink_sel.empty()) {
sink_sel = selection;
cerr << "Warning: Using --selection for sink\n";
}
if (source_sel.empty()) {
source_sel = selection;
cerr << "Warning: Using --selection for source\n";
}
return(true);
}
double cutoff;
string sink_model, source_model;
string selection;
string sink_sel, source_sel;
string timeseries;
bool leave_heavy, smoothed_transition;
};
// @endcond
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\n"
"Calculate the normalized transition between two structures.\n"
"\n"
"\n"
"DESCRIPTION\n"
"\n"
"This tool will calculate the number of unique contacts in\n"
"a trajectory in order to asses its transition from a source\n"
"structure to a sink structure. Contacts are defined using\n"
"two input structures. The set of contacts which differ between\n"
"the two input structures are then used in the calculation.\n"
"This tool explicitly uses the side-chain centriods for the\n"
"calculation. (Note: In this context the word \'unique\' is used\n"
"to describe those contacts present in only the source OR the\n"
"sink structure.)\n"
"\n"
"The result is a normalized count of the number of contacts\n"
"broken and formed for each frame of the trajectory.\n"
"The output is 4 columns:\n"
"\tFrame - trajectory frame number\n"
"\tContacts broken - Number of unique source contacts broken\n"
"\tContacts formed - Number of unique sink contacts formed\n"
"\tTransition - Normalized sum of broken and formed\n"
"\n"
"Optionally, a timeseries of each contact's state may be\n"
"written out. By default, these values are scaled by a \n"
"tanh function centered at the cutoff. This effectively\n"
"smooths the transition matrix so contacts near the cutoff\n"
"have less \"flicker\" between broken and formed. This can\n"
"be changed to a step function by using the option\n"
"\t \"--smoothed-transition=false\"\n"
"In that case 1's are written for formed contacts and 0's\n"
"for broken contacts. Additionally, a list of all changed\n"
"contacts is output for reference.\n"
"\n"
"\n"
"\n"
//
"EXAMPLE\n"
"transition_contacts --cutoff 8 --selection \'segid==\"PROT\"\' model.pdb traj.dcd source.pdb sink.pdb\n"
"\tHere we are calculating how far our simulation has\n"
"\ttransitioned away from the structure in source.pdb\n"
"\ttowards the structure in sink.pdb. The selection\n"
"\tspecifies the entire segid \"PROT\" is used in the\n"
"\tcalculation. In this example the same selection is\n"
"\tapplied to both the source and sink models as well.\n"
"\tAn 8 angstrom cutoff is used to define connectivity.\n"
"\t\n"
"\t\n"
"transition_contacts --sink_sel 'resid >=0 && resid <= 10' --source_sel 'resid >= 100 && resid <= 110' --cutoff 8 --selection \'segid==\"PROT\"\' model.pdb traj.dcd source.pdb sink.pdb\n"
"\tSame as the above command, but now the selections\n"
"\tfor the source and sink models are separately specified.\n"
"\tIMPORTANT: It is your responsibility to ensure that\n"
"\tthe atoms selected in all three models match. This\n"
"\ttool will run regardless, pushing residues onto a \n"
"\tvector. \n"
"\t\n"
"\t\n"
"transition_contacts --timeseries output-time --selection \'segid==\"PROT\"\' model.pdb traj.dcd source.pdb sink.pdb\n"
"\tSame options as the first example, but now we\n"
"\toutput the timeseries of contacts to the file\n"
"\toutput-time in addition to the standard output.\n"
"\t\n"
"\t\n"
"transition_contacts --include-heavy 1 --timeseries output-time --selection \'segid==\"PROT\"\' model.pdb traj.dcd source.pdb sink.pdb\n"
"\tSame as the example above, but now the calculation\n"
"\tincludes backbone atoms and hydrogen atoms. Where\n"
"\tin previous examples these were excluded from the\n"
"\tcalculation.\n"
"\t\n"
"\t\n"
"SEE ALSO\n"
"native_contacts -\n"
"This tool calculates the changes in contacts when a 2nd structure\n"
"is not available.\n"
"\t\n"
"\t\n"
"\n";
return(msg);
}
//### MAIN
int main (int argc, char *argv[]){
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::BasicTrajectory* tropts = new opts::BasicTrajectory;
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(tropts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
cout << "# " << hdr << endl;
AtomicGroup model = tropts->model;
AtomicGroup system = selectAtoms(model, topts->selection);
AtomicGroup init_model = createSystem(topts->source_model);
AtomicGroup init = selectAtoms(init_model, topts->source_sel);
AtomicGroup final_model = createSystem(topts->sink_model);
AtomicGroup final = selectAtoms(final_model, topts->sink_sel);
double cutoff = topts->cutoff;
pTraj traj = tropts->trajectory;
bool smoothed_transition = topts->smoothed_transition;
// Check to see if user requested to leave these atoms...
if (!topts->leave_heavy){
system.remove(system.select(BackboneSelector()));
system.remove(system.select(HydrogenSelector()));
init.remove(init.select(BackboneSelector()));
init.remove(init.select(HydrogenSelector()));
final.remove(final.select(BackboneSelector()));
final.remove(final.select(HydrogenSelector()));
if (system.empty() || init.empty() || final.empty()) {
cerr << "Error: The source, sink, or system is empty after post-processing.\n";
cerr << " Check your selections or use --include-heavy=1\n";
exit(-1);
}
}else{
cerr << "WARNING: Leaving backbone and hydrogen atoms!\n";
}
// Split into residues
vector<AtomicGroup> start_residues = init.splitByResidue();
vector<AtomicGroup> final_residues = final.splitByResidue();
vector<AtomicGroup> residues = system.splitByResidue();
if ((start_residues.size() != final_residues.size()) || (residues.size() != final_residues.size())) {
cerr << boost::format("Error: The trajectory has %d residues, the source has %d residues, and sink has %d residues.\n")
% residues.size()
% start_residues.size()
% final_residues.size();
cerr << "\tThe source and sink selections must have the same number of residues.\n";
exit(-1);
}
double cut2 = cutoff*cutoff;
string timeseries_outfile = topts->timeseries;
ofstream ofs;
if (!timeseries_outfile.empty()){
ofs.open(timeseries_outfile.c_str());
if (ofs.fail()) {
cerr << "Error- failed to open '" << timeseries_outfile << "' for output.\n";
exit(-11);
}
ofs << "# " << hdr << endl;
ofs << "# Changed contacts list:\n";
ofs << "# ------------------------------\n";
}
//######################################################################
//### Build the master list of unique contacts
//######################################################################
vector<AtomicGroup> reslist;
vector<pair<uint, uint> > formed_connection_list;
vector<pair<uint, uint> > broken_connection_list;
for (uint j = 0; j < residues.size()-1; ++j) {
uint jk;
bool any_connection_flag = false;
GCoord cj = start_residues[j].centerOfMass();
for (uint i = j+1; i < residues.size(); ++i) {
GCoord ci = start_residues[i].centerOfMass();
GCoord start_diff = cj - ci;
// If formed in starting structure...
if (start_diff.length2() <= cut2){
GCoord fci = final_residues[i].centerOfMass();
GCoord fcj = final_residues[j].centerOfMass();
GCoord final_diff = fcj - fci;
// ...and if broken in ending structure
if (final_diff.length2() > cut2){
// Check if residue[j]'s first connection
// (we only want [j] listed once)
if (!any_connection_flag){
jk = reslist.size();
reslist.push_back(residues[j]);
any_connection_flag = true;
}
uint ik = reslist.size();
reslist.push_back(residues[i]);
pair<uint,uint> conn_ptr(jk, ik);
// Add these to the broken pair list
broken_connection_list.push_back(conn_ptr);
// Document the residues in the broken list
ofs << "# broken: " << final_residues[j].getAtom(0)->resid() << " "
<< final_residues[i].getAtom(0)->resid() << endl;
}
}
// If broken in starting structure...
if (start_diff.length2() > cut2){
GCoord fci = final_residues[i].centerOfMass();
GCoord fcj = final_residues[j].centerOfMass();
GCoord final_diff = fcj - fci;
// ...and if formed in ending structure
if (final_diff.length2() <= cut2){
if (!any_connection_flag){
jk = reslist.size();
reslist.push_back(residues[j]);
any_connection_flag = true;
}
uint ik = reslist.size();
reslist.push_back(residues[i]);
pair<uint,uint> conn_ptr(jk, ik);
// Add to the formed pair master list
formed_connection_list.push_back(conn_ptr);
// Document the residues in the formed list
ofs << "# formed: " << final_residues[j].getAtom(0)->resid() << " "
<< final_residues[i].getAtom(0)->resid() << endl;
}
}
}
}
//######################################################################
//### Set up params for the calculation
//######################################################################
// Tally of the number of contacts for normalization
uint total_formed_contacts = formed_connection_list.size();
uint total_broken_contacts = broken_connection_list.size();
cout << "# Total differences: \n";
cout << "# Contacts broken: " << total_broken_contacts << endl;
cout << "# Contacts formed: " << total_formed_contacts << endl;
cout << "# Frame \t broken \t formed \t total \n";
cout << "#-------------------------------------------\n";
//######################################################################
//### Iterate over trajectory frames
//### Calc the number of unique contacts broken/formed
//######################################################################
int frame = tropts->skip;
while (traj->readFrame()){
traj->updateGroupCoords(system);
double number_broken = 0.0;
double number_formed = 0.0;
// Build a GCoord vector of CoM's
// with indices corresponding to reslist
vector<GCoord> centers;
for (uint gi = 0; gi < reslist.size(); ++gi){
GCoord temp_com = reslist[gi].centerOfMass();
centers.push_back(temp_com);
}
// Do the actual calculation
// For broken list
for (uint i = 0; i < broken_connection_list.size(); ++i){
GCoord first_current = centers[broken_connection_list[i].first];
GCoord second_current = centers[broken_connection_list[i].second];
bool broken = first_current.distance2(second_current) > cut2;
double current_dist = sqrt(first_current.distance2(second_current));
if (smoothed_transition){
double value = 0.5 * tanh(current_dist-cutoff)+0.5;
number_broken += value;
if (!timeseries_outfile.empty())
ofs << value << '\t';
}else{
if (broken)
++number_broken;
if (!timeseries_outfile.empty())
ofs << (broken ? '0' : '1') << '\t';
}
}
// For formed list
for (uint i = 0; i < formed_connection_list.size(); ++i){
GCoord first_current = centers[formed_connection_list[i].first];
GCoord second_current = centers[formed_connection_list[i].second];
bool formed = first_current.distance2(second_current) < cut2;
double current_dist = sqrt(first_current.distance2(second_current));
if (smoothed_transition){
double value = 0.5 * tanh(current_dist-cutoff)+0.5;
number_formed += value;
if (!timeseries_outfile.empty())
ofs << value << '\t';
}else{
if (formed)
++number_formed;
if (!timeseries_outfile.empty())
ofs << (formed ? '1' : '0') << '\t';
}
}
if (!timeseries_outfile.empty())
ofs << endl;
// Format and output the data
float num_transition = (number_broken + number_formed) / (total_broken_contacts + total_formed_contacts);
float percent_broken = number_broken / total_broken_contacts;
float percent_formed = number_formed / total_formed_contacts;
cout << frame << "\t" << percent_broken << "\t" << percent_formed << "\t" << num_transition << endl;
frame++;
}
}
| 15,774
|
C++
|
.cpp
| 359
| 38.130919
| 191
| 0.632269
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,178
|
rmsds.cpp
|
GrossfieldLab_loos/Tools/rmsds.cpp
|
/*
rmsds.cpp
Pair-wise RMSD
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <unistd.h>
#include <boost/thread/thread.hpp>
using namespace std;
using namespace loos;
typedef boost::thread* Thread;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// const int matrix_precision = 2; // Controls precision in output matrix
int verbosity;
// If the estimated cache memory is more than this fraction of physical memory,
// issue a warning to the user to consider turning off the cache
// Note: the total app size may be 20-30% larger than the cache estimate, so
// take that into consideration when setting the warning threshold
const double cache_memory_fraction_warning = 0.66;
long used_memory = 0;
bool report_stats = false;
// @cond TOOLS_INTERNAL
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\n"
"\tCalculate a pair-wise RMSD for a trajectory (or two trajectories)\n"
"DESCRIPTION\n"
"\n"
"\tThis tool calculates the pair-wise RMSD between each structure in a trajectory\n"
"or, alternatively, between each structure in two different trajectories. In the single\n"
"trajectory case, the ith structure is aligned with the jth structure and the RMSD calculated.\n"
"This is stored in a matrix, i.e. R(j, i) = d(S_i, S_j). The block-structure is indicative\n"
"of sets of similar conformations. The presence (or lack thereof) of multiple cross-peaks\n"
"is diagnostic of the sampling quality of a simulation.\n"
"\n"
"\tThe requested subset for each frame is cached in memory for better performance.\n"
"If the memory used by the cache gets too large, your machine may swap and dramatically slow\n"
"down. The tool will try to warn you if this is a possibility. To use less memory, subsample\n"
"the trajectory either by using the --range1 and --range2 options, or use subsetter to pre-process\n"
"the trajectory.\n"
"\n"
"\tThis tool can be run in parallel with multiple threads for performance. The --threads option\n"
"controls how many threads are used. The default is 1 (non-parallel). Setting it to 0 will use\n"
"as many threads as possible. Note that if LOOS was built using a multi-threaded math library,\n"
"then some care should be taken in how many threads are used for this tool, though it is unlikely\n"
"that there will be a conflict.\n"
"\n"
"EXAMPLES\n"
"\n"
"\trmsds model.pdb simulation.dcd >rmsd.asc\n"
"This example uses all alpha-carbons and every frame in the trajectory.\n"
"\n"
"\trmsds --threads=8 model.pdb simulation.dcd >rmsd.asc\n"
"This example uses all alpha-carbons and every frame in the trajectory, run\n"
"in parallel with 8 threads of execution.\n"
"\n"
"\trmsds inactive.pdb inactive.dcd active.pdb active.dcd >rmsd.asc\n"
"This example uses all alpha-carbons and compares the \"inactive\" simulation\n"
"with the \"active\" one.\n"
"\n"
"\trmsds --sel1 'resid <= 100 && name == \"CA\"' model.pdb simulation.dcd >rmsds.asc\n"
"This example calculates the pair-wise RMSD using only the first 100 alpha-carbons\n"
"\n"
"\trmsds --sel1 'resid <= 50 && name == \"CA\"' \\\n"
"\t --sel2 'resid >=20 && resid <= 69 && name == \"CA\"' \\\n"
"\t inactive.pdb inactive.dcd active.pdb active.dcd >rmsd.asc\n"
"This example compares two trajectories, active and inactive, and uses different selections\n"
"for both: the first 50 residues from the inactive and residues 20-69 from the active.\n"
"\n"
"NOTES\n"
"\tWhen using two trajectories, the selections must match both in number of atoms selected\n"
"and in the sequence of atoms (i.e. the first atom in the --sel2 selection is\n"
"matched with the first atom in the --sel2 selection.)\n"
"\n"
"SEE ALSO\n"
"\trmsd2ref\n"
"\n";
return(msg);
}
class ToolOptions : public opts::OptionsPackage {
public:
ToolOptions() { }
void addGeneric(po::options_description& o) {
o.add_options()
("noout,N", po::value<bool>(&noop)->default_value(false), "Do not output the matrix (i.e. only calc pair-wise RMSD stats)")
("threads", po::value<uint>(&nthreads)->default_value(1), "Number of threads to use (0=all available)")
("sel1", po::value<string>(&sel1)->default_value("name == 'CA'"), "Atom selection for first system")
("skip1", po::value<uint>(&skip1)->default_value(0), "Skip n-frames of first trajectory")
("range1", po::value<string>(&range1), "Matlab-style range of frames to use from first trajectory")
("sel2", po::value<string>(&sel2)->default_value("name == 'CA'"), "Atom selection for second system")
("skip2", po::value<uint>(&skip2)->default_value(0), "Skip n-frames of second trajectory")
("range2", po::value<string>(&range2), "Matlab-style range of frames to use from second trajectory")
("stats", po::value<bool>(&stats)->default_value(false), "Show some statistics for matrix")
("precision,p", po::value<uint>(&matrix_precision)->default_value(2), "Write out matrix coefficients with this many digits.");
}
void addHidden(po::options_description& o) {
o.add_options()
("model1", po::value<string>(&model1), "Model-1 Filename")
("traj1", po::value<string>(&traj1), "Traj-1 Filename")
("model2", po::value<string>(&model2), "Model-2 Filename")
("traj2", po::value<string>(&traj2), "Traj-2 Filename");
}
void addPositional(po::positional_options_description& pos) {
pos.add("model1", 1);
pos.add("traj1", 1);
pos.add("model2", 1);
pos.add("traj2", 1);
}
bool check(po::variables_map& m) {
return( ! ( (m.count("model1") && m.count("traj1")) && !(m.count("model2") ^ m.count("traj2"))) );
}
string help() const {
return("model-1 trajectory-1 [model-2 trajectory-2]");
}
string print() const {
ostringstream oss;
oss << boost::format("stats=%d,matrix_precision=%d,noout=%d,nthreads=%d,sel1='%s',skip1=%d,range1='%s',sel2='%s',skip2=%d,range2='%s',model1='%s',traj1='%s',model2='%s',traj2='%s'")
% stats
% matrix_precision
% noop
% nthreads
% matrix_precision
% sel1
% skip1
% range1
% sel2
% skip2
% range2
% model1
% traj1
% model2
% traj2;
return(oss.str());
}
bool stats;
bool noop;
uint skip1, skip2;
uint nthreads;
uint matrix_precision;
string range1, range2;
string model1, traj1, model2, traj2;
string sel1, sel2;
};
typedef vector<double> vecDouble;
typedef vector<vecDouble> vMatrix;
// @endcond TOOLS_INTERNAL
// --------------------------------------------------------------------------------------
// Parcels out work to the compute threads... Work is given to the threads
// one row at a time.
class Master {
public:
Master(const uint nr, const bool tr, const bool b) : _toprow(0), _maxrow(nr), _updatefreq(500), _triangle(tr),
_verbose(b), _start_time(time(0))
{
if (_triangle)
_total = _maxrow*(_maxrow-1) / 2;
else
_total = _maxrow;
}
// Checks whether there are any columns left to work on
// and places the column index into the passed pointer.
bool workAvailable(uint* ip)
{
_mtx.lock();
if (_toprow >= _maxrow) {
_mtx.unlock();
return(false);
}
*ip = _toprow++;
if (_verbose)
if (_toprow % _updatefreq == 0)
updateStatus();
_mtx.unlock();
return(true);
}
void updateStatus() {
time_t dt = elapsedTime();
uint work_done = _triangle ? (_toprow * (_toprow-1) / 2) : (_toprow);
uint work_left = _total - work_done;
uint d = work_left * dt / work_done; // rate = work_done / dt; d = work_left / rate;
uint hrs = d / 3600;
uint remain = d % 3600;
uint mins = remain / 60;
uint secs = remain % 60;
cerr << boost::format("Row %5d /%5d, Elapsed = %5d s, Remaining = %02d:%02d:%02d\n")
% _toprow % _maxrow % dt % hrs % mins % secs;
}
time_t elapsedTime() const
{
return (time(0) - _start_time);
}
private:
uint _toprow, _maxrow;
uint _updatefreq;
bool _triangle;
bool _verbose;
time_t _start_time;
uint _total;
boost::mutex _mtx;
};
/*
Worker thread processes a column of the all-to-all matrix. Gets which
column to work on from the associated Master object.
*/
// Worker for two different trajectories
class DualWorker
{
public:
DualWorker(RealMatrix* R, vMatrix* T1, vMatrix* T2, Master* M) : _R(R), _T1(T1), _T2(T2), _M(M), _maxcol(T2->size()) { }
DualWorker(const DualWorker& w)
{
_R = w._R;
_T1 = w._T1;
_T2 = w._T2;
_M = w._M;
_maxcol = w._maxcol;
}
void calc(const uint i)
{
for (uint j=0; j<_maxcol; ++j) {
double d = loos::alignment::centeredRMSD((*_T1)[i], (*_T2)[j]);
(*_R)(i, j) = d;
}
}
void operator()()
{
uint i;
while (_M->workAvailable(&i))
calc(i);
}
private:
RealMatrix* _R;
vMatrix* _T1;
vMatrix* _T2;
Master* _M;
uint _maxcol;
};
// Worker for self all-to-all
class SingleWorker
{
public:
SingleWorker(RealMatrix* R, vMatrix* T, Master* M) : _R(R), _T(T), _M(M) { }
SingleWorker(const SingleWorker& w)
{
_R = w._R;
_T = w._T;
_M = w._M;
}
void calc(const uint i)
{
for (uint j=0; j<i; ++j) {
double d = loos::alignment::centeredRMSD((*_T)[i], (*_T)[j]);
(*_R)(j, i) = (*_R)(i, j) = d;
}
}
void operator()()
{
uint i;
while (_M->workAvailable(&i))
calc(i);
}
private:
RealMatrix* _R;
vMatrix* _T;
Master* _M;
};
// Top level object/interface. Will create np Worker threads, cloned from the
// one passed into the constructor.
template<class W>
class Threader
{
public:
Threader(W* wrkr, const uint np) :
worker(wrkr),
threads(vector<Thread>(np))
{
for (uint i=0; i<np; ++i) {
W w(*worker);
threads[i] = new boost::thread(w);
}
}
void join()
{
for (uint i=0; i<threads.size(); ++i)
threads[i]->join();
}
~Threader()
{
for (uint i=0; i<threads.size(); ++i)
delete threads[i];
}
W* worker;
vector<Thread> threads;
};
// --------------------------------------------------------------------------------------
void showStatsHalf(const RealMatrix& R) {
uint total = (R.rows() * (R.rows()-1)) / 2;
double avg = 0.0;
double max = 0.0;
for (uint j=1; j<R.rows(); ++j)
for (uint i=0; i<j; ++i) {
avg += R(j, i);
if (R(j, i) > max)
max = R(j, i);
}
avg /= total;
cerr << boost::format("Max rmsd = %.4f, avg rmsd = %.4f\n") % max % avg;
}
void showStatsWhole(const RealMatrix& R) {
uint total = R.rows() * R.cols();
double avg = 0.0;
double max = 0.0;
for (ulong i=0; i<total; ++i) {
avg += R[i];
if (R[i] > max)
max = R[i];
}
avg /= total;
cerr << boost::format("Max rmsd = %.4f, avg rmsd = %.4f\n") % max % avg;
}
void centerTrajectory(alignment::vecMatrix& U) {
for (uint i=0; i<U.size(); ++i)
alignment::centerAtOrigin(U[i]);
}
void checkMemoryUsage(long mem) {
if (!mem)
return;
double used = static_cast<double>(used_memory) / mem;
if (verbosity > 2)
cerr << boost::format("Memory: available=%d GB, estimated used=%.2f MB\n")
% (mem >> 30) % (static_cast<double>(used_memory) / (1lu<<20) );
if (used >= cache_memory_fraction_warning) {
cerr << boost::format("***WARNING***\nThe estimated memory used is %.1f%% (%d MB) of your total memory (%d GB).\n")
% (used * 100.0)
% (used_memory >> 20)
% (mem >> 30);
cerr << "If your machine starts swapping, try subsampling the trajectories\n";
}
}
int main(int argc, char *argv[]) {
string header = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
verbosity = bopts->verbosity;
report_stats = (verbosity || topts->noop);
AtomicGroup model = createSystem(topts->model1);
pTraj traj = createTrajectory(topts->traj1, model);
AtomicGroup subset = selectAtoms(model, topts->sel1);
vector<uint> indices = assignTrajectoryFrames(traj, topts->range1, topts->skip1);
long mem = availableMemory();
uint nthreads = topts->nthreads ? topts->nthreads : boost::thread::hardware_concurrency();
if (verbosity > 1) {
cerr << "Using " << nthreads << " threads\n";
cerr << "Reading trajectory - " << topts->traj1 << endl;
}
vMatrix T = readCoords(subset, traj, indices, verbosity > 1);
used_memory += T.size() * T[0].size() * sizeof(vMatrix::value_type::value_type); // Coords matrix
used_memory += T.size() * T.size() * sizeof(RealMatrix::element_type); // RMSDS matrix
checkMemoryUsage(mem);
centerTrajectory(T);
RealMatrix M;
if (topts->model2.empty()) {
if (verbosity > 1)
cerr << "Calculating RMSD...\n";
M = RealMatrix(T.size(), T.size());
Master master(T.size(), true, verbosity);
SingleWorker worker(&M, &T, &master);
Threader<SingleWorker> threads(&worker, nthreads);
threads.join();
if (verbosity)
master.updateStatus();
if (verbosity || topts->noop || topts->stats)
showStatsHalf(M);
} else {
AtomicGroup model2 = createSystem(topts->model2);
pTraj traj2 = createTrajectory(topts->traj2, model2);
AtomicGroup subset2 = selectAtoms(model2, topts->sel2);
vector<uint> indices2 = assignTrajectoryFrames(traj2, topts->range2, topts->skip2);
if (verbosity > 1)
cerr << "Reading trajectory - " << topts->traj2 << endl;
vMatrix T2 = readCoords(subset2, traj2, indices2, verbosity > 1);
used_memory += T2.size() * T2[0].size() * sizeof(double);
checkMemoryUsage(mem);
centerTrajectory(T2);
if (verbosity > 1)
cerr << "Calculating RMSD...\n";
M = RealMatrix(T.size(), T2.size());
Master master(T.size(), false, verbosity);
DualWorker worker(&M, &T, &T2, &master);
Threader<DualWorker> threads(&worker, nthreads);
threads.join();
if (verbosity)
master.updateStatus();
if (verbosity || topts->noop || topts->stats)
showStatsWhole(M);
}
if (!topts->noop) {
cout << "# " << header << endl;
cout << setprecision(topts->matrix_precision) << M;
}
}
| 15,477
|
C++
|
.cpp
| 423
| 31.962175
| 185
| 0.638539
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,179
|
fixdcd.cpp
|
GrossfieldLab_loos/Tools/fixdcd.cpp
|
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2013, Tod D. Romo, Grossfield Lab
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace loos;
using namespace std;
int scanTrajectory(const char* fname, bool* swabbing)
{
DCD dcd(fname);
*swabbing = !dcd.nativeFormat();
int n = 0;
while (dcd.readFrame())
++n;
if (n != static_cast<int>(dcd.nframes())) {
cout << boost::format("%s claims to have %d frames.\n") % fname % dcd.nframes();
cout << boost::format("--> Scanning found %d frames.\n") % n;
} else
n = -1; // Signal no-update
return(n);
}
void fixDCD(const char* fname)
{
bool swabbing;
int nframes = scanTrajectory(fname, &swabbing);
if (nframes < 0)
return;
fstream file(fname, ios_base::in | ios_base::out);
if (file.fail()) {
cerr << "Error- cannot open " << fname << endl;
exit(-2);
}
if (swabbing)
nframes = swab(nframes);
file.seekp(8);
file.write(reinterpret_cast<char*>(&nframes), sizeof(nframes));
file.seekp(20);
file.write(reinterpret_cast<char*>(&nframes), sizeof(nframes));
}
int main(int argc, char *argv[])
{
if (argc < 2) {
cerr << "Usage- fixdcd dcdfile [dcdfile ...]\n";
exit(-1);
}
DCD::setSuppression(true);
for (int k=1; k<argc; ++k)
fixDCD(argv[k]);
}
| 2,175
|
C++
|
.cpp
| 61
| 29.967213
| 88
| 0.666175
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,180
|
rad-gyr.cpp
|
GrossfieldLab_loos/Tools/rad-gyr.cpp
|
/*
Compute the distribution or timeseries of radii of gyration for a selection of
atoms.
Alan Grossfield
Grossfield Lab
Department of Biochemistry and Biophysics
University of Rochester Medical School
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2020, Louis Smith
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <loos.hpp>
using namespace std;
using namespace loos;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
const string fullHelpMessage =
// clang-format off
"SYNOPSIS \n"
" \n"
"Read a trajectory and return a histogram of the radius of gyration of a \n"
"selection. \n"
" \n"
"DESCRIPTION \n"
" \n"
"This tool computes the radius of gyration for a selection of atoms for each \n"
"frame of a provided multi-trajectory. By default this selection is treated as \n"
"one group, but if --by-molecule is thrown then the selection will be split by \n"
"connectivity. The skip, stride, and range options operate on the multi-\n"
"trajectory as they would for other LOOS tools. The time-series option specifies\n"
" a file to write a timeseries of the radius of gyrations to. If none is \n"
"specified then no time-series is written. The num-bins, min-bin, and max-bin \n"
"options determine the extent and bin-width of the histogram, which is written \n"
"to stdout. The histogram contains both the probability per bin, and the \n"
"cumulative probability. \n"
" \n"
"EXAMPLE \n"
" \n"
"rad-gyr -k 100 -n 20 -m 5 -M 25 --by-molecule model.pdb traj1.dcd traj2.dcd \n"
"traj3.dcd \n"
" \n"
"This will concatenate traj1, traj2, and traj3 into one virtual trajectory, skip\n"
" the first 100 frames of each, and then histogram the radius of gyration of all\n"
" the atoms in each of the molecules in the model provided with the \n"
"trajectories, computing their radii of gyration and summing over them. Note \n"
"that this would be nonsensical if the molecules in the model were not multiple \n"
"copies of the same molecule, since all such Rgyr will be collated into one \n"
"histogram at the end. Using selection to pick a subsystem of interest makes \n"
"more sense in the context of most analyses of a solute. \n"
" \n"
"POTENTIAL COMPLICATIONS \n"
" \n"
"Gromacs users should be aware that this code assumes the system's\n"
"molecules are not split across the periodic boundary. If that's your\n"
"use-case, apply different reimaging first before using this tool.\n"
"LOOS provides facility to solve these problems in 'merge-traj' and \n"
"subsetter.\n"
"\n"
"The by-molecule flag applies splitByMolecule to the whole system, which is then\n"
"subset on a per molecule basis by the selection string provided. This means \n"
"that if you had a three chain protein and you selected 'name == \"CA\"', you'd \n"
"get three different groups of alpha carbons, each of which would be used to \n"
"calculate a separate radius of gyration. Most of the time this is probably what\n"
" you want, but if you wanted to use your selection to break up whatever is in \n"
"your system into fragments, then track each of those fragments separately, \n"
"throw the --by-fragment flag instead. Doing so flips the order in which the \n"
"selection string and the call to splitByMolecule are applied (in the by-\n"
"fragments case the selection is performed first, then the splitting by \n"
"connectivity) to the model provided. Thus if you provided a discontinuous \n"
"selection like the above for alpha carbons, then you'd be tracking the radii of\n"
" gyration of all those discontinuous fragments as though they were separate \n"
"molecules. \n"
"\n"
"It's also worth saying that this tool requires connectivity if either of the \n"
"splitting flags are thrown. You could use PyLOOS to add connectivity to your \n"
"system by reading it in, adding connectivity (for example, with findBonds) then\n"
" writing it back out again. Caution is advised, though; if you can use a model \n"
"that has connectivity from a better source, like a force field for example (for\n"
" example, prmtops and psfs both have this) you should prefer that to distance-\n"
"based workarounds like findBonds. \n"
" \n"
"Finally, if you are using one of the molecule splittings, know that you will be\n"
" accumulating all the various radii of gyration your selection is tracking for \n"
"each molecule it found in the histogram the tool reports. This, again, is \n"
"probably what you want. However, it could produce subtly screwy results if, for\n"
" example, you were tracking a molecule you did not believe you were tracking, \n"
"or if a molecule you thought you were tracking was actually being treated as \n"
"two molecules. As with all LOOS tools, it's a good idea to use model-select and\n"
" the pdb option to visualize what atoms any selection string under \n"
"consideration tracks before applying a tool that will give necessarily opaque \n"
"output from a goofed up selection. This warning is included here because it \n"
"might be particularly hard to spot an erroneous selection in a histogram of a \n"
"complicated system, like all the lipids in a membrane. \n"
;
//clang-format on
class ToolOptions : public opts::OptionsPackage {
public:
ToolOptions() {}
// clang-format off
void addGeneric(po::options_description& o) {
o.add_options()
("timeseries,t", po::value<string>(×eries)->default_value(""),
"Write Rgyr per-frame to file name provided.")
("num-bins,n", po::value<int>(&num_bins)->default_value(50),
"Number of bins to use for histogramming.")
("min-dist,m", po::value<double>(&min_dist)->default_value(0),
"Minimum value for the histogram bins.")
("max-dist,M", po::value<double>(&max_dist)->default_value(50),
"Maximum value for the histogram bins.")
("by-molecule", po::bool_switch(&by_molecule)->default_value(false),
"Split 'selection' by connectivity of 'model'.")
("by-fragment", po::bool_switch(&by_molecule)->default_value(false),
"Split 'selection' by its own connectivity.")
;
}
// clang-format on
string print() const {
ostringstream oss;
oss << boost::format("timeseries=%s,min_dist=%s,max_dist=%s,by_molecule=%b,"
"by_fragment=%b,num_bins=%d") %
timeseries % min_dist % max_dist % by_molecule % by_fragment %
num_bins;
return (oss.str());
}
bool postConditions(po::variables_map &map) {
if(by_molecule && by_fragment){
cerr << "ERROR: --by-molecule and --by-fragment flags are mutually exclusive.\n";
return(false);
} else
return(true);
}
string timeseries;
double min_dist;
double max_dist;
bool by_molecule;
bool by_fragment;
int num_bins;
};
// Do the work of recording, either in the case where a TS is requested,
inline void histogram_rgyr(vector<greal> &hist, const greal rgyr,
const greal min_dist, const greal max_dist,
const greal bin_width, int &count,
ofstream &outfile) {
if ((rgyr >= min_dist) && (rgyr < max_dist)) {
hist[int((rgyr - min_dist) / bin_width)]++;
count++;
}
}
inline void histogram_molecules_rgyr(vector<greal> &hist,
vector<AtomicGroup> &molecules,
const greal min_dist, const greal max_dist,
const greal bin_width, int &count,
const int frame, ofstream &outfile) {
for (auto molecule : molecules) {
histogram_rgyr(hist, molecule.radiusOfGyration(), min_dist, max_dist,
bin_width, count, outfile);
}
}
// or in the case when not.
inline void ts_hist_rgyr(vector<greal> &hist, vector<AtomicGroup> &molecules,
const greal min_dist, const greal max_dist,
const greal bin_width, int &count, const int frame,
ofstream &outfile) {
greal rgyr;
outfile << frame;
for (auto molecule : molecules) {
rgyr = molecule.radiusOfGyration();
outfile << "\t" << rgyr;
histogram_rgyr(hist, rgyr, min_dist, max_dist, bin_width, count, outfile);
}
outfile << "\n";
}
int main(int argc, char *argv[]) {
string header = invocationHeader(argc, argv);
opts::BasicOptions *bopts = new opts::BasicOptions(fullHelpMessage);
opts::BasicSelection *sopts = new opts::BasicSelection("all");
opts::MultiTrajOptions *mtopts = new opts::MultiTrajOptions;
ToolOptions *topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(sopts).add(mtopts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
// Write histogram results to stdout. Write timeseries, if asked for, to file
cout << "# " << header << "\n";
ofstream tsf(topts->timeseries);
// make a function pointer with a signature matching the
void (*frameOperator)(vector<greal> & hist, vector<AtomicGroup> & molecules,
const greal min_dist, const greal max_dist,
const greal bin_width, int &count, const int frame,
ofstream &outfile);
// establish system, and molecular subsystems
vector<AtomicGroup> molecules;
if (topts->by_molecule)
molecules = mtopts->model.splitByMolecule(sopts->selection);
else if(topts->by_fragment)
molecules = selectAtoms(mtopts->model, sopts->selection).splitByMolecule();
else
molecules.push_back(selectAtoms(mtopts->model, sopts->selection));
// pick which operation to perform per frame using function pointer
if (topts->timeseries.empty())
frameOperator = histogram_molecules_rgyr;
else {
tsf << "# " << header << "\n"
<< "# frame";
// Label each column with the starting and ending index for the 'molecule'
// as a stand in for the case where molecule's chainids are inaccurate.
for (auto molecule : molecules) {
int first = molecule[0]->index();
int last = (*(molecule.end() - 1))->index();
tsf << "\tatoms" << first << "-" << last;
}
tsf << "\n";
frameOperator = ts_hist_rgyr;
}
// prepare for trajectory loop
// counter for number of molecules in histogram bounds
int count = 0;
const int num_bins = topts->num_bins;
const greal min_dist = topts->min_dist;
const greal max_dist = topts->max_dist;
const greal bin_width = (max_dist - min_dist) / num_bins;
// define and zero histogram
vector<greal> hist(num_bins, 0.0);
while (mtopts->trajectory->readFrame()) {
mtopts->trajectory->updateGroupCoords(mtopts->model);
// call fxn pointer to accumulate histogram and optionally write timeseries
(*frameOperator)(hist, molecules, min_dist, max_dist, bin_width, count,
mtopts->trajectory->currentFrame(), tsf);
}
// Write the histogram to stdout
cout << "# Rgyr\tProb\tCum" << endl;
greal cum = 0.0;
for (int i = 0; i < num_bins; i++) {
greal d = bin_width * (i + 0.5) + min_dist;
greal prob = hist[i] / count;
cum += prob;
cout << d << "\t" << prob << "\t" << cum << endl;
}
tsf.close();
}
| 11,880
|
C++
|
.cpp
| 252
| 42.43254
| 87
| 0.698318
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,181
|
model-select.cpp
|
GrossfieldLab_loos/Tools/model-select.cpp
|
/*
model-select.cpp
Takes a model (PDB, PSF, etc) and a selection string. Parses the selection, then
applies it to the PDB and writes the output to stdout. This tool is
used maily for checking your selection strings to make sure you're
actually selecting what you intend to select...
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
enum SplitMode { NONE, RESIDUE, MOLECULE, SEGID, NAME };
SplitMode mode;
bool nobonds;
bool deduce;
bool pdb_output;
string model_name;
string hdr;
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tRaw dump of a model subset in LOOS\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool is useful for diagnosing problems with selections and how\n"
"LOOS reads model files. It will write out a pseudo-XML representation\n"
"of the information it has stored about the selected subset.\n"
"\n"
"EXAMPLES\n"
"\n"
"\tmodel-select model.pdb >model.xml\n"
"This example writes out ALL atoms\n"
"\n"
"\tmodel-select --selection 'name == \"CA\"' model.pdb >model-ca.xml\n"
"This example only writes out alpha-carbons.\n"
"\n"
"\tmodel-select --selection 'resid <= 100' --splitby molecule >model-mols.xml\n"
"This example splits the first 100 residues into molecules as determined\n"
"by the sytem's connectivity. Each group is written out separately.\n"
"\n";
return(msg);
}
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
std::string modeltypes = "Model types:\n" + availableSystemFileTypes();
o.add_options()
("splitby", po::value<string>(&mode_string), "Split by molecule, residue, segid, name")
("deduce", po::value<bool>(&deduce)->default_value(true), "Deduce atomic number from mass")
("pdb", po::value<bool>(&pdb_output)->default_value(false), "Write out PDBs")
("nobonds", po::value<bool>(&nobonds)->default_value(false), "Do not include connectivity")
("modeltype", po::value<std::string>(&modeltype), modeltypes.c_str());
}
void addHidden(po::options_description& o) {
o.add_options()
("model", po::value<string>(&model_name), "model");
}
void addPositional(po::positional_options_description& p) {
p.add("model", 1);
}
bool check(po::variables_map& map) {
if (!map.count("model"))
return(true);
return(false);
}
bool postConditions(po::variables_map& map) {
mode = NONE;
if (!mode_string.empty()) {
if (mode_string == "molecule")
mode = MOLECULE;
else if (mode_string == "residue")
mode = RESIDUE;
else if (mode_string == "segid")
mode = SEGID;
else if (mode_string == "name")
mode = NAME;
else
return(false);
}
return(true);
}
string help() const { return("model"); }
string print() const {
ostringstream oss;
oss << boost::format("mode='%s', deduce=%d, model='%s', pdb=%d, nobonds=%d")
% mode_string % deduce % model_name % pdb_output % nobonds;
return(oss.str());
}
string modeltype;
private:
string mode_string;
};
void dumpChunks(const vector<AtomicGroup>& chunks) {
for (uint i=0; i<chunks.size(); ++i) {
if (pdb_output) {
PDB pdb = PDB::fromAtomicGroup(chunks[i]);
pdb.remarks().add(hdr);
cout << pdb;
} else {
cout << "<!-- *** Group #" << i << " -->\n";
cout << chunks[i] << endl << endl;
}
}
}
int main(int argc, char *argv[]) {
hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::BasicSelection* sopts = new opts::BasicSelection;
ToolOptions* topts = new ToolOptions();
opts::AggregateOptions options;
options.add(bopts).add(sopts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
AtomicGroup model;
if (topts->modeltype.empty())
model = createSystem(model_name);
else
model = createSystem(model_name, topts->modeltype);
if (nobonds)
model.clearBonds();
AtomicGroup subset = selectAtoms(model, sopts->selection);
if (deduce)
subset.deduceAtomicNumberFromMass();
cerr << "You selected " << subset.size() << " atoms out of " << model.size() << endl;
if (!pdb_output)
cout << "<!-- " << hdr << " -->\n";
vector<AtomicGroup> chunks;
map<string, AtomicGroup> named_chunks;
switch(mode) {
case MOLECULE:
chunks = subset.splitByMolecule();
dumpChunks(chunks);
break;
case RESIDUE:
chunks = subset.splitByResidue();
dumpChunks(chunks);
break;
case SEGID:
chunks = subset.splitByUniqueSegid();
dumpChunks(chunks);
break;
case NAME:
named_chunks = subset.splitByName();
for (map<string, AtomicGroup>::const_iterator i = named_chunks.begin(); i != named_chunks.end(); ++i) {
if (pdb_output) {
PDB pdb = PDB::fromAtomicGroup(i->second);
pdb.remarks().add(hdr);
pdb.remarks().add(i->first);
cout << pdb;
} else {
cout << "<!-- Group for name '" << i->first << "' -->\n";
cout << i->second << endl << endl;;
}
}
break;
case NONE:
if (pdb_output) {
PDB pdb = PDB::fromAtomicGroup(subset);
pdb.remarks().add(hdr);
cout << pdb;
} else
cout << subset << endl;
break;
}
}
| 6,235
|
C++
|
.cpp
| 184
| 29.548913
| 107
| 0.666
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,182
|
exposure.cpp
|
GrossfieldLab_loos/Tools/exposure.cpp
|
/*
exposure
(c) 2009 Tod D. Romo, Grossfield Lab
Department of Biochemistry
University of Rochster School of Medicine and Dentistry
Computes the degree of exposure of a set of selections over time.
The exposure is defined as the average density of a probe selection
within a spherical shell about each target atom.
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008-2009, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
typedef vector<AtomicGroup> vGroup;
vector<uint> indices;
double inner_cutoff, outer_cutoff;
string probe_selection;
vector<string> target_selections;
bool symmetry = false;
int verbosity = 0;
bool normalize = true;
bool average = true;
string fullHelpMessage(void) {
string s =
"\n"
"SYNOPSIS\n"
"Calculate the density of various target selections about a probe selection\n"
"\n"
"DESCRIPTION\n"
"\tFor a given probe selection of atoms, exposure will calculate the count of target\n"
"atoms within a given shell (radius) of any probe atom. The output can be normalized by\n"
"the probe volume (i.e. a density), and can be averaged over all probe atoms.\n"
"\n"
"EXAMPLES\n"
"\n"
"\texposure simulation.pdb simulation.dcd 'segid == \"PROT\"'\n"
"Computes the solvent exposure for the molecule with segid \"PROT\".\n"
"\n"
"\texposure -P 'segid =~ \"^L\"' simulation.pdb simulation.dcd \\\n"
"\t 'resname == \"HEXO\" && segid == \"P1\"'\n"
"Computes the exposure of the residue HEXO with segid P1 to a\n"
"lipid membrane (assuming the lipids have segids begining with \"L\".\n"
"This could be used to determine the degree of insertion of the\n"
"residue into the membrane, for example.\n"
"\n"
"\texposure -R1 -P 'segid =~ \"^L\"' simulation.pdb simulation.dcd 'segid == \"P1\"'\n"
"Similar to above, except that it averages over the entire peptide\n"
"with segid P1 and considers periodic boundaries when determining\n"
"which atoms are within the probe shell.\n"
"\n"
"\texposure -R1 -I2 -P 'segid != \"BULK\"' simulation.pdb simulation.dcd 'segid == \"P1\"'\n"
"Computes the degree to which P1 is buried, i.e. the density of non-\n"
"water atoms about P1, excluding any atom that is within 2 A of an atom\n"
"in P1. Also considers periodic boundaries when computing distances.\n"
"\n"
"\texposure -P '!(segid == \"BULK\" || segid == \"P1\")' \\\n"
"\t simulation.pdb simulation.dcd 'segid == \"P1\"'\n"
"Computes the degree to which P1 is buried, ignoring the atoms from P1.\n"
"\n"
"NOTES\n"
"Exposure calculations can be quite lengthy for large systems/trajectories.\n"
"you may want to add '&& !hydrogen' to your selections if speed is an issue.\n"
"\n"
"This tool has been largely replaced by contact-time (which is faster)\n"
"\n"
"SEE ALSO\n"
"\tcontact-time\n";
return(s);
}
// @cond TOOLS_INTERNAL
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("normalize,N", po::value<bool>(&normalize)->default_value(true), "Normalize by volume (i.e. output is density)")
("average,A", po::value<bool>(&average)->default_value(true), "Average contacts over selection")
("probe,P", po::value<string>(&probe_selection)->default_value("segid == 'BULK' && name == 'OH2'"), "Subset to compute exposure against")
("inner,I", po::value<double>(&inner_cutoff)->default_value(0.0), "Inner cutoff (ignore atoms closer than this)")
("outer,O", po::value<double>(&outer_cutoff)->default_value(5.0), "Outer cutoff (ignore atoms further away than this)")
("reimage,R", po::value<bool>(&symmetry)->default_value(true), "Consider symmetry when computing distances");
}
string print() const {
ostringstream oss;
oss << boost::format("normalize=%d, average=%d, probe='%s', inner=%f, outer=%f, reimage=%d")
% normalize
% average
% probe_selection
% inner_cutoff
% outer_cutoff
% symmetry;
return(oss.str());
}
};
// @endcond
double density(const AtomicGroup& target, const AtomicGroup& probe, const double inner_radius, const double outer_radius) {
double or2 = outer_radius * outer_radius;
double ir2 = inner_radius * inner_radius;
double vol_out = 4.0/3.0 * M_PI * or2 * outer_radius;
double vol_inn = 4.0/3.0 * M_PI * ir2 * inner_radius;
double vol = vol_out - vol_inn;
GCoord box = target.periodicBox();
ulong contacts = 0;
for (AtomicGroup::const_iterator j = target.begin(); j != target.end(); ++j) {
GCoord v = (*j)->coords();
ulong probed = 0;
for (AtomicGroup::const_iterator i = probe.begin(); i != probe.end(); ++i) {
GCoord u = (*i)->coords();
double d = symmetry ? v.distance2(u, box) : v.distance2(u);
if (d >= ir2 && d <= or2) {
++probed;
}
}
contacts += probed;
}
double dens = static_cast<double>(contacts);
if (average)
dens /= target.size();
if (normalize)
dens /= vol;
return(dens);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::TrajectoryWithFrameIndices* tropts = new opts::TrajectoryWithFrameIndices;
ToolOptions* topts = new ToolOptions;
opts::RequiredArguments* ropts = new opts::RequiredArguments;
ropts->addVariableArguments("target", "target-selection");
opts::AggregateOptions options;
options.add(bopts).add(tropts).add(topts).add(ropts);
if (!options.parse(argc, argv))
exit(-1);
verbosity = bopts->verbosity;
AtomicGroup model = tropts->model;
pTraj traj = tropts->trajectory;
indices = tropts->frameList();
target_selections = ropts->variableValues("target");
AtomicGroup probe = selectAtoms(model, probe_selection);
vGroup targets;
for (vector<string>::iterator i = target_selections.begin(); i != target_selections.end(); ++i)
targets.push_back(selectAtoms(model, *i));
cout << "# " << hdr << endl;
cout << "# frame ";
for (uint i=0; i < target_selections.size(); ++i)
cout << "Density_" << i << "\t";
cout << endl;
ulong t = 0;
PercentProgressWithTime watcher;
ProgressCounter<PercentTrigger, EstimatingCounter> slayer(PercentTrigger(0.1), EstimatingCounter(indices.size()));
slayer.attach(&watcher);
if (verbosity)
slayer.start();
for (vector<uint>::iterator frame = indices.begin(); frame != indices.end(); ++frame) {
traj->readFrame(*frame);
traj->updateGroupCoords(model);
if (symmetry && !model.isPeriodic()) {
cerr << "ERROR - the trajectory must be periodic to use --reimage\n";
exit(-1);
}
cout << boost::format("%8d") % t;
for (vGroup::const_iterator i = targets.begin(); i != targets.end(); ++i) {
double d;
d = density(*i, probe, inner_cutoff, outer_cutoff);
cout << boost::format(" %8.6f") % d;
}
cout << endl;
++t;
if (verbosity)
slayer.update();
}
if (verbosity)
slayer.finish();
}
| 7,985
|
C++
|
.cpp
| 190
| 37.742105
| 143
| 0.68276
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,183
|
verap.cpp
|
GrossfieldLab_loos/Tools/verap.cpp
|
/*
Vertical (along Z) area profile using radius of gyration or max radius
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2016, Tod D. Romo, Grossfield Lab,
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace loos;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// @cond TOOL_INTERNAL
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"Compute vertical area profile using radius of gyration or max radius\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool computes a vertical area profile by binning a structure along\n"
"the Z-axis, then for each bin, it computes either a radius of gyration or\n"
"a maximum radius. The profile is the average radius for each bin over the\n"
"trajectory. A time-series of the vertical area profile may be written out\n"
"if the --tseries option is used.\n"
"\n"
"EXAMPLES\n"
"\n"
"\tverap -- model.pdb traj.dcd -20 20 20 >profile.asc\n"
"This computes a profile for model using the default selection (backbone)\n"
"with the structure binned from -20 to 20 angstroms using 20 bins.\n"
"\n"
"\tverap --selection 'name == \"CA\"' -- model.pdb traj.dcd -20 20 20 >profile.asc\n"
"This is the same as above, but only alpha-carbons are used rather than\n"
"backbone atoms.\n"
"\n"
"\tverap --tseries time-evolution.asc -- model.pdb traj.dcd -20 20 20 >profile.asc\n"
"Compute an area profile from -20 to 20 with 20 bins using backbone atoms.\n"
"Writes the time-series as a matrix (time is along X, bin-position along Y, and\n"
"the radius is the cell value (color).\n"
"\n"
"NOTES\n"
"\n"
"\tTo use negative numbers for zmin or zmax, place '--' ahead of them to turn off option\n"
"processing.\n"
"\n"
"SEE ALSO\n"
"\tarea_profile.py\n"
"\n";
return(msg);
}
class ToolOptions : public opts::OptionsPackage {
public:
void addGeneric(po::options_description& o) {
o.add_options()
("mode", po::value<string>(&mode_selection)->default_value("rgyr"), "Calculation type (rgyr, maxr)")
("tseries", po::value<string>(×eries_filename), "Output time series to this file");
}
void addHidden(po::options_description& o) {
o.add_options()
("zmin", po::value<double>(&zmin), "Min position along Z")
("zmax", po::value<double>(&zmax), "Max position along Z")
("nbins", po::value<uint>(&nbins), "Number of bins along Z");
}
void addPositional(po::positional_options_description& o) {
o.add("zmin", 1);
o.add("zmax", 1);
o.add("nbins", 1);
}
bool check(po::variables_map& vm) {
return(! (vm.count("zmin") && vm.count("zmax") && vm.count("nbins")) );
}
bool postConditions(po::variables_map& vm)
{
boost::algorithm::to_lower(mode_selection);
if (mode_selection == "rgyr")
rgyr_mode = true;
else if (mode_selection == "maxr")
rgyr_mode = false;
else {
cerr << "Error- mode must be one of: rgyr, maxr\n";
return(false);
}
return(true);
}
string help() const {
return("zmin zmax nbins");
}
string print() const {
ostringstream oss;
oss << boost::format("mode='%s',tseries='%s',zmin=%f,zmax=%f,nbins=%u")
% mode_selection
% timeseries_filename
% zmin
% zmax
% nbins;
return(oss.str());
}
string mode_selection, timeseries_filename;
bool rgyr_mode;
double zmin, zmax;
uint nbins;
};
typedef vector<AtomicGroup> Slices;
// @endcond
double zmin, zmax, delta;
ulong binStructure(const AtomicGroup& structure, Slices& slices) {
ulong oob = 0;
for (AtomicGroup::const_iterator a = structure.begin(); a != structure.end(); ++a) {
double z = (*a)->coords().z();
int bin = (z - zmin) * delta;
if (bin < 0 || bin >= slices.size())
++oob;
else {
pAtom b(*a);
b->coords().z(0.0);
slices[bin].append(b);
}
}
return(oob);
}
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::BasicSelection* sopts = new opts::BasicSelection("backbone");
opts::TrajectoryWithFrameIndices* tropts = new opts::TrajectoryWithFrameIndices;
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(sopts).add(tropts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
AtomicGroup model = tropts->model;
AtomicGroup subset = selectAtoms(tropts->model, sopts->selection);
zmax = topts->zmax;
zmin = topts->zmin;
uint nbins = topts->nbins;
delta = nbins / (zmax - zmin);
vector<uint> frames = tropts->frameList();
uint n = frames.size();
RealMatrix M(nbins, n);
uint col = 0;
ulong out_of_bounds = 0;
vector<double> avgs(nbins, 0.0);
for (uint i=0; i<frames.size(); ++i) {
tropts->trajectory->readFrame(frames[i]);
tropts->trajectory->updateGroupCoords(subset);
Slices slices(nbins);
out_of_bounds += binStructure(subset, slices);
for (uint j=0; j<nbins; ++j) {
double d = 0.0;
if (! slices[j].empty())
d = topts->rgyr_mode ? slices[j].radiusOfGyration() : slices[j].radius();
avgs[j] += d;
M(j, col) = d;
}
++col;
}
out_of_bounds /= n;
for (uint i=0; i<nbins; ++i)
avgs[i] /= n;
vector<double> devs(nbins, 0.0);
for (uint i=0; i<n; ++i)
for (uint j=0; j<nbins; ++j) {
double d = M(j, i) - avgs[j];
devs[j] += d*d;
}
for (uint j=0; j<nbins; ++j)
devs[j] = sqrt(devs[j]/(n-1));
if (! topts->timeseries_filename.empty())
writeAsciiMatrix(topts->timeseries_filename, M, hdr);
cout << "# " << hdr << endl;
cout << "# out of bounds = " << out_of_bounds << endl;
cout << "# bin\tz\tavg\tstd\n";
for (uint j=0; j<nbins; ++j) {
double z = (j+0.5) * (zmax - zmin) / nbins + zmin;
cout << boost::format("%d\t%f\t%f\t%f\n")
% j
% z
% avgs[j]
% devs[j];
}
}
| 6,863
|
C++
|
.cpp
| 194
| 30.814433
| 106
| 0.652696
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,184
|
rms-overlap.cpp
|
GrossfieldLab_loos/Tools/rms-overlap.cpp
|
/*
trans-rmsd.cpp
RMSDS between two sets of multiple trajectories
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008,2016 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <unistd.h>
#include <boost/tuple/tuple.hpp>
#include <boost/thread/thread.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace loos;
typedef boost::thread* Thread;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// const int matrix_precision = 2; // Controls precision in output matrix
int verbosity;
// If the estimated cache memory is more than this fraction of physical memory,
// issue a warning to the user to consider turning off the cache
// Note: the total app size may be 20-30% larger than the cache estimate, so
// take that into consideration when setting the warning threshold
const double cache_memory_fraction_warning = 0.66;
long used_memory = 0;
bool report_stats = false;
// @cond TOOLS_INTERNAL
string fullHelpMessage(void) {
string msg =
"SYNOPSIS \n"
" \n"
"Calculate the RMSD between all pairs of frames from two different sets of \n"
"trajectories. \n"
" \n"
"DESCRIPTION \n"
" \n"
"This tool calculates the pair-wise RMSD between each frame pair from two sets \n"
"of multi-trajectories. The jth structure from set B and the ith structure from \n"
"set A are aligned, then the RMSD is calculated. This is stored in a matrix, \n"
"i.e. R(j, i) = d(S_i, S_j). The block-structure is indicative of sets of \n"
"similar conformations. The matrix is not diagonal unless one or more of the \n"
"trajectories in set A matches one or more of the trajectories in set B (in \n"
"which case that section of the outputted matrix will match what other all-to-\n"
"all rmsd tools would return for that trajectory or trajectories alone). The \n"
"presence (or lack thereof) of multiple cross-peaks is diagnostic of the \n"
"sampling quality of a simulation. Cross-peaks between sub-blocks indicates \n"
"similar conformations in multiple trajectories. This tool is particularly \n"
"useful for comparing trajectories representing the same system at different \n"
"positions along a reaction coordinate. \n"
" \n"
"The requested subset for each frame is cached in memory for better performance.\n"
" If the memory used by the cache gets too large, your machine may swap and \n"
"dramatically slowdown. The tool will try to warn you if this is a possibility.\n"
" To use less memory, subsample the trajectory by using --skip or --stride, or \n"
"use subsetter to pre-process the trajectory. Be wary of writing selection \n"
"strings that could conceivably include many atoms (such as solvent atoms) for a\n"
" trajectory, as in addition to being expensive it will also produce confusing \n"
"and incoherent results. \n"
" \n"
"If subsetter is used to pre-process trajectories to a subset of atoms that \n"
"match over trajectories originally created with different systems, they can \n"
"then be analyzed for similarities in that subset using this tool with some \n"
"additional ease, since trajectories of one time can be kept in set A and \n"
"trajectories of the other type can be kept in set B. Expanding this to more \n"
"types can be done pairwise, although there is some point where the \n"
"combinatorics and the postprocessing requirements may make this not worth it. \n"
" \n"
"This tool can be run in parallel with multiple threads for performance. The \n"
"--threads option controls how many threads are used. The default is 1 (non-\n"
"parallel). Setting it to 0 will use as many threads as possible. Note that if\n"
" LOOS was built using a multi-threaded math library,then some care should be \n"
"taken in how many threads are used for this tool, though it is unlikely that \n"
"there will be a conflict. \n"
" \n"
"This tool can compute some basic statistics about the matrix produced, and can \n"
"also be asked not to return it, for convenience in certain situations (they can\n"
" be very large if comparisons are being made between many trajectories and/or \n"
"many frames). If stats are requested but no cutoff is give, then the program \n"
"calculates the maximum distance between any two frames, as well as the average.\n"
" If a cutoff is given, then the maximum, average, and variance are reported. \n"
"The number of frames below the given cutoff is also reported, along with a \n"
"total number of frames compared (so that one might calculate a 'fractional \n"
"overlap' using these values). \n"
" \n"
"EXAMPLES \n"
" \n"
"rms-overlap --set-A sysA.sim1.dcd sysA.sim2.dcd --set-B sysB.sim3.dcd \\\n"
"sysB.sim4.dcd model.pdb > rmsd.asc \n"
" \n"
"This example uses all backbone heavy atoms and every frame from each trajectory\n"
" in set A to compare to every frame in set B. \n"
" \n"
"rms-overlap --threads=8 --set-A sysA.sim1.dcd sysA.sim2.dcd --set-B \\\n"
"sysB.sim3.dcd sysB.sim4.dcd model.pdb > rmsd.asc \n"
" \n"
"This example uses all backbone heavy atoms and every frame in the trajectories,\n"
" run in parallel with 8 threads of execution. \n"
" \n"
"rms-overlap --selection backbone --skip=50 --stride=10 --set-A sysA.sim1.dcd \\\n"
"sysA.sim2.dcd --set-B sysB.sim3.dcd sysB.sim4.dcd model.pdb > rmsd.asc \n"
"This example uses the backbone atoms, and skips the first 50 frames from each \n"
"trajectory,and only takes every 10th subsequent frame from each trajectory. \n"
" \n"
"rms-overlap -c 2.5 -N 1 -A sysA.sim1.dcd sysA.sim2.dcd sysA.sim3.dcd -B \\\n"
"sysB.sim1.dcd sysB.sim2.dcd model.pdb > stats.out \n"
" \n"
"This example will compute the RMSDs between all frames in set A and all frames \n"
"in set B, but will not write the matrix out to stdout. It will calculate the \n"
"statistics described in the cutoff section above, then write them to stdout \n"
"where they are redirected to stats.out. \n"
" \n"
" \n"
" \n"
"SEE ALSO \n"
" \n"
"rmsds, rmsd2ref \n"
" \n"
"Usage- rms-overlap [options] model \n"
;
return(msg);
}
class ToolOptions : public opts::OptionsPackage {
public:
ToolOptions() { }
void addGeneric(po::options_description& o) {
std::string modeltypes = "Model types:\n" + availableSystemFileTypes();
std::string trajtypes = "Trajectory types:\n" + availableTrajectoryFileTypes();
o.add_options()
("modeltype", po::value<std::string>(), modeltypes.c_str())
("set-A,A", po::value<string>(&set_A), "Space separated set of trajectories to compare pair-wise to B")
("set-B,B", po::value<string>(&set_B), "Space separated set of trajectories to compare pair-wise to A")
("skip,k", po::value<uint>(&skip)->default_value(0), "Number of frames to skip in sub-trajectories")
("stride,i", po::value<uint>(&stride)->default_value(1), "Step through sub-trajectories by this amount")
("range,r", po::value<std::string>(&frame_index_spec), "Which frames to use in composite trajectory")
("noout,N", po::value<bool>(&noop)->default_value(false), "Do not output the matrix (i.e. only calc pair-wise RMSD stats)")
("threads", po::value<uint>(&nthreads)->default_value(1), "Number of threads to use (0=all available)")
("cutoff,c", po::value<float>(&cutoff)->default_value(-1.0), "Outputs fraction of frame-pairs below cutoff.")
("stats", po::value<bool>(&stats)->default_value(false), "Show some statistics for matrix")
("precision,p", po::value<uint>(&matrix_precision)->default_value(2), "Write out matrix coefficients with this many digits.");
}
void addHidden(po::options_description& opts) {
opts.add_options()
("model", po::value<std::string>(&model_name), "Model filename");
}
void addPositional(po::positional_options_description& pos) {
pos.add("model", 1);
}
bool check(po::variables_map& map) {
return( model_name.empty() || set_A.empty() || set_B.empty());
}
bool postConditions(po::variables_map& map) {
if (map.count("modeltype")) {
model_type = map["modeltype"].as<std::string>();
model = createSystem(model_name, model_type);
} else
model = createSystem(model_name);
// boost::split(results_vector, input_string, function_to_split_at(char c))
boost::split(trajlist_A, set_A, boost::is_any_of(" "));
boost::split(trajlist_B, set_B, boost::is_any_of(" "));
mtrajA = MultiTrajectory(trajlist_A, model, skip, stride);
mtrajB = MultiTrajectory(trajlist_B, model, skip, stride);
trajectory_A = pTraj(&mtrajA, boost::lambda::_1);
trajectory_B = pTraj(&mtrajB, boost::lambda::_1);
return true;
}
std::vector<uint> frameList(pTraj trajectory) const {
std::vector<uint> indices = assignTrajectoryFrames(trajectory, frame_index_spec, 0, 1);
return uniquifyVector(indices);
}
// There was an analogous call in multitrajectoryoptions, leaving it out for now to get other things working.
//std::string help() const { return("model trajectory [trajectory ...]"); }
std::string trajectoryTable(MultiTrajectory mtraj) const {
std::ostringstream oss;
if (!frame_index_spec.empty())
oss << "# Note- composite frame range used was '" << frame_index_spec << "'\n";
oss << "# traj\tstart\tend\tfilename\n";
uint start_cnt = 0;
uint j = 0;
for (uint i=0; i<mtraj.size(); ++i) {
uint n = mtraj.nframes(i);
if (n == 0)
oss << boost::format("# Warning- '%s' was skipped due to insufficient frames\n") % mtraj[i]->filename();
else {
oss << boost::format("# %d\t%d\t%d\t%s\n")
% j
% start_cnt
% (start_cnt + n - 1)
% mtraj[i]->filename();
++j;
}
start_cnt += n;
}
return oss.str();
}
string print() const {
ostringstream oss;
oss << boost::format("model='%s', modeltype='%s', skip=%d, stride=%d, trajlist_A=(")
% model_name % model_type % skip % stride;
for (uint i=0; i<trajlist_A.size(); i++)
oss << "'" << trajlist_A[i] << "'" << (i < trajlist_A.size() -1 ? "," : "");
oss << "), trajlist_B=(";
for (uint i=0; i<trajlist_B.size(); ++i)
oss << "'" << trajlist_B[i] << "'" << (i < trajlist_B.size() -1 ? "," : "");
oss << ")";
oss << boost::format("stats=%d,noout=%d,nthreads=%d,matrix_precision=%d")
% stats
% noop
% nthreads
% matrix_precision;
return(oss.str());
}
bool stats;
bool noop;
float cutoff;
uint nthreads;
std::string set_A;
std::string set_B;
std::vector<string> trajlist_A, trajlist_B;
uint skip;
uint stride;
uint matrix_precision;
string frame_index_spec;
string model_name, model_type;
AtomicGroup model;
MultiTrajectory mtrajA, mtrajB;
pTraj trajectory_A, trajectory_B;
};
typedef vector<double> vecDouble;
typedef vector<vecDouble> vMatrix;
// @endcond TOOLS_INTERNAL
// --------------------------------------------------------------------------------------
// Parcels out work to the compute threads... Work is given to the threads
// one row at a time.
class Master {
public:
Master(const uint nr, const bool tr, const bool b) : _toprow(0), _maxrow(nr), _updatefreq(500), _triangle(tr),
_verbose(b), _start_time(time(0))
{
if (_triangle)
_total = _maxrow*(_maxrow-1) / 2;
else
_total = _maxrow;
}
// Checks whether there are any columns left to work on
// and places the column index into the passed pointer.
bool workAvailable(uint* ip)
{
_mtx.lock();
if (_toprow >= _maxrow) {
_mtx.unlock();
return(false);
}
*ip = _toprow++;
if (_verbose)
if (_toprow % _updatefreq == 0)
updateStatus();
_mtx.unlock();
return(true);
}
void updateStatus() {
time_t dt = elapsedTime();
uint work_done = _triangle ? (_toprow * (_toprow-1) / 2) : (_toprow);
uint work_left = _total - work_done;
uint d = work_left * dt / work_done; // rate = work_done / dt; d = work_left / rate;
uint hrs = d / 3600;
uint remain = d % 3600;
uint mins = remain / 60;
uint secs = remain % 60;
cerr << boost::format("Row %5d /%5d, Elapsed = %5d s, Remaining = %02d:%02d:%02d\n")
% _toprow % _maxrow % dt % hrs % mins % secs;
}
time_t elapsedTime() const
{
return (time(0) - _start_time);
}
private:
uint _toprow, _maxrow;
uint _updatefreq;
bool _triangle;
bool _verbose;
time_t _start_time;
uint _total;
boost::mutex _mtx;
};
/*
Worker thread processes a column of the all-to-all matrix. Gets which
column to work on from the associated Master object.
*/
// Worker for self all-to-all
class SingleWorker
{
public:
SingleWorker(RealMatrix* R, vMatrix* TA, vMatrix* TB, Master* M) : _R(R), _TA(TA), _TB(TB), _M(M) { }
SingleWorker(const SingleWorker& w)
{
_R = w._R;
_TA = w._TA;
_TB = w._TB;
_M = w._M;
}
void calc(const uint i)
{
for (uint j=0; j<_R->cols(); ++j)
(*_R)(i, j) = loos::alignment::centeredRMSD((*_TA)[i], (*_TB)[j]);
}
void operator()()
{
uint i;
while (_M->workAvailable(&i))
calc(i);
}
private:
RealMatrix* _R;
vMatrix* _TA;
vMatrix* _TB;
Master* _M;
};
// Top level object/interface. Will create np Worker threads, cloned from the
// one passed into the constructor.
template<class W>
class Threader
{
public:
Threader(W* wrkr, const uint np) :
worker(wrkr),
threads(vector<Thread>(np))
{
for (uint i=0; i<np; ++i) {
W w(*worker);
threads[i] = new boost::thread(w);
}
}
void join()
{
for (uint i=0; i<threads.size(); ++i)
threads[i]->join();
}
~Threader()
{
for (uint i=0; i<threads.size(); ++i)
delete threads[i];
}
W* worker;
vector<Thread> threads;
};
// --------------------------------------------------------------------------------------
// just get max elt and avg like multi-rmsds.
void showStats(const RealMatrix& R) {
uint total = R.rows() * R.cols(); //matrix is not symmetric,
// must do calculation for each element.
double avg = 0.0;
double max = 0.0;
for (uint j=0; j<R.rows(); ++j)
for (uint i=0; i<R.cols(); ++i) {
avg += R(j, i);
if (R(j, i) > max)
max = R(j, i);
}
avg /= total;
cerr << boost::format("Max rmsd = %.4f, avg rmsd = %.4f\n") % max % avg;
}
void showFractionalStats(const RealMatrix& R, const float cutoff, const bool isNoop) {
uint total = R.size();
double avg = 0.0;
double var = 0.0; // squared component of variance operator <x>^2 - <x^2>
boost::tuple<uint, uint, double> max (0,0,0.0);
//max = boost::make_tuple(0,0,0.0);
long unsigned below_cut = 0;
// loop over the matrix
for (uint i=0; i<R.rows(); ++i)
for (uint j=0; j<R.cols(); ++j) {
if (i == j) // skip all the zeros in the diagonal
continue;
var += R(i, j)*R(i, j);
avg += R(i, j);
if (R(i, j) > boost::get<2>(max))
boost::get<0>(max) = i;
boost::get<1>(max) = j;
boost::get<2>(max) = R(i, j);
if (R(i,j) < cutoff)
below_cut++;
}
avg /= total;
var = var/total - avg*avg;
if (isNoop){
cout << boost::format("Max rmsd = %.4f between frames %d, %d, avg rmsd = %.4f, variance = %.4f, frames below %.4f = %d, total = %d\n")
% boost::get<2>(max)
% boost::get<0>(max)
% boost::get<1>(max)
% avg
% var
% cutoff
% below_cut
% total;
} else {
cerr << boost::format("Max rmsd = %.4f between frames %d, %d, avg rmsd = %.4f, variance = %.4f, frames below %.4f = %d, total = %d\n")
% boost::get<2>(max)
% boost::get<0>(max)
% boost::get<1>(max)
% avg
% var
% cutoff
% below_cut
% total;
}
}
void centerTrajectory(alignment::vecMatrix& U) {
for (uint i=0; i<U.size(); ++i)
alignment::centerAtOrigin(U[i]);
}
void checkMemoryUsage(long mem) {
if (!mem)
return;
double used = static_cast<double>(used_memory) / mem;
if (verbosity > 2)
cerr << boost::format("Memory: available=%d GB, estimated used=%.2f MB\n")
% (mem >> 30) % (static_cast<double>(used_memory) / (1lu<<20) );
if (used >= cache_memory_fraction_warning) {
cerr << boost::format("***WARNING***\nThe estimated memory used is %.1f%% (%d MB) of your total memory (%d GB).\n")
% (used * 100.0)
% (used_memory >> 20)
% (mem >> 30);
cerr << "If your machine starts swapping, try subsampling the trajectories\n";
}
}
int main(int argc, char *argv[]) {
string header = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::BasicSelection* sopts = new opts::BasicSelection("name == 'backbone' && ! hydrogen");
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(sopts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
verbosity = bopts->verbosity;
report_stats = (verbosity || topts->noop);
AtomicGroup model = topts->model;
AtomicGroup subset = selectAtoms(model, sopts->selection);
vector<uint> indices_A = topts->frameList(topts->trajectory_A);
vector<uint> indices_B = topts->frameList(topts->trajectory_B);
long mem = availableMemory();
uint nthreads = topts->nthreads ? topts->nthreads : boost::thread::hardware_concurrency();
if (verbosity > 1)
cerr << "Using " << nthreads << " threads\n";
// read in system A
vMatrix TA = readCoords(subset, topts->trajectory_A, indices_A, verbosity > 1);
// read in system B
vMatrix TB = readCoords(subset, topts->trajectory_B, indices_B, verbosity > 1);
used_memory += TA.size() * TA[0].size() * sizeof(vMatrix::value_type::value_type); // Coords matrix for A
used_memory += TB.size() * TB[0].size() * sizeof(vMatrix::value_type::value_type); // Coords matrix for B
used_memory += TA.size() * TB.size() * sizeof(RealMatrix::element_type); // RMSDS matrix
checkMemoryUsage(mem);
centerTrajectory(TA);
centerTrajectory(TB);
RealMatrix M;
if (verbosity > 1)
cerr << "Calculating RMSD...\n";
M = RealMatrix(TA.size(), TB.size());
// note the 'false' here causes master to do full matrix, not just triangle.
Master master(TA.size(), false, verbosity);
SingleWorker worker(&M, &TA, &TB, &master);
Threader<SingleWorker> threads(&worker, nthreads);
threads.join();
if (verbosity)
master.updateStatus();
if (verbosity || topts->noop || topts->stats || topts->cutoff > 0){
if (topts->cutoff > 0)
showFractionalStats(M, topts->cutoff, topts->noop);
else
showStats(M);
}
if (!topts->noop) {
cout << "# " << header << endl;
cout << topts->trajectoryTable(topts->mtrajA);
cout << topts->trajectoryTable(topts->mtrajB);
cout << setprecision(topts->matrix_precision) << M;
}
}
| 19,674
|
C++
|
.cpp
| 491
| 36.069246
| 139
| 0.658878
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,185
|
smooth-traj.cpp
|
GrossfieldLab_loos/Tools/smooth-traj.cpp
|
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2012, Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
using namespace std;
using namespace loos;
namespace opts = loos::OptionsFramework;
namespace po = loos::OptionsFramework::po;
// @cond TOOLS_INTERNAL
// Base class for handling different windowing functions
struct Window {
Window(const uint window_size) : _window_size(window_size) { }
virtual double weight(const uint t) const =0;
// Total weight for window
double sum() const {
double s = 0.0;
for (uint i=0; i<_window_size; ++i)
s += weight(i);
return(s);
}
uint _window_size;
};
struct UniformWindow : public Window {
UniformWindow(const uint n) : Window(n) { }
double weight(const uint t) const { return(1.0); }
};
struct CosineWindow : public Window {
CosineWindow(const uint n) : Window(n) { }
double weight(const uint t) const {
double d = static_cast<double>(t) / _window_size - 0.5;
return(cos(d * M_PI/2.0));
}
};
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tSmooths a trajectory by using a windowed-average\n"
"DESCRIPTION\n"
"\tsmooth-traj can reduce high-frequency motion in a trajectory by averaging together\n"
"frames of the trajectory within a sliding window. The weighting within the window is\n"
"determined by the weighting function. The window size determines how many frames are\n"
"included in the window (centered at a given frame) and the stride determines how far\n"
"the window is slid for each frame of the output trajectory. These options allow not\n"
"only smoothing, but also subsampling of the trajectory.\n"
"\n"
"EXAMPLES\n"
"\n"
"\tsmooth-traj model.pdb simulation.dcd\n"
"Smooths the trajectory \"simulation.dcd\" using the default window size of 10 frames\n"
"and a cosine-weighted window. The output has the default prefix \"smoothed\" and the\n"
"output trajectory has the same timestep as the original trajectory.\n"
"\n"
"\tsmooth-traj --window=100 --stride=100 model.pdb simulation.dcd\n"
"This smooths the trajectory using a window size of 100 frames. The window is moved\n"
"100 frames for each output timepoint. If the input trajectory has a timestep of 10ps,\n"
"then the output trajectory will have a timestep of 1ns and each output frame will have\n"
"been averaged over a window 1ns long, centered at the given frame's time.\n"
"\n";
return(msg);
}
class ToolOptions : public opts::OptionsPackage {
public:
ToolOptions() : weight_name("cos"),
window_size(10),
stride(1)
{ }
void addGeneric(po::options_description& o) {
o.add_options()
("weighting", po::value<string>(&weight_name)->default_value(weight_name), "Weighting method to use (cos|uniform)")
("window", po::value<uint>(&window_size)->default_value(window_size), "Size of window to average over")
("stride", po::value<uint>(&stride)->default_value(stride), "How may frames to skip per step")
("clip", po::value<bool>(&clip)->default_value(true), "Clip the ends of the trajectory ");
}
bool postConditions(po::variables_map& map)
{
if (weight_name == "cos")
window = new CosineWindow(window_size);
else if (weight_name == "uniform")
window = new UniformWindow(window_size);
else {
cerr << "Error- unknown weighting method '" << weight_name << "'.\n"
<< "Must be: cos, uniform\n";
return(false);
}
return(true);
}
string print() const {
ostringstream oss;
oss << boost::format("weighting='%s',size=%d,stride=%d,clip=%d")
% weight_name
% window_size
% stride
% clip;
return(oss.str());
}
string weight_name;
uint window_size, stride;
bool clip;
Window* window;
};
// @endcond
// ----------------------------------------------------------------------------------
void zeroCoords(AtomicGroup& model) {
for (AtomicGroup::iterator i = model.begin(); i != model.end(); ++i)
(*i)->coords(GCoord(0,0,0));
}
void addCoords(AtomicGroup& avg, const AtomicGroup model, const double scale) {
for (uint i=0; i<avg.size(); ++i)
avg[i]->coords() += scale * model[i]->coords();
}
void divideCoords(AtomicGroup& avg, const double d) {
for (AtomicGroup::iterator i = avg.begin(); i != avg.end(); ++i)
(*i)->coords() /= d;
}
// ----------------------------------------------------------------------------------
int main(int argc, char *argv[]) {
string hdr = invocationHeader(argc, argv);
opts::BasicOptions* bopts = new opts::BasicOptions(fullHelpMessage());
opts::OutputPrefix* prefopts = new opts::OutputPrefix("smoothed");
opts::BasicSelection* sopts = new opts::BasicSelection("!hydrogen");
opts::BasicTrajectory* tropts = new opts::BasicTrajectory;
opts::OutputTrajectoryTypeOptions* otopts = new opts::OutputTrajectoryTypeOptions;
ToolOptions* topts = new ToolOptions;
opts::AggregateOptions options;
options.add(bopts).add(prefopts).add(sopts).add(tropts).add(otopts).add(topts);
if (!options.parse(argc, argv))
exit(-1);
string output_name = prefopts->prefix;
AtomicGroup model = tropts->model;
pTraj traj = tropts->trajectory;
AtomicGroup subset = selectAtoms(model, sopts->selection);
int window_size = topts->window_size;
uint stride = topts->stride;
bool clip = topts->clip;
uint starting_frame = clip ? window_size/2 : 0;
uint ending_frame = traj->nframes() - (clip ? window_size/2 : 0);
Window* window = topts->window;
PDB pdb = PDB::fromAtomicGroup(subset);
pdb.remarks().add(hdr);
string pdb_name = output_name + ".pdb";
ofstream ofs(pdb_name.c_str());
ofs << pdb;
pTrajectoryWriter outtraj = otopts->createTrajectory(prefopts->prefix);
outtraj->setComments(hdr);
AtomicGroup frame = subset.copy();
for (uint j=starting_frame; j<ending_frame; j += stride) {
zeroCoords(frame);
double scaling = 0.0;
// Now average...
for (int wi = 0; wi < window_size; ++wi) {
double scale = window->weight(wi);
int t = j + wi - wi/2;
if (t < 0 || t >= traj->nframes())
continue;
traj->readFrame(t);
traj->updateGroupCoords(subset);
addCoords(frame, subset, scale);
scaling += window->weight(wi);
}
divideCoords(frame, scaling);
outtraj->writeFrame(frame);
}
}
| 7,249
|
C++
|
.cpp
| 177
| 36.214689
| 127
| 0.669054
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,186
|
rotamer.cpp
|
GrossfieldLab_loos/Tools/rotamer.cpp
|
/*
rotamer.cpp
Computes chi-1, chi-2 angles for selected side-chains. If the
requested angle doesn't exist, then -9999.99 is output as a marker.
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008 Tod D. Romo
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <loos.hpp>
#include <boost/format.hpp>
#include <boost/unordered_map.hpp>
#include <boost/algorithm/string.hpp>
#include <cmath>
#include <sstream>
#include <limits>
using namespace std;
using namespace loos;
const double null_value = -9999.99;
/// @cond TOOLS_INTERNAL
string fullHelpMessage(void) {
string msg =
"\n"
"SYNOPSIS\n"
"\tCalculate the chi-1 and chi-2 angles for selected side chains\n"
"\n"
"DESCRIPTION\n"
"\n"
"\tThis tool will calculate the chi-1 and chi-2 angles for the selected\n"
"side chains, writing them out as a time-series (matrix). For residues\n"
"where an angle does not exist, -9999.99 is written as a marker.\n"
"\n"
"EXAMPLES\n"
"\n"
"\trotamer model.pdb simulation.dcd 'resid >= 50 && resid <= 59' >data.asc\n"
"This example calculates chi-1 and chi-2 for residues 50 through 59.\n"
"\n"
"\trotamer model.pdb simulation.dcd 'segid == \"BAR2\"' >data.asc\n"
"This example calculates chi-1 and chi-2 for all residues in the \"BAR2\" segment.\n"
"\n"
"NOTES\n"
"\tThe selection must include all atoms in each residue necessary for determining\n"
"chi-1 and chi-2.\n"
"\n"
"SEE ALSO\n"
"\tramachandran\n";
return(msg);
}
// Interface for torsion calculation class.
class Torsion {
public:
virtual double torsion(void) =0;
virtual ~Torsion() { }
};
// This class records specific pAtoms and will calculate their torsion
// angle...
class TorsionedAtoms : public Torsion {
public:
TorsionedAtoms(pAtom a, pAtom b, pAtom c, pAtom d) {
atoms = a + b + c + d;
}
virtual ~TorsionedAtoms() { }
double torsion(void) { return(Math::torsion(atoms[0], atoms[1], atoms[2], atoms[3])); }
friend ostream& operator<<(ostream& os, const TorsionedAtoms& t) {
os << t.atoms;
return(os);
}
private:
AtomicGroup atoms;
};
// This class just returns the null_value... It's used when a torsion
// angle doesn't exist (i.e. chi-2 for Cys...)
class NoTorsion : public Torsion {
public:
double torsion(void) { return(null_value); }
virtual ~NoTorsion() { }
};
/// @endcond
// Utility function to pick a specific atom by name out of a group.
// It's overkill, but doing it this way does make it easy to note when
// a selection may be malformed and it only needs to be done once at
// startup...
pAtom pickAtom(const AtomicGroup& grp, const string& name) {
AtomNameSelector sel(name);
AtomicGroup pick = grp.select(sel);
pAtom atom;
if (pick.size() > 1)
cerr << boost::format("WARNING - found more than one %s in :\n%s\n") % name % grp;
if (pick.size() >= 1)
atom = pick[0];
else {
cerr << "ERROR - could not find " << name << " in:\n" << grp << endl;
exit(-10);
}
return(atom);
}
// Factory function for binding the torsion calculation to a group of
// atoms..
Torsion* torsionFactory(const AtomicGroup& grp, const string& a, const string& b, const string& c, const string& d) {
if (a == "-" || b == "-" || c == "-" || d == "-")
return(new NoTorsion());
return(new TorsionedAtoms(pickAtom(grp, a), pickAtom(grp, b), pickAtom(grp, c), pickAtom(grp, d)));
}
// ---------------------------------------------------------------
// Map of residues to chi-1, chi-2 atom lists. An atom name of "-"
// indicates that this angle can't be calculated. An entry of all "-"
// marks the end of the list...
string angle_mapping[][3] = {
{ "GLY", "-,-,-,-", "-,-,-,-" },
{ "ALA", "-,-,-,-", "-,-,-,-" },
{ "VAL", "N,CA,CB,CG1", "-,-,-,-" },
{ "LEU", "N,CA,CB,CG", "CA,CB,CG,CD1" },
{ "ILE", "N,CA,CB,CG1", "CA,CB,CG1,CD" },
{ "PRO", "N,CA,CB,CG", "CA,CB,CG,CD" },
{ "PHE", "N,CA,CB,CG", "CA,CB,CG,CD1" },
{ "TYR", "N,CA,CB,CG", "CA,CB,CG,CD1" },
{ "TRP", "N,CA,CB,CG", "CA,CB,CG,CD1" },
{ "SER", "N,CA,CB,OG", "-,-,-,-" },
{ "THR", "N,CA,CB,OG1", "-,-,-,-" },
{ "CYS", "N,CA,CB,SG", "-,-,-,-" },
{ "MET", "N,CA,CB,CG", "CA,CB,CG,SD" },
{ "MSE", "N,CA,CB,CG", "CA,CB,CG,SE" },
{ "LYS", "N,CA,CB,CG", "CA,CB,CG,CD" },
{ "HIS", "N,CA,CB,CG", "CA,CB,CG,ND1" },
{ "ARG", "N,CA,CB,CG", "CA,CB,CG,CD" },
{ "ASP", "N,CA,CB,CG", "CA,CB,CG,OD1" },
{ "ASN", "N,CA,CB,CG", "CA,CB,CG,OD1" },
{ "GLN", "N,CA,CB,CG", "CA,CB,CG,CD" },
{ "GLU", "N,CA,CB,CG", "CA,CB,CG,CD" },
{ "---", "-,-,-,-", "-,-,-,-" }
};
// @cond TOOLS_INTERNAL
// Convenience class for grouping 4 strings together...
struct DihedralAtoms {
DihedralAtoms() : a("-"), b("-"), c("-"), d("-") { }
DihedralAtoms(const string& sa, const string& sb, const string& sc, const string& sd) :
a(sa), b(sb), c(sc), d(sd) { }
DihedralAtoms(const DihedralAtoms& t) : a(t.a), b(t.b), c(t.c), d(t.d) { }
friend ostream& operator<<(ostream& os, const DihedralAtoms& t) {
os << boost::format("(%s,%s,%s,%s)") % t.a % t.b % t.c % t.d;
return(os);
}
string a, b, c, d;
};
// Mapping of residue names to the appropriate atoms for calculating
// torsion angles...
typedef boost::unordered_map<string, DihedralAtoms> ResidueDihedralAtoms;
ResidueDihedralAtoms Chi1Atoms;
ResidueDihedralAtoms Chi2Atoms;
// @endcond
// Initialize the maps...
void makeMaps(void) {
for (int i=0; angle_mapping[i][0] != "---"; ++i) {
vector<string> tokens;
string name = angle_mapping[i][0];
tokens = boost::split(tokens, angle_mapping[i][1], boost::is_any_of(","));
if (tokens.size() != 4)
throw(logic_error("Invalid count of dihedral atoms"));
Chi1Atoms[name] = DihedralAtoms(tokens[0], tokens[1], tokens[2], tokens[3]);
tokens.clear();
tokens = boost::split(tokens, angle_mapping[i][2], boost::is_any_of(","));
if (tokens.size() != 4)
throw(logic_error("Invalid count of dihedral atoms"));
Chi2Atoms[name] = DihedralAtoms(tokens[0], tokens[1], tokens[2], tokens[3]);
}
}
// Given a map of residue to torsion atoms, pull them out of the
// passed group and bind it to a torsion calculator...
Torsion* makeTorsion(const AtomicGroup& grp, ResidueDihedralAtoms& binding) {
// Note: G++ < 4.1 has a bug in tr1::unordered_map where there is no
// default constructor for the iterators, so we must use the CC to
// instantiate them... This also apparently causes an issue when
// trying to make binding const (and use a const_iterator)
ResidueDihedralAtoms::iterator i(binding.end());
string name = grp[0]->resname();
i = binding.find(name);
if (i == binding.end()) {
cerr << "ERROR - no torsion information available for " << name << endl;
exit(-20);
}
DihedralAtoms atoms = i->second;
return(torsionFactory(grp, atoms.a, atoms.b, atoms.c, atoms.d));
}
// ---------------------------------------------------------------
int main(int argc, char *argv[]) {
if (argc < 4) {
cerr << "Usage - rotamer model traj sel-1 [sel-2 ...] >output.asc\n";
cerr << fullHelpMessage();
exit(-1);
}
ostringstream sshdr;
sshdr << invocationHeader(argc, argv) << endl;
makeMaps();
AtomicGroup model = loos::createSystem(argv[1]);
pTraj traj = loos::createTrajectory(argv[2], model);
// Build the list of atoms/torsion angles to calculate...
vector<Torsion*> chi1;
vector<Torsion*> chi2;
uint idx = 2;
for (int i=3; i<argc; i++) {
AtomicGroup subset = loos::selectAtoms(model, argv[i]);
vector<AtomicGroup> residues = subset.splitByResidue();
for (uint j=0; j<residues.size(); ++j, idx += 2) {
sshdr << boost::format("# %d = %d %s %s %d %s%s")
% idx
% residues[j][0]->id()
% residues[j][0]->name()
% residues[j][0]->resname()
% residues[j][0]->resid()
% residues[j][0]->segid()
% (i == argc-1 && j == residues.size()-1 ? "" : "\n");
Torsion *x1 = makeTorsion(residues[j], Chi1Atoms);
Torsion *x2 = makeTorsion(residues[j], Chi2Atoms);
chi1.push_back(x1);
chi2.push_back(x2);
}
}
uint rows = traj->nframes();
uint n = chi1.size();
uint cols = 2 * n;
Math::Matrix<double, Math::RowMajor> M(rows, cols+1);
for (uint j=0; j<rows; ++j) {
traj->readFrame(j);
traj->updateGroupCoords(model);
M(j, 0) = j;
for (uint i = 0; i<n; i++) {
M(j, 2*i+1) = chi1[i]->torsion();
M(j, 2*i+2) = chi2[i]->torsion();
}
}
string hdr = sshdr.str();
writeAsciiMatrix(cout, M, hdr);
}
| 9,328
|
C++
|
.cpp
| 245
| 34.465306
| 117
| 0.626195
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
755,187
|
density-dist-windowed.cpp
|
GrossfieldLab_loos/Tools/density-dist-windowed.cpp
|
/*
density-dist-windowed.cpp
Compute the charge/mass/electron density along the z dimension of a system
*/
/*
This file is part of LOOS.
LOOS (Lightweight Object-Oriented Structure library)
Copyright (c) 2008, Alan Grossfield
Department of Biochemistry and Biophysics
School of Medicine & Dentistry, University of Rochester
This package (LOOS) is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
This package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <ctype.h>
#include <loos.hpp>
using namespace std;
using namespace loos;
void Usage()
{
cerr << "Usage: density-dist-windowed "
<< " system traj E|C|M num_frames_to_skip min_z max_z num_bins window_size"
<< " filename_prototype [extra_selection_1 ...]"
<< endl;
cerr << "Note: the system file must specify the mass and charge" << endl;
}
int main(int argc, char *argv[]) {
cout << "# This program is now deprecated: we suggest you use density-dist"
<< " with the --window option instead."
<< endl;
if ( (argc <= 1) ||
(strncmp(argv[1], "-h", 2) == 0) ||
(argc < 10) ) {
Usage();
exit(-1);
}
cout << "# " << invocationHeader(argc, argv) << endl;
AtomicGroup system = createSystem(argv[1]);
pTraj traj = createTrajectory(argv[2], system);
char calc_type = toupper(*argv[3]); // bad programmer, no cookie for you
int num_skip = atoi(argv[4]);
double min_z = atof(argv[5]);
double max_z = atof(argv[6]);
int num_bins = atoi(argv[7]);
int window = atoi(argv[8]);
string filename_proto = string(argv[9]);
bool do_charge = false;
bool do_mass = false;
bool do_elec = false;
// Figure out if we're doing charge, electron density, or mass
if (calc_type == 'C')
do_charge = true;
else if (calc_type == 'E')
do_elec = true;
else if (calc_type == 'M')
do_mass = true;
else
throw(runtime_error("calc type must be C, E, or M"));
// Add an arbitrary number of selections, and track the
// density from each selection
vector<AtomicGroup> subsets;
subsets.push_back(system);
for (int i=10; i<argc; i++) {
//Parser parser(argv[i]);
//KernelSelector parsed_sel(parser.kernel());
//AtomicGroup g = system.select(parsed_sel);
AtomicGroup g = selectAtoms(system, argv[i]);
subsets.push_back(g);
}
double bin_width = (max_z - min_z) / num_bins;
// Create and zero out the total charge_distribution
vector< vector<double> > dists;
dists.reserve(subsets.size());
for (unsigned int i=0; i<=subsets.size(); i++) {
vector<double> *v = new vector<double>;
v->insert(v->begin(), num_bins, 0.0);
dists.push_back(*v);
}
// skip the equilibration frames
if (num_skip > 0)
traj->readFrame(num_skip-1);
// loop over the remaining frames
int frame = 0;
while (traj->readFrame()) {
// update coordinates
traj->updateGroupCoords(system);
// Loop over the subsets and compute charge distribution.
// (first set is all atoms)
for (unsigned int i=0; i<subsets.size(); i++) {
pAtom pa;
AtomicGroup::Iterator iter(subsets[i]);
double weight=0.0;
while ( (pa = iter()) ) {
if (do_charge)
weight = pa->charge();
else if (do_mass)
weight = pa->mass();
else if (do_elec)
weight = pa->atomic_number() - pa->charge();
double z = pa->coords().z();
if ( (z > min_z) && (z < max_z) ) {
int bin = (int)( (z - min_z) / bin_width );
dists[i][bin] += weight;
}
}
}
frame++;
// output the results for this averaging window
if (frame % window == 0) {
int output_val = frame/window;
// set up the output file
char piece[128];
snprintf(piece, 128, "_%d.dat", output_val);
string filename = filename_proto + string(piece);
ofstream outfile(filename.c_str());
if (!outfile.is_open() ) {
throw(runtime_error("couldn't open output file"));
}
outfile << "# Z\tAllAtoms";
for (unsigned int i=1; i<subsets.size(); i++) {
outfile << " Set(" << i <<") ";
}
outfile << endl;
// Normalize by the number of frames and
// output the average density
for (int i=0; i<num_bins; i++) {
double z = (i+0.5)*bin_width + min_z;
outfile << z << "\t";
for (unsigned int j=0; j<subsets.size(); j++) {
double c = dists[j][i] / window;
outfile << c << "\t";
}
outfile << endl;
}
// zero out the distributions
vector< vector<double> >::iterator d;
for (d=dists.begin(); d!=dists.end(); d++) {
d->assign(d->size(), 0.0);
}
}
}
}
| 5,755
|
C++
|
.cpp
| 148
| 29.763514
| 84
| 0.560382
|
GrossfieldLab/loos
| 121
| 26
| 11
|
GPL-3.0
|
9/20/2024, 9:42:21 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.